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