47e7f306ea41965cc4980b7f49222527a9a9d088
[jalview.git] / src / jalview / structures / models / AAStructureBindingModel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.structures.models;
22
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureRenderer;
26 import jalview.api.SequenceRenderer;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.api.structures.JalviewStructureDisplayI;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.ext.rbvi.chimera.AtomSpecModel;
34 import jalview.ext.rbvi.chimera.ChimeraCommands;
35 import jalview.io.DataSourceType;
36 import jalview.renderer.seqfeatures.FeatureColourFinder;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.structure.AtomSpec;
39 import jalview.structure.StructureListener;
40 import jalview.structure.StructureMapping;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.Comparison;
43 import jalview.util.MessageManager;
44
45 import java.awt.Color;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.BitSet;
49 import java.util.Collections;
50 import java.util.Iterator;
51 import java.util.LinkedHashMap;
52 import java.util.List;
53 import java.util.Map;
54
55 /**
56  * 
57  * A base class to hold common function for protein structure model binding.
58  * Initial version created by refactoring JMol and Chimera binding models, but
59  * other structure viewers could in principle be accommodated in future.
60  * 
61  * @author gmcarstairs
62  *
63  */
64 public abstract class AAStructureBindingModel
65         extends SequenceStructureBindingModel
66         implements StructureListener, StructureSelectionManagerProvider
67 {
68
69   private StructureSelectionManager ssm;
70
71   /*
72    * distinct PDB entries (pdb files) associated
73    * with sequences
74    */
75   private PDBEntry[] pdbEntry;
76
77   /*
78    * sequences mapped to each pdbentry
79    */
80   private SequenceI[][] sequence;
81
82   /*
83    * array of target chains for sequences - tied to pdbentry and sequence[]
84    */
85   private String[][] chains;
86
87   /*
88    * datasource protocol for access to PDBEntrylatest
89    */
90   DataSourceType protocol = null;
91
92   protected boolean colourBySequence = true;
93
94   private boolean nucleotide;
95
96   private boolean finishedInit = false;
97
98   /**
99    * current set of model filenames loaded in the Jmol instance
100    */
101   protected String[] modelFileNames = null;
102
103   public String fileLoadingError;
104
105   private boolean showAlignmentOnly;
106
107   /*
108    * a list of chains "pdbid:chainid" to show in the viewer;
109    * empty means show all
110    */
111   // TODO make private once showStructures() deals with this
112   protected List<String> chainsToShow;
113
114   private boolean hideHiddenRegions;
115
116   /**
117    * Data bean class to simplify parameterisation in superposeStructures
118    */
119   protected class SuperposeData
120   {
121     /**
122      * Constructor with alignment width argument
123      * 
124      * @param width
125      */
126     public SuperposeData(int width)
127     {
128       pdbResNo = new int[width];
129     }
130
131     public String filename;
132
133     public String pdbId;
134
135     public String chain = "";
136
137     public boolean isRna;
138
139     /*
140      * The pdb residue number (if any) mapped to each column of the alignment
141      */
142     public int[] pdbResNo;
143   }
144
145   /**
146    * Constructor
147    * 
148    * @param ssm
149    * @param seqs
150    */
151   public AAStructureBindingModel(StructureSelectionManager ssm,
152           SequenceI[][] seqs)
153   {
154     this.ssm = ssm;
155     this.sequence = seqs;
156     chainsToShow = new ArrayList<>();
157   }
158
159   /**
160    * Constructor
161    * 
162    * @param ssm
163    * @param pdbentry
164    * @param sequenceIs
165    * @param protocol
166    */
167   public AAStructureBindingModel(StructureSelectionManager ssm,
168           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
169           DataSourceType protocol)
170   {
171     this.ssm = ssm;
172     this.sequence = sequenceIs;
173     this.nucleotide = Comparison.isNucleotide(sequenceIs);
174     this.pdbEntry = pdbentry;
175     this.protocol = protocol;
176     chainsToShow = new ArrayList<>();
177
178     resolveChains();
179   }
180
181   private boolean resolveChains()
182   {
183     /**
184      * final count of chain mappings discovered
185      */
186     int chainmaps = 0;
187     // JBPNote: JAL-2693 - this should be a list of chain mappings per
188     // [pdbentry][sequence]
189     String[][] newchains = new String[pdbEntry.length][];
190     int pe = 0;
191     for (PDBEntry pdb : pdbEntry)
192     {
193       SequenceI[] seqsForPdb = sequence[pe];
194       if (seqsForPdb != null)
195       {
196         newchains[pe] = new String[seqsForPdb.length];
197         int se = 0;
198         for (SequenceI asq : seqsForPdb)
199         {
200           String chain = (chains != null && chains[pe] != null)
201                   ? chains[pe][se]
202                   : null;
203           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
204                   : asq.getDatasetSequence();
205           if (sq.getAllPDBEntries() != null)
206           {
207             for (PDBEntry pdbentry : sq.getAllPDBEntries())
208             {
209               if (pdb.getFile() != null && pdbentry.getFile() != null
210                       && pdb.getFile().equals(pdbentry.getFile()))
211               {
212                 String chaincode = pdbentry.getChainCode();
213                 if (chaincode != null && chaincode.length() > 0)
214                 {
215                   chain = chaincode;
216                   chainmaps++;
217                   break;
218                 }
219               }
220             }
221           }
222           newchains[pe][se] = chain;
223           se++;
224         }
225         pe++;
226       }
227     }
228
229     chains = newchains;
230     return chainmaps > 0;
231   }
232   public StructureSelectionManager getSsm()
233   {
234     return ssm;
235   }
236
237   /**
238    * Returns the i'th PDBEntry (or null)
239    * 
240    * @param i
241    * @return
242    */
243   public PDBEntry getPdbEntry(int i)
244   {
245     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
246   }
247
248   /**
249    * Answers true if this binding includes the given PDB id, else false
250    * 
251    * @param pdbId
252    * @return
253    */
254   public boolean hasPdbId(String pdbId)
255   {
256     if (pdbEntry != null)
257     {
258       for (PDBEntry pdb : pdbEntry)
259       {
260         if (pdb.getId().equals(pdbId))
261         {
262           return true;
263         }
264       }
265     }
266     return false;
267   }
268
269   /**
270    * Returns the number of modelled PDB file entries.
271    * 
272    * @return
273    */
274   public int getPdbCount()
275   {
276     return pdbEntry == null ? 0 : pdbEntry.length;
277   }
278
279   public SequenceI[][] getSequence()
280   {
281     return sequence;
282   }
283
284   public String[][] getChains()
285   {
286     return chains;
287   }
288
289   public DataSourceType getProtocol()
290   {
291     return protocol;
292   }
293
294   // TODO may remove this if calling methods can be pulled up here
295   protected void setPdbentry(PDBEntry[] pdbentry)
296   {
297     this.pdbEntry = pdbentry;
298   }
299
300   protected void setSequence(SequenceI[][] sequence)
301   {
302     this.sequence = sequence;
303   }
304
305   protected void setChains(String[][] chains)
306   {
307     this.chains = chains;
308   }
309
310   /**
311    * Construct a title string for the viewer window based on the data Jalview
312    * knows about
313    * 
314    * @param viewerName
315    *          TODO
316    * @param verbose
317    * 
318    * @return
319    */
320   public String getViewerTitle(String viewerName, boolean verbose)
321   {
322     if (getSequence() == null || getSequence().length < 1
323             || getPdbCount() < 1 || getSequence()[0].length < 1)
324     {
325       return ("Jalview " + viewerName + " Window");
326     }
327     // TODO: give a more informative title when multiple structures are
328     // displayed.
329     StringBuilder title = new StringBuilder(64);
330     final PDBEntry pdbe = getPdbEntry(0);
331     title.append(viewerName + " view for " + getSequence()[0][0].getName()
332             + ":" + pdbe.getId());
333
334     if (verbose)
335     {
336       String method = (String) pdbe.getProperty("method");
337       if (method != null)
338       {
339         title.append(" Method: ").append(method);
340       }
341       String chain = (String) pdbe.getProperty("chains");
342       if (chain != null)
343       {
344         title.append(" Chain:").append(chain);
345       }
346     }
347     return title.toString();
348   }
349
350   /**
351    * Called by after closeViewer is called, to release any resources and
352    * references so they can be garbage collected. Override if needed.
353    */
354   protected void releaseUIResources()
355   {
356
357   }
358
359   public boolean isColourBySequence()
360   {
361     return colourBySequence;
362   }
363
364   public void setColourBySequence(boolean colourBySequence)
365   {
366     this.colourBySequence = colourBySequence;
367   }
368
369   protected void addSequenceAndChain(int pe, SequenceI[] seq,
370           String[] tchain)
371   {
372     if (pe < 0 || pe >= getPdbCount())
373     {
374       throw new Error(MessageManager.formatMessage(
375               "error.implementation_error_no_pdbentry_from_index",
376               new Object[]
377               { Integer.valueOf(pe).toString() }));
378     }
379     final String nullChain = "TheNullChain";
380     List<SequenceI> s = new ArrayList<>();
381     List<String> c = new ArrayList<>();
382     if (getChains() == null)
383     {
384       setChains(new String[getPdbCount()][]);
385     }
386     if (getSequence()[pe] != null)
387     {
388       for (int i = 0; i < getSequence()[pe].length; i++)
389       {
390         s.add(getSequence()[pe][i]);
391         if (getChains()[pe] != null)
392         {
393           if (i < getChains()[pe].length)
394           {
395             c.add(getChains()[pe][i]);
396           }
397           else
398           {
399             c.add(nullChain);
400           }
401         }
402         else
403         {
404           if (tchain != null && tchain.length > 0)
405           {
406             c.add(nullChain);
407           }
408         }
409       }
410     }
411     for (int i = 0; i < seq.length; i++)
412     {
413       if (!s.contains(seq[i]))
414       {
415         s.add(seq[i]);
416         if (tchain != null && i < tchain.length)
417         {
418           c.add(tchain[i] == null ? nullChain : tchain[i]);
419         }
420       }
421     }
422     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
423     getSequence()[pe] = tmp;
424     if (c.size() > 0)
425     {
426       String[] tch = c.toArray(new String[c.size()]);
427       for (int i = 0; i < tch.length; i++)
428       {
429         if (tch[i] == nullChain)
430         {
431           tch[i] = null;
432         }
433       }
434       getChains()[pe] = tch;
435     }
436     else
437     {
438       getChains()[pe] = null;
439     }
440   }
441
442   /**
443    * add structures and any known sequence associations
444    * 
445    * @returns the pdb entries added to the current set.
446    */
447   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
448           SequenceI[][] seq, String[][] chns)
449   {
450     List<PDBEntry> v = new ArrayList<>();
451     List<int[]> rtn = new ArrayList<>();
452     for (int i = 0; i < getPdbCount(); i++)
453     {
454       v.add(getPdbEntry(i));
455     }
456     for (int i = 0; i < pdbe.length; i++)
457     {
458       int r = v.indexOf(pdbe[i]);
459       if (r == -1 || r >= getPdbCount())
460       {
461         rtn.add(new int[] { v.size(), i });
462         v.add(pdbe[i]);
463       }
464       else
465       {
466         // just make sure the sequence/chain entries are all up to date
467         addSequenceAndChain(r, seq[i], chns[i]);
468       }
469     }
470     pdbe = v.toArray(new PDBEntry[v.size()]);
471     setPdbentry(pdbe);
472     if (rtn.size() > 0)
473     {
474       // expand the tied sequence[] and string[] arrays
475       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
476       String[][] sch = new String[getPdbCount()][];
477       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
478       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
479       setSequence(sqs);
480       setChains(sch);
481       pdbe = new PDBEntry[rtn.size()];
482       for (int r = 0; r < pdbe.length; r++)
483       {
484         int[] stri = (rtn.get(r));
485         // record the pdb file as a new addition
486         pdbe[r] = getPdbEntry(stri[0]);
487         // and add the new sequence/chain entries
488         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
489       }
490     }
491     else
492     {
493       pdbe = null;
494     }
495     return pdbe;
496   }
497
498   /**
499    * Add sequences to the pe'th pdbentry's sequence set.
500    * 
501    * @param pe
502    * @param seq
503    */
504   public void addSequence(int pe, SequenceI[] seq)
505   {
506     addSequenceAndChain(pe, seq, null);
507   }
508
509   /**
510    * add the given sequences to the mapping scope for the given pdb file handle
511    * 
512    * @param pdbFile
513    *          - pdbFile identifier
514    * @param seq
515    *          - set of sequences it can be mapped to
516    */
517   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
518   {
519     for (int pe = 0; pe < getPdbCount(); pe++)
520     {
521       if (getPdbEntry(pe).getFile().equals(pdbFile))
522       {
523         addSequence(pe, seq);
524       }
525     }
526   }
527
528   @Override
529   public abstract void highlightAtoms(List<AtomSpec> atoms);
530
531   protected boolean isNucleotide()
532   {
533     return this.nucleotide;
534   }
535
536   /**
537    * Returns a readable description of all mappings for the wrapped pdbfile to
538    * any mapped sequences
539    * 
540    * @param pdbfile
541    * @param seqs
542    * @return
543    */
544   public String printMappings()
545   {
546     if (pdbEntry == null)
547     {
548       return "";
549     }
550     StringBuilder sb = new StringBuilder(128);
551     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
552     {
553       String pdbfile = getPdbEntry(pdbe).getFile();
554       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
555       sb.append(getSsm().printMappings(pdbfile, seqs));
556     }
557     return sb.toString();
558   }
559
560   /**
561    * Returns the mapped structure position for a given aligned column of a given
562    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
563    * not mapped to structure.
564    * 
565    * @param seq
566    * @param alignedPos
567    * @param mapping
568    * @return
569    */
570   protected int getMappedPosition(SequenceI seq, int alignedPos,
571           StructureMapping mapping)
572   {
573     if (alignedPos >= seq.getLength())
574     {
575       return -1;
576     }
577
578     if (Comparison.isGap(seq.getCharAt(alignedPos)))
579     {
580       return -1;
581     }
582     int seqPos = seq.findPosition(alignedPos);
583     int pos = mapping.getPDBResNum(seqPos);
584     return pos;
585   }
586
587   /**
588    * Helper method to identify residues that can participate in a structure
589    * superposition command. For each structure, identify a sequence in the
590    * alignment which is mapped to the structure. Identify non-gapped columns in
591    * the sequence which have a mapping to a residue in the structure. Returns
592    * the index of the first structure that has a mapping to the alignment.
593    * 
594    * @param alignment
595    *          the sequence alignment which is the basis of structure
596    *          superposition
597    * @param matched
598    *          a BitSet, where bit j is set to indicate that every structure has
599    *          a mapped residue present in column j (so the column can
600    *          participate in structure alignment)
601    * @param structures
602    *          an array of data beans corresponding to pdb file index
603    * @return
604    */
605   protected int findSuperposableResidues(AlignmentI alignment,
606           BitSet matched, SuperposeData[] structures)
607   {
608     int refStructure = -1;
609     String[] files = getStructureFiles();
610     if (files == null)
611     {
612       return -1;
613     }
614     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
615     {
616       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
617       int lastPos = -1;
618
619       /*
620        * Find the first mapped sequence (if any) for this PDB entry which is in
621        * the alignment
622        */
623       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
624       for (int s = 0; s < seqCountForPdbFile; s++)
625       {
626         for (StructureMapping mapping : mappings)
627         {
628           final SequenceI theSequence = getSequence()[pdbfnum][s];
629           if (mapping.getSequence() == theSequence
630                   && alignment.findIndex(theSequence) > -1)
631           {
632             if (refStructure < 0)
633             {
634               refStructure = pdbfnum;
635             }
636             for (int r = 0; r < alignment.getWidth(); r++)
637             {
638               if (!matched.get(r))
639               {
640                 continue;
641               }
642               int pos = getMappedPosition(theSequence, r, mapping);
643               if (pos < 1 || pos == lastPos)
644               {
645                 matched.clear(r);
646                 continue;
647               }
648               lastPos = pos;
649               structures[pdbfnum].pdbResNo[r] = pos;
650             }
651             String chain = mapping.getChain();
652             if (chain != null && chain.trim().length() > 0)
653             {
654               structures[pdbfnum].chain = chain;
655             }
656             structures[pdbfnum].pdbId = mapping.getPdbId();
657             structures[pdbfnum].isRna = theSequence.getRNA() != null;
658
659             /*
660              * move on to next pdb file (ignore sequences for other chains
661              * for the same structure)
662              */
663             s = seqCountForPdbFile;
664             break;
665           }
666         }
667       }
668     }
669     return refStructure;
670   }
671
672   /**
673    * Returns true if the structure viewer has loaded all of the files of
674    * interest (identified by the file mapping having been set up), or false if
675    * any are still not loaded after a timeout interval.
676    * 
677    * @param files
678    */
679   protected boolean waitForFileLoad(String[] files)
680   {
681     /*
682      * give up after 10 secs plus 1 sec per file
683      */
684     long starttime = System.currentTimeMillis();
685     long endTime = 10000 + 1000 * files.length + starttime;
686     String notLoaded = null;
687
688     boolean waiting = true;
689     while (waiting && System.currentTimeMillis() < endTime)
690     {
691       waiting = false;
692       for (String file : files)
693       {
694         notLoaded = file;
695         if (file == null)
696         {
697           continue;
698         }
699         try
700         {
701           StructureMapping[] sm = getSsm().getMapping(file);
702           if (sm == null || sm.length == 0)
703           {
704             waiting = true;
705           }
706         } catch (Throwable x)
707         {
708           waiting = true;
709         }
710       }
711     }
712
713     if (waiting)
714     {
715       System.err.println(
716               "Timed out waiting for structure viewer to load file "
717                       + notLoaded);
718       return false;
719     }
720     return true;
721   }
722
723   @Override
724   public boolean isListeningFor(SequenceI seq)
725   {
726     if (sequence != null)
727     {
728       for (SequenceI[] seqs : sequence)
729       {
730         if (seqs != null)
731         {
732           for (SequenceI s : seqs)
733           {
734             if (s == seq || (s.getDatasetSequence() != null
735                     && s.getDatasetSequence() == seq.getDatasetSequence()))
736             {
737               return true;
738             }
739           }
740         }
741       }
742     }
743     return false;
744   }
745
746   public boolean isFinishedInit()
747   {
748     return finishedInit;
749   }
750
751   public void setFinishedInit(boolean fi)
752   {
753     this.finishedInit = fi;
754   }
755
756   /**
757    * Returns a list of chains mapped in this viewer.
758    * 
759    * @return
760    */
761   public abstract List<String> getChainNames();
762
763   /**
764    * Returns the Jalview panel hosting the structure viewer (if any)
765    * 
766    * @return
767    */
768   public JalviewStructureDisplayI getViewer()
769   {
770     return null;
771   }
772
773   public abstract void setJalviewColourScheme(ColourSchemeI cs);
774
775   /**
776    * Constructs and sends a command to align structures against a reference
777    * structure, based on one or more sequence alignments. May optionally return
778    * an error or warning message for the alignment command.
779    * 
780    * @param alignments
781    *          an array of alignments to process
782    * @param structureIndices
783    *          an array of corresponding reference structures (index into pdb
784    *          file array); if a negative value is passed, the first PDB file
785    *          mapped to an alignment sequence is used as the reference for
786    *          superposition
787    * @param hiddenCols
788    *          an array of corresponding hidden columns for each alignment
789    * @return
790    */
791   public abstract String superposeStructures(AlignmentI[] alignments,
792           int[] structureIndices, HiddenColumns[] hiddenCols);
793
794   public abstract void setBackgroundColour(Color col);
795
796   protected abstract String[] getColourBySequenceCommands(
797           String[] files, AlignmentViewPanel avp);
798
799   /**
800    * returns the current sequenceRenderer that should be used to colour the
801    * structures
802    * 
803    * @param alignment
804    * 
805    * @return
806    */
807   public abstract SequenceRenderer getSequenceRenderer(
808           AlignmentViewPanel alignment);
809
810   protected abstract void colourBySequence(
811           String[] colourBySequenceCommands);
812
813   public abstract void colourByChain();
814
815   public abstract void colourByCharge();
816
817   /**
818    * Recolours the displayed structures, if they are coloured by sequence, or
819    * 'show only visible alignment' is selected. This supports updating structure
820    * colours on either change of alignment colours, or change to the visible
821    * region of the alignment.
822    */
823   public void updateStructureColours(AlignmentViewPanel alignmentv)
824   {
825     if (!isLoadingFinished())
826     {
827       return;
828     }
829
830     /*
831      * if structure is not coloured by sequence, but restricted to the alignment,
832      * then redraw it (but don't recolour it) in case hidden regions have changed
833      * (todo: specific messaging for change of hidden region only)
834      */
835     if (!colourBySequence)
836     {
837       if (isShowAlignmentOnly())
838       {
839         showStructures(alignmentv.getAlignViewport(), false);
840       }
841       return;
842     }
843     if (getSsm() == null)
844     {
845       return;
846     }
847     String[] files = getStructureFiles();
848
849     String[] colourBySequenceCommands = getColourBySequenceCommands(
850             files, alignmentv);
851     colourBySequence(colourBySequenceCommands);
852   }
853
854   public boolean hasFileLoadingError()
855   {
856     return fileLoadingError != null && fileLoadingError.length() > 0;
857   }
858
859   public abstract jalview.api.FeatureRenderer getFeatureRenderer(
860           AlignmentViewPanel alignment);
861
862   /**
863    * Sets the flag for whether only mapped visible residues in the alignment
864    * should be visible in the structure viewer
865    * 
866    * @param b
867    */
868   public void setShowAlignmentOnly(boolean b)
869   {
870     showAlignmentOnly = b;
871   }
872
873   /**
874    * Answers true if only residues mapped to the alignment should be shown in the
875    * structure viewer, else false
876    * 
877    * @return
878    */
879   public boolean isShowAlignmentOnly()
880   {
881     return showAlignmentOnly;
882   }
883
884   /**
885    * Sets the flag for hiding regions of structure which are hidden in the
886    * alignment (only applies when the structure viewer is restricted to the
887    * alignment only)
888    * 
889    * @param b
890    */
891   public void setHideHiddenRegions(boolean b)
892   {
893     hideHiddenRegions = b;
894   }
895
896   /**
897    * Answers true if regions hidden in the alignment should also be hidden in the
898    * structure viewer, else false (only applies when the structure viewer is
899    * restricted to the alignment only)
900    * 
901    * @return
902    */
903   public boolean isHideHiddenRegions()
904   {
905     return hideHiddenRegions;
906   }
907
908   /**
909    * Shows the structures in the viewer, without changing their colouring. This is
910    * to support toggling of whether the whole structure is shown, or only residues
911    * mapped to visible regions of the alignment.
912    * 
913    * @param alignViewportI
914    * @param refocus
915    *                         if true, refit the display to the viewer
916    */
917   public void showStructures(AlignViewportI alignViewportI, boolean refocus)
918   {
919     // override with implementation
920   }
921
922   @Override
923   public void updateColours(Object source)
924   {
925     AlignmentViewPanel ap = (AlignmentViewPanel) source;
926     // ignore events from panels not used to colour this view
927     if (!getViewer().isUsedforcolourby(ap))
928     {
929       return;
930     }
931     if (!isLoadingFromArchive())
932     {
933       updateStructureColours(ap);
934     }
935   }
936
937   /**
938    * Sets the list of chains to display (as "pdbid:chain"), where an empty list
939    * means show all
940    * 
941    * @param chains
942    */
943   public void setChainsToShow(List<String> chains)
944   {
945     chainsToShow = chains;
946   }
947
948   /**
949    * Answers true if the specified structure and chain are selected to be shown in
950    * the viewer, else false
951    * 
952    * @param pdbId
953    * @param chainId
954    * @return
955    */
956   protected boolean isShowChain(String pdbId, String chainId)
957   {
958     if (chainsToShow.isEmpty())
959     {
960       return true;
961     }
962     return chainsToShow.contains(pdbId + ":" + chainId);
963   }
964
965   @Override
966   public abstract String[] getStructureFiles();
967
968   /**
969    * Builds a model of residues mapped from sequences to show on structure, taking
970    * into account user choices of
971    * <ul>
972    * <li>which chains are shown</li>
973    * <li>whether all structure is shown, or only that mapped to the alignment</li>
974    * <li>whether hidden regions of the alignment are hidden (excluded) or grayed
975    * out (included)</li>
976    * </ul>
977    * 
978    * @param av
979    * @return
980    */
981   protected AtomSpecModel getShownResidues(AlignViewportI av)
982   {
983     AlignmentI alignment = av.getAlignment();
984     final int width = alignment.getWidth();
985   
986     String[] files = getStructureFiles();
987   
988     AtomSpecModel model = new AtomSpecModel();
989   
990     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
991     {
992       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
993   
994       /*
995        * Find the first mapped sequence (if any) for this PDB entry which is in
996        * the alignment
997        */
998       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
999       for (int s = 0; s < seqCountForPdbFile; s++)
1000       {
1001         for (StructureMapping mapping : mappings)
1002         {
1003           final SequenceI theSequence = getSequence()[pdbfnum][s];
1004           if (mapping.getSequence() == theSequence
1005                   && alignment.findIndex(theSequence) > -1)
1006           {
1007             String chainCd = mapping.getChain();
1008             if (!isShowChain(mapping.getPdbId(), chainCd))
1009             {
1010               continue;
1011             }
1012             Iterator<int[]> visible;
1013             if (isShowAlignmentOnly() && isHideHiddenRegions())
1014             {
1015               visible = alignment.getHiddenColumns()
1016                     .getVisContigsIterator(0, width, true);
1017             }
1018             else
1019             {
1020               visible = Collections.singletonList(new int[] { 0, width })
1021                       .iterator();
1022             }
1023             while (visible.hasNext())
1024             {
1025               int[] visibleRegion = visible.next();
1026               int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1027               int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1028               List<int[]> residueRanges = mapping
1029                       .getPDBResNumRanges(seqStartPos, seqEndPos);
1030               if (!residueRanges.isEmpty())
1031               {
1032                 for (int[] range : residueRanges)
1033                 {
1034                   model.addRange(pdbfnum, range[0], range[1], chainCd);
1035                 }
1036               }
1037             }
1038           }
1039         }
1040       }
1041     }
1042   
1043     return model;
1044   }
1045
1046   /**
1047    * Answers a default structure model specification which is simply the string
1048    * form of the model number. Override if needed to specify submodels.
1049    * 
1050    * @param model
1051    * @return
1052    */
1053   public String getModelSpec(int model)
1054   {
1055     return String.valueOf(model);
1056   }
1057
1058   /**
1059    * Build a data structure which records contiguous subsequences for each colour.
1060    * From this we can easily generate the Chimera command for colour by sequence.
1061    * 
1062    * <pre>
1063    * Color
1064    *     Model number
1065    *         Chain
1066    *             list of start/end ranges
1067    * </pre>
1068    * 
1069    * Ordering is by order of addition (for colours and positions), natural
1070    * ordering (for models and chains)
1071    * 
1072    * @param viewPanel
1073    * @return
1074    */
1075   public Map<Object, AtomSpecModel> buildColoursMap(
1076           AlignmentViewPanel viewPanel)
1077   {
1078     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1079     FeatureColourFinder finder = new FeatureColourFinder(fr);
1080     AlignViewportI viewport = viewPanel.getAlignViewport();
1081     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1082     AlignmentI al = viewport.getAlignment();
1083     SequenceRenderer sr = getSequenceRenderer(viewPanel);
1084     String[] files = getStructureFiles();
1085     
1086     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1087     Color lastColour = null;
1088   
1089     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1090     {
1091       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1092   
1093       if (mapping == null || mapping.length < 1)
1094       {
1095         continue;
1096       }
1097   
1098       int startPos = -1, lastPos = -1;
1099       String lastChain = "";
1100       for (int s = 0; s < sequence[pdbfnum].length; s++)
1101       {
1102         for (int sp, m = 0; m < mapping.length; m++)
1103         {
1104           final SequenceI seq = sequence[pdbfnum][s];
1105           if (mapping[m].getSequence() == seq
1106                   && (sp = al.findIndex(seq)) > -1)
1107           {
1108             SequenceI asp = al.getSequenceAt(sp);
1109             for (int r = 0; r < asp.getLength(); r++)
1110             {
1111               // no mapping to gaps in sequence
1112               if (Comparison.isGap(asp.getCharAt(r)))
1113               {
1114                 continue;
1115               }
1116               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1117   
1118               if (pos < 1 || pos == lastPos)
1119               {
1120                 continue;
1121               }
1122   
1123               Color colour = sr.getResidueColour(seq, r, finder);
1124   
1125               /*
1126                * hidden regions are shown gray or, optionally, ignored
1127                */
1128               if (!cs.isVisible(r))
1129               {
1130                 if (hideHiddenRegions)
1131                 {
1132                   continue;
1133                 }
1134                 else
1135                 {
1136                   colour = Color.GRAY;
1137                 }
1138               }
1139   
1140               final String chain = mapping[m].getChain();
1141   
1142               /*
1143                * Just keep incrementing the end position for this colour range
1144                * _unless_ colour, PDB model or chain has changed, or there is a
1145                * gap in the mapped residue sequence
1146                */
1147               final boolean newColour = !colour.equals(lastColour);
1148               final boolean nonContig = lastPos + 1 != pos;
1149               final boolean newChain = !chain.equals(lastChain);
1150               if (newColour || nonContig || newChain)
1151               {
1152                 if (startPos != -1)
1153                 {
1154                   ChimeraCommands.addAtomSpecRange(colourMap, lastColour,
1155                           pdbfnum, startPos,
1156                           lastPos, lastChain);
1157                 }
1158                 startPos = pos;
1159               }
1160               lastColour = colour;
1161               lastPos = pos;
1162               lastChain = chain;
1163             }
1164             // final colour range
1165             if (lastColour != null)
1166             {
1167               ChimeraCommands.addAtomSpecRange(colourMap, lastColour,
1168                       pdbfnum,
1169                       startPos, lastPos, lastChain);
1170             }
1171             // break;
1172           }
1173         }
1174       }
1175     }
1176     return colourMap;
1177   }
1178 }