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