3c4041413282c840e9631e2262e086c21321cbd1
[jalview.git] / src / jalview / structures / models / AAStructureBindingModel.java
1 package jalview.structures.models;
2
3 import jalview.api.StructureSelectionManagerProvider;
4 import jalview.datamodel.AlignmentI;
5 import jalview.datamodel.PDBEntry;
6 import jalview.datamodel.SequenceI;
7 import jalview.structure.AtomSpec;
8 import jalview.structure.StructureListener;
9 import jalview.structure.StructureMapping;
10 import jalview.structure.StructureSelectionManager;
11 import jalview.util.Comparison;
12 import jalview.util.MessageManager;
13
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.List;
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   private boolean finishedInit = false;
56
57   /**
58    * Data bean class to simplify parameterisation in superposeStructures
59    */
60   protected class SuperposeData
61   {
62     /**
63      * Constructor with alignment width argument
64      * 
65      * @param width
66      */
67     public SuperposeData(int width)
68     {
69       pdbResNo = new int[width];
70     }
71
72     public String filename;
73
74     public String pdbId;
75
76     public String chain = "";
77
78     public boolean isRna;
79
80     /*
81      * The pdb residue number (if any) mapped to each column of the alignment
82      */
83     public int[] pdbResNo;
84   }
85
86   /**
87    * Constructor
88    * 
89    * @param ssm
90    * @param seqs
91    */
92   public AAStructureBindingModel(StructureSelectionManager ssm,
93           SequenceI[][] seqs)
94   {
95     this.ssm = ssm;
96     this.sequence = seqs;
97   }
98
99   /**
100    * Constructor
101    * 
102    * @param ssm
103    * @param pdbentry
104    * @param sequenceIs
105    * @param chains
106    * @param protocol
107    */
108   public AAStructureBindingModel(StructureSelectionManager ssm,
109           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
110           String protocol)
111   {
112     this.ssm = ssm;
113     this.sequence = sequenceIs;
114     this.nucleotide = Comparison.isNucleotide(sequenceIs);
115     this.chains = chains;
116     this.pdbEntry = pdbentry;
117     this.protocol = protocol;
118     if (chains == null)
119     {
120       this.chains = new String[pdbentry.length][];
121     }
122   }
123
124   public StructureSelectionManager getSsm()
125   {
126     return ssm;
127   }
128
129   /**
130    * Returns the i'th PDBEntry (or null)
131    * 
132    * @param i
133    * @return
134    */
135   public PDBEntry getPdbEntry(int i)
136   {
137     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
138   }
139
140   /**
141    * Answers true if this binding includes the given PDB id, else false
142    * 
143    * @param pdbId
144    * @return
145    */
146   public boolean hasPdbId(String pdbId)
147   {
148     if (pdbEntry != null)
149     {
150       for (PDBEntry pdb : pdbEntry)
151       {
152         if (pdb.getId().equals(pdbId))
153         {
154           return true;
155         }
156       }
157     }
158     return false;
159   }
160
161   /**
162    * Returns the number of modelled PDB file entries.
163    * 
164    * @return
165    */
166   public int getPdbCount()
167   {
168     return pdbEntry == null ? 0 : pdbEntry.length;
169   }
170
171   public SequenceI[][] getSequence()
172   {
173     return sequence;
174   }
175
176   public String[][] getChains()
177   {
178     return chains;
179   }
180
181   public String getProtocol()
182   {
183     return protocol;
184   }
185
186   // TODO may remove this if calling methods can be pulled up here
187   protected void setPdbentry(PDBEntry[] pdbentry)
188   {
189     this.pdbEntry = pdbentry;
190   }
191
192   protected void setSequence(SequenceI[][] sequence)
193   {
194     this.sequence = sequence;
195   }
196
197   protected void setChains(String[][] chains)
198   {
199     this.chains = chains;
200   }
201
202   /**
203    * Construct a title string for the viewer window based on the data Jalview
204    * knows about
205    * 
206    * @param viewerName
207    *          TODO
208    * @param verbose
209    * 
210    * @return
211    */
212   public String getViewerTitle(String viewerName, boolean verbose)
213   {
214     if (getSequence() == null || getSequence().length < 1
215             || getPdbCount() < 1 || getSequence()[0].length < 1)
216     {
217       return ("Jalview " + viewerName + " Window");
218     }
219     // TODO: give a more informative title when multiple structures are
220     // displayed.
221     StringBuilder title = new StringBuilder(64);
222     final PDBEntry pdbEntry = getPdbEntry(0);
223     title.append(viewerName + " view for " + getSequence()[0][0].getName()
224             + ":" + pdbEntry.getId());
225
226     if (verbose)
227     {
228       if (pdbEntry.getProperty() != null)
229       {
230         if (pdbEntry.getProperty().get("method") != null)
231         {
232           title.append(" Method: ");
233           title.append(pdbEntry.getProperty().get("method"));
234         }
235         if (pdbEntry.getProperty().get("chains") != null)
236         {
237           title.append(" Chain:");
238           title.append(pdbEntry.getProperty().get("chains"));
239         }
240       }
241     }
242     return title.toString();
243   }
244
245   /**
246    * Called by after closeViewer is called, to release any resources and
247    * references so they can be garbage collected. Override if needed.
248    */
249   protected void releaseUIResources()
250   {
251
252   }
253
254   public boolean isColourBySequence()
255   {
256     return colourBySequence;
257   }
258
259   public void setColourBySequence(boolean colourBySequence)
260   {
261     this.colourBySequence = colourBySequence;
262   }
263
264   protected void addSequenceAndChain(int pe, SequenceI[] seq,
265           String[] tchain)
266   {
267     if (pe < 0 || pe >= getPdbCount())
268     {
269       throw new Error(MessageManager.formatMessage(
270               "error.implementation_error_no_pdbentry_from_index",
271               new Object[] { Integer.valueOf(pe).toString() }));
272     }
273     final String nullChain = "TheNullChain";
274     List<SequenceI> s = new ArrayList<SequenceI>();
275     List<String> c = new ArrayList<String>();
276     if (getChains() == null)
277     {
278       setChains(new String[getPdbCount()][]);
279     }
280     if (getSequence()[pe] != null)
281     {
282       for (int i = 0; i < getSequence()[pe].length; i++)
283       {
284         s.add(getSequence()[pe][i]);
285         if (getChains()[pe] != null)
286         {
287           if (i < getChains()[pe].length)
288           {
289             c.add(getChains()[pe][i]);
290           }
291           else
292           {
293             c.add(nullChain);
294           }
295         }
296         else
297         {
298           if (tchain != null && tchain.length > 0)
299           {
300             c.add(nullChain);
301           }
302         }
303       }
304     }
305     for (int i = 0; i < seq.length; i++)
306     {
307       if (!s.contains(seq[i]))
308       {
309         s.add(seq[i]);
310         if (tchain != null && i < tchain.length)
311         {
312           c.add(tchain[i] == null ? nullChain : tchain[i]);
313         }
314       }
315     }
316     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
317     getSequence()[pe] = tmp;
318     if (c.size() > 0)
319     {
320       String[] tch = c.toArray(new String[c.size()]);
321       for (int i = 0; i < tch.length; i++)
322       {
323         if (tch[i] == nullChain)
324         {
325           tch[i] = null;
326         }
327       }
328       getChains()[pe] = tch;
329     }
330     else
331     {
332       getChains()[pe] = null;
333     }
334   }
335
336   /**
337    * add structures and any known sequence associations
338    * 
339    * @returns the pdb entries added to the current set.
340    */
341   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
342           SequenceI[][] seq, String[][] chns)
343   {
344     List<PDBEntry> v = new ArrayList<PDBEntry>();
345     List<int[]> rtn = new ArrayList<int[]>();
346     for (int i = 0; i < getPdbCount(); i++)
347     {
348       v.add(getPdbEntry(i));
349     }
350     for (int i = 0; i < pdbe.length; i++)
351     {
352       int r = v.indexOf(pdbe[i]);
353       if (r == -1 || r >= getPdbCount())
354       {
355         rtn.add(new int[] { 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
627   public boolean isFinishedInit()
628   {
629     return finishedInit;
630   }
631
632   public void setFinishedInit(boolean fi)
633   {
634     this.finishedInit = fi;
635   }
636 }