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