JAL-2430 colour columns hidden in alignment gray on structure
[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.ColumnSelection;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.DataSourceType;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureListener;
37 import jalview.structure.StructureMapping;
38 import jalview.structure.StructureMappingcommandSet;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.MessageManager;
42
43 import java.awt.Color;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.BitSet;
47 import java.util.List;
48
49 /**
50  * 
51  * A base class to hold common function for protein structure model binding.
52  * Initial version created by refactoring JMol and Chimera binding models, but
53  * other structure viewers could in principle be accommodated in future.
54  * 
55  * @author gmcarstairs
56  *
57  */
58 public abstract class AAStructureBindingModel extends
59         SequenceStructureBindingModel implements StructureListener,
60         StructureSelectionManagerProvider
61 {
62
63   private StructureSelectionManager ssm;
64
65   /*
66    * distinct PDB entries (pdb files) associated
67    * with sequences
68    */
69   private PDBEntry[] pdbEntry;
70
71   /*
72    * sequences mapped to each pdbentry
73    */
74   private SequenceI[][] sequence;
75
76   /*
77    * array of target chains for sequences - tied to pdbentry and sequence[]
78    */
79   private String[][] chains;
80
81   /*
82    * datasource protocol for access to PDBEntrylatest
83    */
84   DataSourceType protocol = null;
85
86   protected boolean colourBySequence = true;
87
88   private boolean nucleotide;
89
90   private boolean finishedInit = false;
91
92   /**
93    * current set of model filenames loaded in the Jmol instance
94    */
95   protected String[] modelFileNames = null;
96
97   public String fileLoadingError;
98
99   /**
100    * Data bean class to simplify parameterisation in superposeStructures
101    */
102   protected class SuperposeData
103   {
104     /**
105      * Constructor with alignment width argument
106      * 
107      * @param width
108      */
109     public SuperposeData(int width)
110     {
111       pdbResNo = new int[width];
112     }
113
114     public String filename;
115
116     public String pdbId;
117
118     public String chain = "";
119
120     public boolean isRna;
121
122     /*
123      * The pdb residue number (if any) mapped to each column of the alignment
124      */
125     public int[] pdbResNo;
126   }
127
128   /**
129    * Constructor
130    * 
131    * @param ssm
132    * @param seqs
133    */
134   public AAStructureBindingModel(StructureSelectionManager ssm,
135           SequenceI[][] seqs)
136   {
137     this.ssm = ssm;
138     this.sequence = seqs;
139   }
140
141   /**
142    * Constructor
143    * 
144    * @param ssm
145    * @param pdbentry
146    * @param sequenceIs
147    * @param chains
148    * @param protocol
149    */
150   public AAStructureBindingModel(StructureSelectionManager ssm,
151           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
152           DataSourceType protocol)
153   {
154     this.ssm = ssm;
155     this.sequence = sequenceIs;
156     this.nucleotide = Comparison.isNucleotide(sequenceIs);
157     this.pdbEntry = pdbentry;
158     this.protocol = protocol;
159   }
160
161   public StructureSelectionManager getSsm()
162   {
163     return ssm;
164   }
165
166   /**
167    * Returns the i'th PDBEntry (or null)
168    * 
169    * @param i
170    * @return
171    */
172   public PDBEntry getPdbEntry(int i)
173   {
174     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
175   }
176
177   /**
178    * Answers true if this binding includes the given PDB id, else false
179    * 
180    * @param pdbId
181    * @return
182    */
183   public boolean hasPdbId(String pdbId)
184   {
185     if (pdbEntry != null)
186     {
187       for (PDBEntry pdb : pdbEntry)
188       {
189         if (pdb.getId().equals(pdbId))
190         {
191           return true;
192         }
193       }
194     }
195     return false;
196   }
197
198   /**
199    * Returns the number of modelled PDB file entries.
200    * 
201    * @return
202    */
203   public int getPdbCount()
204   {
205     return pdbEntry == null ? 0 : pdbEntry.length;
206   }
207
208   public SequenceI[][] getSequence()
209   {
210     return sequence;
211   }
212
213   public String[][] getChains()
214   {
215     return chains;
216   }
217
218   public DataSourceType getProtocol()
219   {
220     return protocol;
221   }
222
223   // TODO may remove this if calling methods can be pulled up here
224   protected void setPdbentry(PDBEntry[] pdbentry)
225   {
226     this.pdbEntry = pdbentry;
227   }
228
229   protected void setSequence(SequenceI[][] sequence)
230   {
231     this.sequence = sequence;
232   }
233
234   protected void setChains(String[][] chains)
235   {
236     this.chains = chains;
237   }
238
239   /**
240    * Construct a title string for the viewer window based on the data Jalview
241    * knows about
242    * 
243    * @param viewerName
244    *          TODO
245    * @param verbose
246    * 
247    * @return
248    */
249   public String getViewerTitle(String viewerName, boolean verbose)
250   {
251     if (getSequence() == null || getSequence().length < 1
252             || getPdbCount() < 1 || getSequence()[0].length < 1)
253     {
254       return ("Jalview " + viewerName + " Window");
255     }
256     // TODO: give a more informative title when multiple structures are
257     // displayed.
258     StringBuilder title = new StringBuilder(64);
259     final PDBEntry pdbe = getPdbEntry(0);
260     title.append(viewerName + " view for " + getSequence()[0][0].getName()
261             + ":" + pdbe.getId());
262
263     if (verbose)
264     {
265       String method = (String) pdbe.getProperty("method");
266       if (method != null)
267       {
268         title.append(" Method: ").append(method);
269       }
270       String chain = (String) pdbe.getProperty("chains");
271       if (chain != null)
272       {
273         title.append(" Chain:").append(chain);
274       }
275     }
276     return title.toString();
277   }
278
279   /**
280    * Called by after closeViewer is called, to release any resources and
281    * references so they can be garbage collected. Override if needed.
282    */
283   protected void releaseUIResources()
284   {
285
286   }
287
288   public boolean isColourBySequence()
289   {
290     return colourBySequence;
291   }
292
293   public void setColourBySequence(boolean colourBySequence)
294   {
295     this.colourBySequence = colourBySequence;
296   }
297
298   protected void addSequenceAndChain(int pe, SequenceI[] seq,
299           String[] tchain)
300   {
301     if (pe < 0 || pe >= getPdbCount())
302     {
303       throw new Error(MessageManager.formatMessage(
304               "error.implementation_error_no_pdbentry_from_index",
305               new Object[] { Integer.valueOf(pe).toString() }));
306     }
307     final String nullChain = "TheNullChain";
308     List<SequenceI> s = new ArrayList<SequenceI>();
309     List<String> c = new ArrayList<String>();
310     if (getChains() == null)
311     {
312       setChains(new String[getPdbCount()][]);
313     }
314     if (getSequence()[pe] != null)
315     {
316       for (int i = 0; i < getSequence()[pe].length; i++)
317       {
318         s.add(getSequence()[pe][i]);
319         if (getChains()[pe] != null)
320         {
321           if (i < getChains()[pe].length)
322           {
323             c.add(getChains()[pe][i]);
324           }
325           else
326           {
327             c.add(nullChain);
328           }
329         }
330         else
331         {
332           if (tchain != null && tchain.length > 0)
333           {
334             c.add(nullChain);
335           }
336         }
337       }
338     }
339     for (int i = 0; i < seq.length; i++)
340     {
341       if (!s.contains(seq[i]))
342       {
343         s.add(seq[i]);
344         if (tchain != null && i < tchain.length)
345         {
346           c.add(tchain[i] == null ? nullChain : tchain[i]);
347         }
348       }
349     }
350     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
351     getSequence()[pe] = tmp;
352     if (c.size() > 0)
353     {
354       String[] tch = c.toArray(new String[c.size()]);
355       for (int i = 0; i < tch.length; i++)
356       {
357         if (tch[i] == nullChain)
358         {
359           tch[i] = null;
360         }
361       }
362       getChains()[pe] = tch;
363     }
364     else
365     {
366       getChains()[pe] = null;
367     }
368   }
369
370   /**
371    * add structures and any known sequence associations
372    * 
373    * @returns the pdb entries added to the current set.
374    */
375   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
376           SequenceI[][] seq, String[][] chns)
377   {
378     List<PDBEntry> v = new ArrayList<PDBEntry>();
379     List<int[]> rtn = new ArrayList<int[]>();
380     for (int i = 0; i < getPdbCount(); i++)
381     {
382       v.add(getPdbEntry(i));
383     }
384     for (int i = 0; i < pdbe.length; i++)
385     {
386       int r = v.indexOf(pdbe[i]);
387       if (r == -1 || r >= getPdbCount())
388       {
389         rtn.add(new int[] { v.size(), i });
390         v.add(pdbe[i]);
391       }
392       else
393       {
394         // just make sure the sequence/chain entries are all up to date
395         addSequenceAndChain(r, seq[i], chns[i]);
396       }
397     }
398     pdbe = v.toArray(new PDBEntry[v.size()]);
399     setPdbentry(pdbe);
400     if (rtn.size() > 0)
401     {
402       // expand the tied sequence[] and string[] arrays
403       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
404       String[][] sch = new String[getPdbCount()][];
405       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
406       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
407       setSequence(sqs);
408       setChains(sch);
409       pdbe = new PDBEntry[rtn.size()];
410       for (int r = 0; r < pdbe.length; r++)
411       {
412         int[] stri = (rtn.get(r));
413         // record the pdb file as a new addition
414         pdbe[r] = getPdbEntry(stri[0]);
415         // and add the new sequence/chain entries
416         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
417       }
418     }
419     else
420     {
421       pdbe = null;
422     }
423     return pdbe;
424   }
425
426   /**
427    * Add sequences to the pe'th pdbentry's sequence set.
428    * 
429    * @param pe
430    * @param seq
431    */
432   public void addSequence(int pe, SequenceI[] seq)
433   {
434     addSequenceAndChain(pe, seq, null);
435   }
436
437   /**
438    * add the given sequences to the mapping scope for the given pdb file handle
439    * 
440    * @param pdbFile
441    *          - pdbFile identifier
442    * @param seq
443    *          - set of sequences it can be mapped to
444    */
445   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
446   {
447     for (int pe = 0; pe < getPdbCount(); pe++)
448     {
449       if (getPdbEntry(pe).getFile().equals(pdbFile))
450       {
451         addSequence(pe, seq);
452       }
453     }
454   }
455
456   @Override
457   public abstract void highlightAtoms(List<AtomSpec> atoms);
458
459   protected boolean isNucleotide()
460   {
461     return this.nucleotide;
462   }
463
464   /**
465    * Returns a readable description of all mappings for the wrapped pdbfile to
466    * any mapped sequences
467    * 
468    * @param pdbfile
469    * @param seqs
470    * @return
471    */
472   public String printMappings()
473   {
474     if (pdbEntry == null)
475     {
476       return "";
477     }
478     StringBuilder sb = new StringBuilder(128);
479     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
480     {
481       String pdbfile = getPdbEntry(pdbe).getFile();
482       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
483       sb.append(getSsm().printMappings(pdbfile, seqs));
484     }
485     return sb.toString();
486   }
487
488   /**
489    * Returns the mapped structure position for a given aligned column of a given
490    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
491    * not mapped to structure.
492    * 
493    * @param seq
494    * @param alignedPos
495    * @param mapping
496    * @return
497    */
498   protected int getMappedPosition(SequenceI seq, int alignedPos,
499           StructureMapping mapping)
500   {
501     if (alignedPos >= seq.getLength())
502     {
503       return -1;
504     }
505
506     if (Comparison.isGap(seq.getCharAt(alignedPos)))
507     {
508       return -1;
509     }
510     int seqPos = seq.findPosition(alignedPos);
511     int pos = mapping.getPDBResNum(seqPos);
512     return pos;
513   }
514
515   /**
516    * Helper method to identify residues that can participate in a structure
517    * superposition command. For each structure, identify a sequence in the
518    * alignment which is mapped to the structure. Identify non-gapped columns in
519    * the sequence which have a mapping to a residue in the structure. Returns
520    * the index of the first structure that has a mapping to the alignment.
521    * 
522    * @param alignment
523    *          the sequence alignment which is the basis of structure
524    *          superposition
525    * @param matched
526    *          a BitSet, where bit j is set to indicate that every structure has
527    *          a mapped residue present in column j (so the column can
528    *          participate in structure alignment)
529    * @param structures
530    *          an array of data beans corresponding to pdb file index
531    * @return
532    */
533   protected int findSuperposableResidues(AlignmentI alignment,
534           BitSet matched, SuperposeData[] structures)
535   {
536     int refStructure = -1;
537     String[] files = getPdbFile();
538     if (files == null)
539     {
540       return -1;
541     }
542     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
543     {
544       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
545       int lastPos = -1;
546
547       /*
548        * Find the first mapped sequence (if any) for this PDB entry which is in
549        * the alignment
550        */
551       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
552       for (int s = 0; s < seqCountForPdbFile; s++)
553       {
554         for (StructureMapping mapping : mappings)
555         {
556           final SequenceI theSequence = getSequence()[pdbfnum][s];
557           if (mapping.getSequence() == theSequence
558                   && alignment.findIndex(theSequence) > -1)
559           {
560             if (refStructure < 0)
561             {
562               refStructure = pdbfnum;
563             }
564             for (int r = 0; r < alignment.getWidth(); r++)
565             {
566               if (!matched.get(r))
567               {
568                 continue;
569               }
570               int pos = getMappedPosition(theSequence, r, mapping);
571               if (pos < 1 || pos == lastPos)
572               {
573                 matched.clear(r);
574                 continue;
575               }
576               lastPos = pos;
577               structures[pdbfnum].pdbResNo[r] = pos;
578             }
579             String chain = mapping.getChain();
580             if (chain != null && chain.trim().length() > 0)
581             {
582               structures[pdbfnum].chain = chain;
583             }
584             structures[pdbfnum].pdbId = mapping.getPdbId();
585             structures[pdbfnum].isRna = theSequence.getRNA() != null;
586
587             /*
588              * move on to next pdb file (ignore sequences for other chains
589              * for the same structure)
590              */
591             s = seqCountForPdbFile;
592             break;
593           }
594         }
595       }
596     }
597     return refStructure;
598   }
599
600   /**
601    * Returns true if the structure viewer has loaded all of the files of
602    * interest (identified by the file mapping having been set up), or false if
603    * any are still not loaded after a timeout interval.
604    * 
605    * @param files
606    */
607   protected boolean waitForFileLoad(String[] files)
608   {
609     /*
610      * give up after 10 secs plus 1 sec per file
611      */
612     long starttime = System.currentTimeMillis();
613     long endTime = 10000 + 1000 * files.length + starttime;
614     String notLoaded = null;
615
616     boolean waiting = true;
617     while (waiting && System.currentTimeMillis() < endTime)
618     {
619       waiting = false;
620       for (String file : files)
621       {
622         notLoaded = file;
623         if (file == null)
624         {
625           continue;
626         }
627         try
628         {
629           StructureMapping[] sm = getSsm().getMapping(file);
630           if (sm == null || sm.length == 0)
631           {
632             waiting = true;
633           }
634         } catch (Throwable x)
635         {
636           waiting = true;
637         }
638       }
639     }
640
641     if (waiting)
642     {
643       System.err
644               .println("Timed out waiting for structure viewer to load file "
645                       + notLoaded);
646       return false;
647     }
648     return true;
649   }
650
651   @Override
652   public boolean isListeningFor(SequenceI seq)
653   {
654     if (sequence != null)
655     {
656       for (SequenceI[] seqs : sequence)
657       {
658         if (seqs != null)
659         {
660           for (SequenceI s : seqs)
661           {
662             if (s == seq
663                     || (s.getDatasetSequence() != null && s
664                             .getDatasetSequence() == seq
665                             .getDatasetSequence()))
666             {
667               return true;
668             }
669           }
670         }
671       }
672     }
673     return false;
674   }
675
676   public boolean isFinishedInit()
677   {
678     return finishedInit;
679   }
680
681   public void setFinishedInit(boolean fi)
682   {
683     this.finishedInit = fi;
684   }
685
686   /**
687    * Returns a list of chains mapped in this viewer.
688    * 
689    * @return
690    */
691   public abstract List<String> getChainNames();
692
693   /**
694    * Returns the Jalview panel hosting the structure viewer (if any)
695    * 
696    * @return
697    */
698   public JalviewStructureDisplayI getViewer()
699   {
700     return null;
701   }
702
703   public abstract void setJalviewColourScheme(ColourSchemeI cs);
704
705   /**
706    * Constructs and sends a command to align structures against a reference
707    * structure, based on one or more sequence alignments. May optionally return
708    * an error or warning message for the alignment command.
709    * 
710    * @param alignments
711    *          an array of alignments to process
712    * @param structureIndices
713    *          an array of corresponding reference structures (index into pdb
714    *          file array); if a negative value is passed, the first PDB file
715    *          mapped to an alignment sequence is used as the reference for
716    *          superposition
717    * @param hiddenCols
718    *          an array of corresponding hidden columns for each alignment
719    * @return
720    */
721   public abstract String superposeStructures(AlignmentI[] alignments, int[] structureIndices,
722           ColumnSelection[] hiddenCols);
723
724   public abstract void setBackgroundColour(Color col);
725
726   protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
727           String[] files, SequenceRenderer sr, FeatureRenderer fr,
728           AlignViewportI alignViewportI);
729
730   /**
731    * returns the current featureRenderer that should be used to colour the
732    * structures
733    * 
734    * @param alignment
735    * 
736    * @return
737    */
738   public abstract FeatureRenderer getFeatureRenderer(AlignmentViewPanel alignment);
739
740   /**
741    * returns the current sequenceRenderer that should be used to colour the
742    * structures
743    * 
744    * @param alignment
745    * 
746    * @return
747    */
748   public abstract SequenceRenderer getSequenceRenderer(AlignmentViewPanel alignment);
749
750   protected abstract void colourBySequence(
751           StructureMappingcommandSet[] colourBySequenceCommands);
752
753   public abstract void colourByChain();
754
755   public abstract void colourByCharge();
756
757   /**
758    * colour any structures associated with sequences in the given alignment
759    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
760    * if colourBySequence is enabled.
761    */
762   public void colourBySequence(AlignmentViewPanel alignmentv)
763   {
764     if (!colourBySequence || !isLoadingFinished())
765     {
766       return;
767     }
768     if (getSsm() == null)
769     {
770       return;
771     }
772     String[] files = getPdbFile();
773   
774     SequenceRenderer sr = getSequenceRenderer(alignmentv);
775   
776     FeatureRenderer fr = null;
777     boolean showFeatures = alignmentv.getAlignViewport()
778             .isShowSequenceFeatures();
779     if (showFeatures)
780     {
781       fr = getFeatureRenderer(alignmentv);
782     }
783   
784     StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
785             files, sr, fr, alignmentv.getAlignViewport());
786     colourBySequence(colourBySequenceCommands);
787   }
788
789   public boolean hasFileLoadingError()
790   {
791     return fileLoadingError != null && fileLoadingError.length() > 0;
792   }
793 }