8d8957c244530a0ab25ef979f2429035eb12aeb7
[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.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureRenderer;
26 import jalview.api.SequenceRenderer;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.api.structures.JalviewStructureDisplayI;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.StructureViewer.ViewerType;
34 import jalview.io.DataSourceType;
35 import jalview.io.StructureFile;
36 import jalview.renderer.seqfeatures.FeatureColourFinder;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.AtomSpec;
40 import jalview.structure.AtomSpecModel;
41 import jalview.structure.StructureCommandI;
42 import jalview.structure.StructureCommandsI;
43 import jalview.structure.StructureListener;
44 import jalview.structure.StructureMapping;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.util.Comparison;
47 import jalview.util.MessageManager;
48
49 import java.awt.Color;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.BitSet;
53 import java.util.HashMap;
54 import java.util.LinkedHashMap;
55 import java.util.List;
56 import java.util.Map;
57
58 import javax.swing.SwingUtilities;
59
60 /**
61  * 
62  * A base class to hold common function for protein structure model binding.
63  * Initial version created by refactoring JMol and Chimera binding models, but
64  * other structure viewers could in principle be accommodated in future.
65  * 
66  * @author gmcarstairs
67  *
68  */
69 public abstract class AAStructureBindingModel
70         extends SequenceStructureBindingModel
71         implements StructureListener, StructureSelectionManagerProvider
72 {
73   /**
74    * Data bean class to simplify parameterisation in superposeStructures
75    */
76   public static class SuperposeData
77   {
78     public String filename;
79   
80     public String pdbId;
81   
82     public String chain = "";
83   
84     public boolean isRna;
85   
86     /*
87      * The pdb residue number (if any) mapped to columns of the alignment
88      */
89     public int[] pdbResNo; // or use SparseIntArray?
90   
91     public String modelId;
92   
93     /**
94      * Constructor
95      * 
96      * @param width
97      *          width of alignment (number of columns that may potentially
98      *          participate in superposition)
99      * @param model
100      *          structure viewer model number
101      */
102     public SuperposeData(int width, String model)
103     {
104       pdbResNo = new int[width];
105       modelId = model;
106     }
107   }
108
109   private static final int MIN_POS_TO_SUPERPOSE = 4;
110
111   private static final String COLOURING_STRUCTURES = MessageManager
112           .getString("status.colouring_structures");
113
114   /*
115    * the Jalview panel through which the user interacts
116    * with the structure viewer
117    */
118   private JalviewStructureDisplayI viewer;
119
120   /*
121    * helper that generates command syntax
122    */
123   private StructureCommandsI commandGenerator;
124
125   private StructureSelectionManager ssm;
126
127   /*
128    * modelled chains, formatted as "pdbid:chainCode"
129    */
130   private List<String> chainNames;
131
132   /*
133    * lookup of pdb file name by key "pdbid:chainCode"
134    */
135   private Map<String, String> chainFile;
136
137   /*
138    * distinct PDB entries (pdb files) associated
139    * with sequences
140    */
141   private PDBEntry[] pdbEntry;
142
143   /*
144    * sequences mapped to each pdbentry
145    */
146   private SequenceI[][] sequence;
147
148   /*
149    * array of target chains for sequences - tied to pdbentry and sequence[]
150    */
151   private String[][] chains;
152
153   /*
154    * datasource protocol for access to PDBEntrylatest
155    */
156   DataSourceType protocol = null;
157
158   protected boolean colourBySequence = true;
159
160   private boolean nucleotide;
161
162   private boolean finishedInit = false;
163
164   /**
165    * current set of model filenames loaded in the viewer
166    */
167   protected String[] modelFileNames = null;
168
169   public String fileLoadingError;
170
171   /**
172    * Constructor
173    * 
174    * @param ssm
175    * @param seqs
176    */
177   public AAStructureBindingModel(StructureSelectionManager ssm,
178           SequenceI[][] seqs)
179   {
180     this.ssm = ssm;
181     this.sequence = seqs;
182     chainNames = new ArrayList<>();
183     chainFile = new HashMap<>();
184   }
185
186   /**
187    * Constructor
188    * 
189    * @param ssm
190    * @param pdbentry
191    * @param sequenceIs
192    * @param protocol
193    */
194   public AAStructureBindingModel(StructureSelectionManager ssm,
195           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
196           DataSourceType protocol)
197   {
198     this(ssm, sequenceIs);
199     this.nucleotide = Comparison.isNucleotide(sequenceIs);
200     this.pdbEntry = pdbentry;
201     this.protocol = protocol;
202     resolveChains();
203   }
204
205   private boolean resolveChains()
206   {
207     /**
208      * final count of chain mappings discovered
209      */
210     int chainmaps = 0;
211     // JBPNote: JAL-2693 - this should be a list of chain mappings per
212     // [pdbentry][sequence]
213     String[][] newchains = new String[pdbEntry.length][];
214     int pe = 0;
215     for (PDBEntry pdb : pdbEntry)
216     {
217       SequenceI[] seqsForPdb = sequence[pe];
218       if (seqsForPdb != null)
219       {
220         newchains[pe] = new String[seqsForPdb.length];
221         int se = 0;
222         for (SequenceI asq : seqsForPdb)
223         {
224           String chain = (chains != null && chains[pe] != null)
225                   ? chains[pe][se]
226                   : null;
227           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
228                   : asq.getDatasetSequence();
229           if (sq.getAllPDBEntries() != null)
230           {
231             for (PDBEntry pdbentry : sq.getAllPDBEntries())
232             {
233               if (pdb.getFile() != null && pdbentry.getFile() != null
234                       && pdb.getFile().equals(pdbentry.getFile()))
235               {
236                 String chaincode = pdbentry.getChainCode();
237                 if (chaincode != null && chaincode.length() > 0)
238                 {
239                   chain = chaincode;
240                   chainmaps++;
241                   break;
242                 }
243               }
244             }
245           }
246           newchains[pe][se] = chain;
247           se++;
248         }
249         pe++;
250       }
251     }
252
253     chains = newchains;
254     return chainmaps > 0;
255   }
256   public StructureSelectionManager getSsm()
257   {
258     return ssm;
259   }
260
261   /**
262    * Returns the i'th PDBEntry (or null)
263    * 
264    * @param i
265    * @return
266    */
267   public PDBEntry getPdbEntry(int i)
268   {
269     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
270   }
271
272   /**
273    * Answers true if this binding includes the given PDB id, else false
274    * 
275    * @param pdbId
276    * @return
277    */
278   public boolean hasPdbId(String pdbId)
279   {
280     if (pdbEntry != null)
281     {
282       for (PDBEntry pdb : pdbEntry)
283       {
284         if (pdb.getId().equals(pdbId))
285         {
286           return true;
287         }
288       }
289     }
290     return false;
291   }
292
293   /**
294    * Returns the number of modelled PDB file entries.
295    * 
296    * @return
297    */
298   public int getPdbCount()
299   {
300     return pdbEntry == null ? 0 : pdbEntry.length;
301   }
302
303   public SequenceI[][] getSequence()
304   {
305     return sequence;
306   }
307
308   public String[][] getChains()
309   {
310     return chains;
311   }
312
313   public DataSourceType getProtocol()
314   {
315     return protocol;
316   }
317
318   // TODO may remove this if calling methods can be pulled up here
319   protected void setPdbentry(PDBEntry[] pdbentry)
320   {
321     this.pdbEntry = pdbentry;
322   }
323
324   protected void setSequence(SequenceI[][] sequence)
325   {
326     this.sequence = sequence;
327   }
328
329   protected void setChains(String[][] chains)
330   {
331     this.chains = chains;
332   }
333
334   /**
335    * Construct a title string for the viewer window based on the data Jalview
336    * knows about
337    * 
338    * @param viewerName
339    *          TODO
340    * @param verbose
341    * 
342    * @return
343    */
344   public String getViewerTitle(String viewerName, boolean verbose)
345   {
346     if (getSequence() == null || getSequence().length < 1
347             || getPdbCount() < 1 || getSequence()[0].length < 1)
348     {
349       return ("Jalview " + viewerName + " Window");
350     }
351     // TODO: give a more informative title when multiple structures are
352     // displayed.
353     StringBuilder title = new StringBuilder(64);
354     final PDBEntry pdbe = getPdbEntry(0);
355     title.append(viewerName + " view for " + getSequence()[0][0].getName()
356             + ":" + pdbe.getId());
357
358     if (verbose)
359     {
360       String method = (String) pdbe.getProperty("method");
361       if (method != null)
362       {
363         title.append(" Method: ").append(method);
364       }
365       String chain = (String) pdbe.getProperty("chains");
366       if (chain != null)
367       {
368         title.append(" Chain:").append(chain);
369       }
370     }
371     return title.toString();
372   }
373
374   /**
375    * Called by after closeViewer is called, to release any resources and
376    * references so they can be garbage collected. Override if needed.
377    */
378   protected void releaseUIResources()
379   {
380   }
381
382   @Override
383   public void releaseReferences(Object svl)
384   {
385   }
386
387   public boolean isColourBySequence()
388   {
389     return colourBySequence;
390   }
391
392   /**
393    * Called when the binding thinks the UI needs to be refreshed after a
394    * structure viewer state change. This could be because structures were
395    * loaded, or because an error has occurred. Default does nothing, override as
396    * required.
397    */
398   public void refreshGUI()
399   {
400   }
401
402   /**
403    * Instruct the Jalview binding to update the pdbentries vector if necessary
404    * prior to matching the jmol view's contents to the list of structure files
405    * Jalview knows about. By default does nothing, override as required.
406    */
407   public void refreshPdbEntries()
408   {
409   }
410
411   public void setColourBySequence(boolean colourBySequence)
412   {
413     this.colourBySequence = colourBySequence;
414   }
415
416   protected void addSequenceAndChain(int pe, SequenceI[] seq,
417           String[] tchain)
418   {
419     if (pe < 0 || pe >= getPdbCount())
420     {
421       throw new Error(MessageManager.formatMessage(
422               "error.implementation_error_no_pdbentry_from_index",
423               new Object[]
424               { Integer.valueOf(pe).toString() }));
425     }
426     final String nullChain = "TheNullChain";
427     List<SequenceI> s = new ArrayList<>();
428     List<String> c = new ArrayList<>();
429     if (getChains() == null)
430     {
431       setChains(new String[getPdbCount()][]);
432     }
433     if (getSequence()[pe] != null)
434     {
435       for (int i = 0; i < getSequence()[pe].length; i++)
436       {
437         s.add(getSequence()[pe][i]);
438         if (getChains()[pe] != null)
439         {
440           if (i < getChains()[pe].length)
441           {
442             c.add(getChains()[pe][i]);
443           }
444           else
445           {
446             c.add(nullChain);
447           }
448         }
449         else
450         {
451           if (tchain != null && tchain.length > 0)
452           {
453             c.add(nullChain);
454           }
455         }
456       }
457     }
458     for (int i = 0; i < seq.length; i++)
459     {
460       if (!s.contains(seq[i]))
461       {
462         s.add(seq[i]);
463         if (tchain != null && i < tchain.length)
464         {
465           c.add(tchain[i] == null ? nullChain : tchain[i]);
466         }
467       }
468     }
469     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
470     getSequence()[pe] = tmp;
471     if (c.size() > 0)
472     {
473       String[] tch = c.toArray(new String[c.size()]);
474       for (int i = 0; i < tch.length; i++)
475       {
476         if (tch[i] == nullChain)
477         {
478           tch[i] = null;
479         }
480       }
481       getChains()[pe] = tch;
482     }
483     else
484     {
485       getChains()[pe] = null;
486     }
487   }
488
489   /**
490    * add structures and any known sequence associations
491    * 
492    * @returns the pdb entries added to the current set.
493    */
494   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
495           SequenceI[][] seq, String[][] chns)
496   {
497     List<PDBEntry> v = new ArrayList<>();
498     List<int[]> rtn = new ArrayList<>();
499     for (int i = 0; i < getPdbCount(); i++)
500     {
501       v.add(getPdbEntry(i));
502     }
503     for (int i = 0; i < pdbe.length; i++)
504     {
505       int r = v.indexOf(pdbe[i]);
506       if (r == -1 || r >= getPdbCount())
507       {
508         rtn.add(new int[] { v.size(), i });
509         v.add(pdbe[i]);
510       }
511       else
512       {
513         // just make sure the sequence/chain entries are all up to date
514         addSequenceAndChain(r, seq[i], chns[i]);
515       }
516     }
517     pdbe = v.toArray(new PDBEntry[v.size()]);
518     setPdbentry(pdbe);
519     if (rtn.size() > 0)
520     {
521       // expand the tied sequence[] and string[] arrays
522       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
523       String[][] sch = new String[getPdbCount()][];
524       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
525       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
526       setSequence(sqs);
527       setChains(sch);
528       pdbe = new PDBEntry[rtn.size()];
529       for (int r = 0; r < pdbe.length; r++)
530       {
531         int[] stri = (rtn.get(r));
532         // record the pdb file as a new addition
533         pdbe[r] = getPdbEntry(stri[0]);
534         // and add the new sequence/chain entries
535         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
536       }
537     }
538     else
539     {
540       pdbe = null;
541     }
542     return pdbe;
543   }
544
545   /**
546    * Add sequences to the pe'th pdbentry's sequence set.
547    * 
548    * @param pe
549    * @param seq
550    */
551   public void addSequence(int pe, SequenceI[] seq)
552   {
553     addSequenceAndChain(pe, seq, null);
554   }
555
556   /**
557    * add the given sequences to the mapping scope for the given pdb file handle
558    * 
559    * @param pdbFile
560    *          - pdbFile identifier
561    * @param seq
562    *          - set of sequences it can be mapped to
563    */
564   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
565   {
566     for (int pe = 0; pe < getPdbCount(); pe++)
567     {
568       if (getPdbEntry(pe).getFile().equals(pdbFile))
569       {
570         addSequence(pe, seq);
571       }
572     }
573   }
574
575   @Override
576   public abstract void highlightAtoms(List<AtomSpec> atoms);
577
578   protected boolean isNucleotide()
579   {
580     return this.nucleotide;
581   }
582
583   /**
584    * Returns a readable description of all mappings for the wrapped pdbfile to
585    * any mapped sequences
586    * 
587    * @param pdbfile
588    * @param seqs
589    * @return
590    */
591   public String printMappings()
592   {
593     if (pdbEntry == null)
594     {
595       return "";
596     }
597     StringBuilder sb = new StringBuilder(128);
598     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
599     {
600       String pdbfile = getPdbEntry(pdbe).getFile();
601       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
602       sb.append(getSsm().printMappings(pdbfile, seqs));
603     }
604     return sb.toString();
605   }
606
607   /**
608    * Returns the mapped structure position for a given aligned column of a given
609    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
610    * not mapped to structure.
611    * 
612    * @param seq
613    * @param alignedPos
614    * @param mapping
615    * @return
616    */
617   protected int getMappedPosition(SequenceI seq, int alignedPos,
618           StructureMapping mapping)
619   {
620     if (alignedPos >= seq.getLength())
621     {
622       return -1;
623     }
624
625     if (Comparison.isGap(seq.getCharAt(alignedPos)))
626     {
627       return -1;
628     }
629     int seqPos = seq.findPosition(alignedPos);
630     int pos = mapping.getPDBResNum(seqPos);
631     return pos;
632   }
633
634   /**
635    * Helper method to identify residues that can participate in a structure
636    * superposition command. For each structure, identify a sequence in the
637    * alignment which is mapped to the structure. Identify non-gapped columns in
638    * the sequence which have a mapping to a residue in the structure. Returns
639    * the index of the first structure that has a mapping to the alignment.
640    * 
641    * @param alignment
642    *          the sequence alignment which is the basis of structure
643    *          superposition
644    * @param matched
645    *          a BitSet, where bit j is set to indicate that every structure has
646    *          a mapped residue present in column j (so the column can
647    *          participate in structure alignment)
648    * @param structures
649    *          an array of data beans corresponding to pdb file index
650    * @return
651    */
652   protected int findSuperposableResidues(AlignmentI alignment,
653           BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
654   {
655     int refStructure = -1;
656     String[] files = getStructureFiles();
657     if (files == null)
658     {
659       return -1;
660     }
661     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
662     {
663       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
664       int lastPos = -1;
665
666       /*
667        * Find the first mapped sequence (if any) for this PDB entry which is in
668        * the alignment
669        */
670       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
671       for (int s = 0; s < seqCountForPdbFile; s++)
672       {
673         for (StructureMapping mapping : mappings)
674         {
675           final SequenceI theSequence = getSequence()[pdbfnum][s];
676           if (mapping.getSequence() == theSequence
677                   && alignment.findIndex(theSequence) > -1)
678           {
679             if (refStructure < 0)
680             {
681               refStructure = pdbfnum;
682             }
683             for (int r = 0; r < alignment.getWidth(); r++)
684             {
685               if (!matched.get(r))
686               {
687                 continue;
688               }
689               int pos = getMappedPosition(theSequence, r, mapping);
690               if (pos < 1 || pos == lastPos)
691               {
692                 matched.clear(r);
693                 continue;
694               }
695               lastPos = pos;
696               structures[pdbfnum].pdbResNo[r] = pos;
697             }
698             String chain = mapping.getChain();
699             if (chain != null && chain.trim().length() > 0)
700             {
701               structures[pdbfnum].chain = chain;
702             }
703             structures[pdbfnum].pdbId = mapping.getPdbId();
704             structures[pdbfnum].isRna = theSequence.getRNA() != null;
705
706             /*
707              * move on to next pdb file (ignore sequences for other chains
708              * for the same structure)
709              */
710             s = seqCountForPdbFile;
711             break; // fixme break out of two loops here!
712           }
713         }
714       }
715     }
716     return refStructure;
717   }
718
719   /**
720    * Returns true if the structure viewer has loaded all of the files of
721    * interest (identified by the file mapping having been set up), or false if
722    * any are still not loaded after a timeout interval.
723    * 
724    * @param files
725    */
726   protected boolean waitForFileLoad(String[] files)
727   {
728     /*
729      * give up after 10 secs plus 1 sec per file
730      */
731     long starttime = System.currentTimeMillis();
732     long endTime = 10000 + 1000 * files.length + starttime;
733     String notLoaded = null;
734
735     boolean waiting = true;
736     while (waiting && System.currentTimeMillis() < endTime)
737     {
738       waiting = false;
739       for (String file : files)
740       {
741         notLoaded = file;
742         if (file == null)
743         {
744           continue;
745         }
746         try
747         {
748           StructureMapping[] sm = getSsm().getMapping(file);
749           if (sm == null || sm.length == 0)
750           {
751             waiting = true;
752           }
753         } catch (Throwable x)
754         {
755           waiting = true;
756         }
757       }
758     }
759
760     if (waiting)
761     {
762       System.err.println(
763               "Timed out waiting for structure viewer to load file "
764                       + notLoaded);
765       return false;
766     }
767     return true;
768   }
769
770   @Override
771   public boolean isListeningFor(SequenceI seq)
772   {
773     if (sequence != null)
774     {
775       for (SequenceI[] seqs : sequence)
776       {
777         if (seqs != null)
778         {
779           for (SequenceI s : seqs)
780           {
781             if (s == seq || (s.getDatasetSequence() != null
782                     && s.getDatasetSequence() == seq.getDatasetSequence()))
783             {
784               return true;
785             }
786           }
787         }
788       }
789     }
790     return false;
791   }
792
793   public boolean isFinishedInit()
794   {
795     return finishedInit;
796   }
797
798   public void setFinishedInit(boolean fi)
799   {
800     this.finishedInit = fi;
801   }
802
803   /**
804    * Returns a list of chains mapped in this viewer, formatted as
805    * "pdbid:chainCode"
806    * 
807    * @return
808    */
809   public List<String> getChainNames()
810   {
811     return chainNames;
812   }
813
814   /**
815    * Returns the Jalview panel hosting the structure viewer (if any)
816    * 
817    * @return
818    */
819   public JalviewStructureDisplayI getViewer()
820   {
821     return viewer;
822   }
823
824   public void setViewer(JalviewStructureDisplayI v)
825   {
826     viewer = v;
827   }
828
829   /**
830    * Constructs and sends a command to align structures against a reference
831    * structure, based on one or more sequence alignments. May optionally return
832    * an error or warning message for the alignment command(s).
833    * 
834    * @param alignWith
835    *          an array of one or more alignment views to process
836    * @return
837    */
838   public String superposeStructures(List<AlignmentViewPanel> alignWith)
839   {
840     String error = "";
841     String[] files = getStructureFiles();
842
843     if (!waitForFileLoad(files))
844     {
845       return null;
846     }
847     refreshPdbEntries();
848
849     for (AlignmentViewPanel view : alignWith)
850     {
851       AlignmentI alignment = view.getAlignment();
852       HiddenColumns hiddenCols = alignment.getHiddenColumns();
853
854       /*
855        * 'matched' bit i will be set for visible alignment columns i where
856        * all sequences have a residue with a mapping to their PDB structure
857        */
858       BitSet matched = new BitSet();
859       final int width = alignment.getWidth();
860       for (int m = 0; m < width; m++)
861       {
862         if (hiddenCols == null || hiddenCols.isVisible(m))
863         {
864           matched.set(m);
865         }
866       }
867
868       AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
869       for (int f = 0; f < files.length; f++)
870       {
871         structures[f] = new AAStructureBindingModel.SuperposeData(width,
872                 getModelIdForFile(files[f]));
873       }
874
875       /*
876        * Calculate the superposable alignment columns ('matched'), and the
877        * corresponding structure residue positions (structures.pdbResNo)
878        */
879       int refStructure = findSuperposableResidues(alignment,
880               matched, structures);
881
882       /*
883        * require at least 4 positions to be able to execute superposition
884        */
885       int nmatched = matched.cardinality();
886       if (nmatched < MIN_POS_TO_SUPERPOSE)
887       {
888         String msg = MessageManager.formatMessage("label.insufficient_residues",
889                 nmatched);
890         error += view.getViewName() + ": " + msg + "; ";
891         continue;
892       }
893
894       /*
895        * get a model of the superposable residues in the reference structure 
896        */
897       AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
898               matched);
899
900       /*
901        * Show all as backbone before doing superposition(s)
902        * (residues used for matching will be shown as ribbon)
903        */
904       // todo better way to ensure synchronous than setting getReply true!!
905       executeCommands(commandGenerator.showBackbone(), true, null);
906
907       /*
908        * superpose each (other) structure to the reference in turn
909        */
910       for (int i = 0; i < structures.length; i++)
911       {
912         if (i != refStructure)
913         {
914           AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
915           List<StructureCommandI> commands = commandGenerator
916                   .superposeStructures(refAtoms,
917                   atomSpec);
918           List<String> replies = executeCommands(commands, true, null);
919           for (String reply : replies)
920           {
921             // return this error (Chimera only) to the user
922             if (reply.toLowerCase().contains("unequal numbers of atoms"))
923             {
924               error += "; " + reply;
925             }
926           }
927         }
928       }
929     }
930
931     return error;
932   }
933
934   private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
935           BitSet matched)
936   {
937     AtomSpecModel model = new AtomSpecModel();
938     int nextColumnMatch = matched.nextSetBit(0);
939     while (nextColumnMatch != -1)
940     {
941       int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
942       model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
943               superposeData.chain);
944       nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
945     }
946
947     return model;
948   }
949
950   /**
951    * returns the current sequenceRenderer that should be used to colour the
952    * structures
953    * 
954    * @param alignment
955    * 
956    * @return
957    */
958   public abstract SequenceRenderer getSequenceRenderer(
959           AlignmentViewPanel alignment);
960
961   /**
962    * Sends a command to the structure viewer to colour each chain with a
963    * distinct colour (to the extent supported by the viewer)
964    */
965   public void colourByChain()
966   {
967     colourBySequence = false;
968
969     // TODO: JAL-628 colour chains distinctly across all visible models
970
971     executeCommand(commandGenerator.colourByChain(), false,
972             COLOURING_STRUCTURES);
973   }
974
975   /**
976    * Sends a command to the structure viewer to colour each chain with a
977    * distinct colour (to the extent supported by the viewer)
978    */
979   public void colourByCharge()
980   {
981     colourBySequence = false;
982
983     executeCommands(commandGenerator.colourByCharge(), false,
984             COLOURING_STRUCTURES);
985   }
986
987   /**
988    * Sends a command to the structure to apply a colour scheme (defined in
989    * Jalview but not necessarily applied to the alignment), which defines a
990    * colour per residue letter. More complex schemes (e.g. that depend on
991    * consensus) cannot be used here and are ignored.
992    * 
993    * @param cs
994    */
995   public void colourByJalviewColourScheme(ColourSchemeI cs)
996   {
997     colourBySequence = false;
998
999     if (cs == null || !cs.isSimple())
1000     {
1001       return;
1002     }
1003     
1004     /*
1005      * build a map of {Residue3LetterCode, Color}
1006      */
1007     Map<String, Color> colours = new HashMap<>();
1008     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1009             false);
1010     for (String resName : residues)
1011     {
1012       char res = resName.length() == 3
1013               ? ResidueProperties.getSingleCharacterCode(resName)
1014               : resName.charAt(0);
1015       Color colour = cs.findColour(res, 0, null, null, 0f);
1016       colours.put(resName, colour);
1017     }
1018
1019     /*
1020      * pass to the command constructor, and send the command
1021      */
1022     List<StructureCommandI> cmd = commandGenerator
1023             .colourByResidues(colours);
1024     executeCommands(cmd, false, COLOURING_STRUCTURES);
1025   }
1026
1027   public void setBackgroundColour(Color col)
1028   {
1029     StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1030     executeCommand(cmd, false, null);
1031   }
1032
1033   /**
1034    * Sends one command to the structure viewer. If {@code getReply} is true, the
1035    * command is sent synchronously, otherwise in a deferred thread.
1036    * <p>
1037    * If a progress message is supplied, this is displayed before command
1038    * execution, and removed afterwards.
1039    * 
1040    * @param cmd
1041    * @param getReply
1042    * @param msg
1043    * @return
1044    */
1045   private List<String> executeCommand(StructureCommandI cmd,
1046           boolean getReply, String msg)
1047   {
1048     if (getReply)
1049     {
1050       /*
1051        * synchronous (same thread) execution so reply can be returned
1052        */
1053       final JalviewStructureDisplayI theViewer = getViewer();
1054       final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1055       try
1056       {
1057         return executeCommand(cmd, getReply);
1058       } finally
1059       {
1060         if (msg != null)
1061         {
1062           theViewer.stopProgressBar(null, handle);
1063         }
1064       }
1065     }
1066     else
1067     {
1068       /*
1069        * asynchronous (new thread) execution if no reply needed
1070        */
1071       final JalviewStructureDisplayI theViewer = getViewer();
1072       final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1073       
1074       SwingUtilities.invokeLater(new Runnable()
1075       {
1076         @Override
1077         public void run()
1078         {
1079           try
1080           {
1081             executeCommand(cmd, false);
1082           } finally
1083           {
1084             if (msg != null)
1085             {
1086               theViewer.stopProgressBar(null, handle);
1087             }
1088           }
1089         }
1090       });
1091       return null;
1092     }
1093   }
1094
1095   /**
1096    * Execute one structure viewer command. If {@code getReply} is true, may
1097    * optionally return one or more reply messages, else returns null.
1098    * 
1099    * @param cmd
1100    * @param getReply
1101    */
1102   protected abstract List<String> executeCommand(StructureCommandI cmd,
1103           boolean getReply);
1104
1105   /**
1106    * A helper method that converts list of commands to a vararg array
1107    * 
1108    * @param commands
1109    * @param getReply
1110    * @param msg
1111    */
1112   private List<String> executeCommands(List<StructureCommandI> commands,
1113           boolean getReply, String msg)
1114   {
1115     return executeCommands(getReply, msg,
1116             commands.toArray(new StructureCommandI[commands.size()]));
1117   }
1118
1119   /**
1120    * Executes one or more structure viewer commands. If a progress message is
1121    * provided, it is shown first, and removed after all commands have been run.
1122    * 
1123    * @param getReply
1124    * @param msg
1125    * @param commands
1126    * @return
1127    */
1128   protected List<String> executeCommands(boolean getReply, String msg,
1129           StructureCommandI[] commands)
1130   {
1131     // todo: tidy this up
1132
1133     /*
1134      * show progress message if specified
1135      */
1136     final JalviewStructureDisplayI theViewer = getViewer();
1137     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1138
1139     List<String> response = getReply ? new ArrayList<>() : null;
1140     try
1141     {
1142       for (StructureCommandI cmd : commands)
1143       {
1144         List<String> replies = executeCommand(cmd, getReply, null);
1145         if (getReply && replies != null)
1146         {
1147           response.addAll(replies);
1148         }
1149       }
1150       return response;
1151     } finally
1152     {
1153       if (msg != null)
1154       {
1155         theViewer.stopProgressBar(null, handle);
1156       }
1157     }
1158   }
1159
1160   /**
1161    * colour any structures associated with sequences in the given alignment
1162    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
1163    * if colourBySequence is enabled.
1164    */
1165   public void colourBySequence(AlignmentViewPanel alignmentv)
1166   {
1167     if (!colourBySequence || !isLoadingFinished())
1168     {
1169       return;
1170     }
1171     if (getSsm() == null)
1172     {
1173       return;
1174     }
1175     String[] files = getStructureFiles();
1176
1177     SequenceRenderer sr = getSequenceRenderer(alignmentv);
1178     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
1179             sequence, sr, alignmentv);
1180
1181     List<StructureCommandI> colourBySequenceCommands = commandGenerator
1182             .colourBySequence(colourMap);
1183     executeCommands(colourBySequenceCommands, false, null);
1184   }
1185
1186   /**
1187    * Centre the display in the structure viewer
1188    */
1189   public void focusView()
1190   {
1191     executeCommand(commandGenerator.focusView(), false, null);
1192   }
1193
1194   /**
1195    * Generates and executes a command to show only specified chains in the
1196    * structure viewer. The list of chains to show should contain entries
1197    * formatted as "pdbid:chaincode".
1198    * 
1199    * @param toShow
1200    */
1201   public void showChains(List<String> toShow)
1202   {
1203     // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1204
1205     /*
1206      * Reformat the pdbid:chainCode values as modelNo:chainCode
1207      * since this is what is needed to construct the viewer command
1208      * todo: find a less messy way to do this
1209      */
1210     List<String> showThese = new ArrayList<>();
1211     for (String chainId : toShow)
1212     {
1213       String[] tokens = chainId.split("\\:");
1214       if (tokens.length == 2)
1215       {
1216         String pdbFile = getFileForChain(chainId);
1217         String model = getModelIdForFile(pdbFile);
1218         showThese.add(model + ":" + tokens[1]);
1219       }
1220     }
1221     executeCommands(commandGenerator.showChains(showThese), false, null);
1222   }
1223
1224   /**
1225    * Answers the structure viewer's model id given a PDB file name. Returns an
1226    * empty string if model id is not found.
1227    * 
1228    * @param chainId
1229    * @return
1230    */
1231   protected abstract String getModelIdForFile(String chainId);
1232
1233   public boolean hasFileLoadingError()
1234   {
1235     return fileLoadingError != null && fileLoadingError.length() > 0;
1236   }
1237
1238   /**
1239    * Returns the FeatureRenderer for the given alignment view, or null if
1240    * feature display is turned off in the view.
1241    * 
1242    * @param avp
1243    * @return
1244    */
1245   public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1246   {
1247     AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1248             : avp;
1249     return ap.getAlignViewport().isShowSequenceFeatures()
1250             ? ap.getFeatureRenderer()
1251             : null;
1252   }
1253
1254   protected void setStructureCommands(StructureCommandsI cmd)
1255   {
1256     commandGenerator = cmd;
1257   }
1258
1259   /**
1260    * Records association of one chain id (formatted as "pdbid:chainCode") with
1261    * the corresponding PDB file name
1262    * 
1263    * @param chainId
1264    * @param fileName
1265    */
1266   public void addChainFile(String chainId, String fileName)
1267   {
1268     chainFile.put(chainId, fileName);
1269   }
1270
1271   /**
1272    * Returns the PDB filename for the given chain id (formatted as
1273    * "pdbid:chainCode"), or null if not found
1274    * 
1275    * @param chainId
1276    * @return
1277    */
1278   protected String getFileForChain(String chainId)
1279   {
1280     return chainFile.get(chainId);
1281   }
1282
1283   @Override
1284   public void updateColours(Object source)
1285   {
1286     AlignmentViewPanel ap = (AlignmentViewPanel) source;
1287     // ignore events from panels not used to colour this view
1288     if (!getViewer().isUsedForColourBy(ap))
1289     {
1290       return;
1291     }
1292     if (!isLoadingFromArchive())
1293     {
1294       colourBySequence(ap);
1295     }
1296   }
1297
1298   public StructureCommandsI getCommandGenerator()
1299   {
1300     return commandGenerator;
1301   }
1302
1303   protected abstract ViewerType getViewerType();
1304
1305   /**
1306    * Send a structure viewer command asynchronously in a new thread. If the
1307    * progress message is not null, display this message while the command is
1308    * executing.
1309    * 
1310    * @param command
1311    * @param progressMsg
1312    */
1313   protected void sendAsynchronousCommand(StructureCommandI command,
1314           String progressMsg)
1315   {
1316     final JalviewStructureDisplayI theViewer = getViewer();
1317     final long handle = progressMsg == null ? 0
1318             : theViewer.startProgressBar(progressMsg);
1319     SwingUtilities.invokeLater(new Runnable()
1320     {
1321       @Override
1322       public void run()
1323       {
1324         try
1325         {
1326           executeCommand(command, false, null);
1327         } finally
1328         {
1329           if (progressMsg != null)
1330           {
1331             theViewer.stopProgressBar(null, handle);
1332           }
1333         }
1334       }
1335     });
1336
1337   }
1338
1339   /**
1340    * Builds a data structure which records mapped structure residues for each
1341    * colour. From this we can easily generate the viewer commands for colour by
1342    * sequence. Constructs and returns a map of {@code Color} to
1343    * {@code AtomSpecModel}, where the atomspec model holds
1344    * 
1345    * <pre>
1346    *   Model ids
1347    *     Chains
1348    *       Residue positions
1349    * </pre>
1350    * 
1351    * Ordering is by order of addition (for colours), natural ordering (for
1352    * models and chains)
1353    * 
1354    * @param ssm
1355    * @param files
1356    * @param sequence
1357    * @param sr
1358    * @param viewPanel
1359    * @return
1360    */
1361   protected Map<Object, AtomSpecModel> buildColoursMap(
1362           StructureSelectionManager ssm, String[] files,
1363           SequenceI[][] sequence, SequenceRenderer sr, AlignmentViewPanel viewPanel)
1364   {
1365     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1366     FeatureColourFinder finder = new FeatureColourFinder(fr);
1367     AlignViewportI viewport = viewPanel.getAlignViewport();
1368     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1369     AlignmentI al = viewport.getAlignment();
1370     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1371     Color lastColour = null;
1372   
1373     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1374     {
1375       // todo indirect this resolution / allow override
1376       final String modelId = getModelIdForFile(files[pdbfnum]);
1377       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1378   
1379       if (mapping == null || mapping.length < 1)
1380       {
1381         continue;
1382       }
1383   
1384       int startPos = -1, lastPos = -1;
1385       String lastChain = "";
1386       for (int s = 0; s < sequence[pdbfnum].length; s++)
1387       {
1388         for (int sp, m = 0; m < mapping.length; m++)
1389         {
1390           final SequenceI seq = sequence[pdbfnum][s];
1391           if (mapping[m].getSequence() == seq
1392                   && (sp = al.findIndex(seq)) > -1)
1393           {
1394             SequenceI asp = al.getSequenceAt(sp);
1395             for (int r = 0; r < asp.getLength(); r++)
1396             {
1397               // no mapping to gaps in sequence
1398               if (Comparison.isGap(asp.getCharAt(r)))
1399               {
1400                 continue;
1401               }
1402               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1403   
1404               if (pos < 1 || pos == lastPos)
1405               {
1406                 continue;
1407               }
1408   
1409               Color colour = sr.getResidueColour(seq, r, finder);
1410   
1411               /*
1412                * darker colour for hidden regions
1413                */
1414               if (!cs.isVisible(r))
1415               {
1416                 colour = Color.GRAY;
1417               }
1418   
1419               final String chain = mapping[m].getChain();
1420   
1421               /*
1422                * Just keep incrementing the end position for this colour range
1423                * _unless_ colour, PDB model or chain has changed, or there is a
1424                * gap in the mapped residue sequence
1425                */
1426               final boolean newColour = !colour.equals(lastColour);
1427               final boolean nonContig = lastPos + 1 != pos;
1428               final boolean newChain = !chain.equals(lastChain);
1429               if (newColour || nonContig || newChain)
1430               {
1431                 if (startPos != -1)
1432                 {
1433                   addAtomSpecRange(colourMap, lastColour, modelId,
1434                           startPos, lastPos, lastChain);
1435                 }
1436                 startPos = pos;
1437               }
1438               lastColour = colour;
1439               lastPos = pos;
1440               lastChain = chain;
1441             }
1442             // final colour range
1443             if (lastColour != null)
1444             {
1445               addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1446                       lastPos, lastChain);
1447             }
1448             // break;
1449           }
1450         }
1451       }
1452     }
1453     return colourMap;
1454   }
1455
1456   /**
1457    * todo better refactoring (map lookup or similar to get viewer structure id)
1458    * 
1459    * @param pdbfnum
1460    * @param file
1461    * @return
1462    */
1463   protected String getModelId(int pdbfnum, String file)
1464   {
1465     return String.valueOf(pdbfnum);
1466   }
1467
1468   /**
1469    * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1470    * full PDB file path
1471    * 
1472    * @param pdb
1473    * @param file
1474    */
1475   public void stashFoundChains(StructureFile pdb, String file)
1476   {
1477     for (int i = 0; i < pdb.getChains().size(); i++)
1478     {
1479       String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1480       addChainFile(chid, file);
1481       getChainNames().add(chid);
1482     }
1483   }
1484
1485   /**
1486    * Helper method to add one contiguous range to the AtomSpec model for the given
1487    * value (creating the model if necessary). As used by Jalview, {@code value} is
1488    * <ul>
1489    * <li>a colour, when building a 'colour structure by sequence' command</li>
1490    * <li>a feature value, when building a 'set Chimera attributes from features'
1491    * command</li>
1492    * </ul>
1493    * 
1494    * @param map
1495    * @param value
1496    * @param model
1497    * @param startPos
1498    * @param endPos
1499    * @param chain
1500    */
1501   public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1502           Object value,
1503           String model, int startPos, int endPos, String chain)
1504   {
1505     /*
1506      * Get/initialize map of data for the colour
1507      */
1508     AtomSpecModel atomSpec = map.get(value);
1509     if (atomSpec == null)
1510     {
1511       atomSpec = new AtomSpecModel();
1512       map.put(value, atomSpec);
1513     }
1514   
1515     atomSpec.addRange(model, startPos, endPos, chain);
1516   }
1517 }