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