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