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