70fe60964640d9d5aad37b259ac9e43d8002cf45
[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.datamodel.AlignmentI;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.io.DataSourceType;
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   private PDBEntry[] pdbEntry;
56
57   /*
58    * sequences mapped to each pdbentry
59    */
60   private SequenceI[][] sequence;
61
62   /*
63    * array of target chains for sequences - tied to pdbentry and sequence[]
64    */
65   private String[][] chains;
66
67   /*
68    * datasource protocol for access to PDBEntrylatest
69    */
70   DataSourceType protocol = null;
71
72   protected boolean colourBySequence = true;
73
74   private boolean nucleotide;
75
76   private boolean finishedInit = false;
77
78   /**
79    * Data bean class to simplify parameterisation in superposeStructures
80    */
81   protected class SuperposeData
82   {
83     /**
84      * Constructor with alignment width argument
85      * 
86      * @param width
87      */
88     public SuperposeData(int width)
89     {
90       pdbResNo = new int[width];
91     }
92
93     public String filename;
94
95     public String pdbId;
96
97     public String chain = "";
98
99     public boolean isRna;
100
101     /*
102      * The pdb residue number (if any) mapped to each column of the alignment
103      */
104     public int[] pdbResNo;
105   }
106
107   /**
108    * Constructor
109    * 
110    * @param ssm
111    * @param seqs
112    */
113   public AAStructureBindingModel(StructureSelectionManager ssm,
114           SequenceI[][] seqs)
115   {
116     this.ssm = ssm;
117     this.sequence = seqs;
118   }
119
120   /**
121    * Constructor
122    * 
123    * @param ssm
124    * @param pdbentry
125    * @param sequenceIs
126    * @param chains
127    * @param protocol2
128    */
129   public AAStructureBindingModel(StructureSelectionManager ssm,
130           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
131           DataSourceType protocol2)
132   {
133     this.ssm = ssm;
134     this.sequence = sequenceIs;
135     this.nucleotide = Comparison.isNucleotide(sequenceIs);
136     this.chains = chains;
137     this.pdbEntry = pdbentry;
138     this.protocol = protocol2;
139     if (chains == null)
140     {
141       this.chains = new String[pdbentry.length][];
142     }
143   }
144
145   public StructureSelectionManager getSsm()
146   {
147     return ssm;
148   }
149
150   /**
151    * Returns the i'th PDBEntry (or null)
152    * 
153    * @param i
154    * @return
155    */
156   public PDBEntry getPdbEntry(int i)
157   {
158     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
159   }
160
161   /**
162    * Answers true if this binding includes the given PDB id, else false
163    * 
164    * @param pdbId
165    * @return
166    */
167   public boolean hasPdbId(String pdbId)
168   {
169     if (pdbEntry != null)
170     {
171       for (PDBEntry pdb : pdbEntry)
172       {
173         if (pdb.getId().equals(pdbId))
174         {
175           return true;
176         }
177       }
178     }
179     return false;
180   }
181
182   /**
183    * Returns the number of modelled PDB file entries.
184    * 
185    * @return
186    */
187   public int getPdbCount()
188   {
189     return pdbEntry == null ? 0 : pdbEntry.length;
190   }
191
192   public SequenceI[][] getSequence()
193   {
194     return sequence;
195   }
196
197   public String[][] getChains()
198   {
199     return chains;
200   }
201
202   public DataSourceType getProtocol()
203   {
204     return protocol;
205   }
206
207   // TODO may remove this if calling methods can be pulled up here
208   protected void setPdbentry(PDBEntry[] pdbentry)
209   {
210     this.pdbEntry = pdbentry;
211   }
212
213   protected void setSequence(SequenceI[][] sequence)
214   {
215     this.sequence = sequence;
216   }
217
218   protected void setChains(String[][] chains)
219   {
220     this.chains = chains;
221   }
222
223   /**
224    * Construct a title string for the viewer window based on the data Jalview
225    * knows about
226    * 
227    * @param viewerName
228    *          TODO
229    * @param verbose
230    * 
231    * @return
232    */
233   public String getViewerTitle(String viewerName, boolean verbose)
234   {
235     if (getSequence() == null || getSequence().length < 1
236             || getPdbCount() < 1 || getSequence()[0].length < 1)
237     {
238       return ("Jalview " + viewerName + " Window");
239     }
240     // TODO: give a more informative title when multiple structures are
241     // displayed.
242     StringBuilder title = new StringBuilder(64);
243     final PDBEntry pdbEntry = getPdbEntry(0);
244     title.append(viewerName + " view for " + getSequence()[0][0].getName()
245             + ":" + pdbEntry.getId());
246
247     if (verbose)
248     {
249       if (pdbEntry.getProperty() != null)
250       {
251         if (pdbEntry.getProperty().get("method") != null)
252         {
253           title.append(" Method: ");
254           title.append(pdbEntry.getProperty().get("method"));
255         }
256         if (pdbEntry.getProperty().get("chains") != null)
257         {
258           title.append(" Chain:");
259           title.append(pdbEntry.getProperty().get("chains"));
260         }
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     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
526     {
527       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
528       int lastPos = -1;
529
530       /*
531        * Find the first mapped sequence (if any) for this PDB entry which is in
532        * the alignment
533        */
534       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
535       for (int s = 0; s < seqCountForPdbFile; s++)
536       {
537         for (StructureMapping mapping : mappings)
538         {
539           final SequenceI theSequence = getSequence()[pdbfnum][s];
540           if (mapping.getSequence() == theSequence
541                   && alignment.findIndex(theSequence) > -1)
542           {
543             if (refStructure < 0)
544             {
545               refStructure = pdbfnum;
546             }
547             for (int r = 0; r < matched.length; r++)
548             {
549               if (!matched[r])
550               {
551                 continue;
552               }
553               int pos = getMappedPosition(theSequence, r, mapping);
554               if (pos < 1 || pos == lastPos)
555               {
556                 matched[r] = false;
557                 continue;
558               }
559               lastPos = pos;
560               structures[pdbfnum].pdbResNo[r] = pos;
561             }
562             String chain = mapping.getChain();
563             if (chain != null && chain.trim().length() > 0)
564             {
565               structures[pdbfnum].chain = chain;
566             }
567             structures[pdbfnum].pdbId = mapping.getPdbId();
568             structures[pdbfnum].isRna = theSequence.getRNA() != null;
569             // move on to next pdb file
570             s = seqCountForPdbFile;
571             break;
572           }
573         }
574       }
575     }
576     return refStructure;
577   }
578
579   /**
580    * Returns true if the structure viewer has loaded all of the files of
581    * interest (identified by the file mapping having been set up), or false if
582    * any are still not loaded after a timeout interval.
583    * 
584    * @param files
585    */
586   protected boolean waitForFileLoad(String[] files)
587   {
588     /*
589      * give up after 10 secs plus 1 sec per file
590      */
591     long starttime = System.currentTimeMillis();
592     long endTime = 10000 + 1000 * files.length + starttime;
593     String notLoaded = null;
594
595     boolean waiting = true;
596     while (waiting && System.currentTimeMillis() < endTime)
597     {
598       waiting = false;
599       for (String file : files)
600       {
601         notLoaded = file;
602         if (file == null)
603         {
604           continue;
605         }
606         try
607         {
608           StructureMapping[] sm = getSsm().getMapping(file);
609           if (sm == null || sm.length == 0)
610           {
611             waiting = true;
612           }
613         } catch (Throwable x)
614         {
615           waiting = true;
616         }
617       }
618     }
619
620     if (waiting)
621     {
622       System.err
623               .println("Timed out waiting for structure viewer to load file "
624                       + notLoaded);
625       return false;
626     }
627     return true;
628   }
629
630   @Override
631   public boolean isListeningFor(SequenceI seq)
632   {
633     if (sequence != null)
634     {
635       for (SequenceI[] seqs : sequence)
636       {
637         if (seqs != null)
638         {
639           for (SequenceI s : seqs)
640           {
641             if (s == seq
642                     || (s.getDatasetSequence() != null && s
643                             .getDatasetSequence() == seq
644                             .getDatasetSequence()))
645             {
646               return true;
647             }
648           }
649         }
650       }
651     }
652     return false;
653   }
654
655   public boolean isFinishedInit()
656   {
657     return finishedInit;
658   }
659
660   public void setFinishedInit(boolean fi)
661   {
662     this.finishedInit = fi;
663   }
664 }