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