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