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