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