JAL-3551 tidying, improved commands, fix Jmol model number derivation
[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, atomSpec);
917           List<String> replies = executeCommands(commands, true, null);
918           for (String reply : replies)
919           {
920             // return this error (Chimera only) to the user
921             if (reply.toLowerCase().contains("unequal numbers of atoms"))
922             {
923               error += "; " + reply;
924             }
925           }
926         }
927       }
928     }
929
930     return error;
931   }
932
933   private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
934           BitSet matched)
935   {
936     AtomSpecModel model = new AtomSpecModel();
937     int nextColumnMatch = matched.nextSetBit(0);
938     while (nextColumnMatch != -1)
939     {
940       int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
941       model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
942               superposeData.chain);
943       nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
944     }
945
946     return model;
947   }
948
949   /**
950    * returns the current sequenceRenderer that should be used to colour the
951    * structures
952    * 
953    * @param alignment
954    * 
955    * @return
956    */
957   public abstract SequenceRenderer getSequenceRenderer(
958           AlignmentViewPanel alignment);
959
960   /**
961    * Sends a command to the structure viewer to colour each chain with a
962    * distinct colour (to the extent supported by the viewer)
963    */
964   public void colourByChain()
965   {
966     colourBySequence = false;
967
968     // TODO: JAL-628 colour chains distinctly across all visible models
969
970     executeCommand(commandGenerator.colourByChain(), false,
971             COLOURING_STRUCTURES);
972   }
973
974   /**
975    * Sends a command to the structure viewer to colour each chain with a
976    * distinct colour (to the extent supported by the viewer)
977    */
978   public void colourByCharge()
979   {
980     colourBySequence = false;
981
982     executeCommands(commandGenerator.colourByCharge(), false,
983             COLOURING_STRUCTURES);
984   }
985
986   /**
987    * Sends a command to the structure to apply a colour scheme (defined in
988    * Jalview but not necessarily applied to the alignment), which defines a
989    * colour per residue letter. More complex schemes (e.g. that depend on
990    * consensus) cannot be used here and are ignored.
991    * 
992    * @param cs
993    */
994   public void colourByJalviewColourScheme(ColourSchemeI cs)
995   {
996     colourBySequence = false;
997
998     if (cs == null || !cs.isSimple())
999     {
1000       return;
1001     }
1002     
1003     /*
1004      * build a map of {Residue3LetterCode, Color}
1005      */
1006     Map<String, Color> colours = new HashMap<>();
1007     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1008             false);
1009     for (String resName : residues)
1010     {
1011       char res = resName.length() == 3
1012               ? ResidueProperties.getSingleCharacterCode(resName)
1013               : resName.charAt(0);
1014       Color colour = cs.findColour(res, 0, null, null, 0f);
1015       colours.put(resName, colour);
1016     }
1017
1018     /*
1019      * pass to the command constructor, and send the command
1020      */
1021     List<StructureCommandI> cmd = commandGenerator
1022             .colourByResidues(colours);
1023     executeCommands(cmd, false, COLOURING_STRUCTURES);
1024   }
1025
1026   public void setBackgroundColour(Color col)
1027   {
1028     StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1029     executeCommand(cmd, false, null);
1030   }
1031
1032   /**
1033    * Sends one command to the structure viewer. If {@code getReply} is true, the
1034    * command is sent synchronously, otherwise in a deferred thread.
1035    * <p>
1036    * If a progress message is supplied, this is displayed before command
1037    * execution, and removed afterwards.
1038    * 
1039    * @param cmd
1040    * @param getReply
1041    * @param msg
1042    * @return
1043    */
1044   private List<String> executeCommand(StructureCommandI cmd,
1045           boolean getReply, String msg)
1046   {
1047     if (getReply)
1048     {
1049       /*
1050        * synchronous (same thread) execution so reply can be returned
1051        */
1052       final JalviewStructureDisplayI theViewer = getViewer();
1053       final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1054       try
1055       {
1056         return executeCommand(cmd, getReply);
1057       } finally
1058       {
1059         if (msg != null)
1060         {
1061           theViewer.stopProgressBar(null, handle);
1062         }
1063       }
1064     }
1065     else
1066     {
1067       /*
1068        * asynchronous (new thread) execution if no reply needed
1069        */
1070       final JalviewStructureDisplayI theViewer = getViewer();
1071       final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1072       
1073       SwingUtilities.invokeLater(new Runnable()
1074       {
1075         @Override
1076         public void run()
1077         {
1078           try
1079           {
1080             executeCommand(cmd, false);
1081           } finally
1082           {
1083             if (msg != null)
1084             {
1085               theViewer.stopProgressBar(null, handle);
1086             }
1087           }
1088         }
1089       });
1090       return null;
1091     }
1092   }
1093
1094   /**
1095    * Execute one structure viewer command. If {@code getReply} is true, may
1096    * optionally return one or more reply messages, else returns null.
1097    * 
1098    * @param cmd
1099    * @param getReply
1100    */
1101   protected abstract List<String> executeCommand(StructureCommandI cmd,
1102           boolean getReply);
1103
1104   /**
1105    * A helper method that converts list of commands to a vararg array
1106    * 
1107    * @param commands
1108    * @param getReply
1109    * @param msg
1110    */
1111   private List<String> executeCommands(List<StructureCommandI> commands,
1112           boolean getReply, String msg)
1113   {
1114     return executeCommands(getReply, msg,
1115             commands.toArray(new StructureCommandI[commands.size()]));
1116   }
1117
1118   /**
1119    * Executes one or more structure viewer commands. If a progress message is
1120    * provided, it is shown first, and removed after all commands have been run.
1121    * 
1122    * @param getReply
1123    * @param msg
1124    * @param commands
1125    * @return
1126    */
1127   protected List<String> executeCommands(boolean getReply, String msg,
1128           StructureCommandI[] commands)
1129   {
1130     // todo: tidy this up
1131
1132     /*
1133      * show progress message if specified
1134      */
1135     final JalviewStructureDisplayI theViewer = getViewer();
1136     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1137
1138     List<String> response = getReply ? new ArrayList<>() : null;
1139     try
1140     {
1141       for (StructureCommandI cmd : commands)
1142       {
1143         List<String> replies = executeCommand(cmd, getReply, null);
1144         if (getReply && replies != null)
1145         {
1146           response.addAll(replies);
1147         }
1148       }
1149       return response;
1150     } finally
1151     {
1152       if (msg != null)
1153       {
1154         theViewer.stopProgressBar(null, handle);
1155       }
1156     }
1157   }
1158
1159   /**
1160    * colour any structures associated with sequences in the given alignment
1161    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
1162    * if colourBySequence is enabled.
1163    */
1164   public void colourBySequence(AlignmentViewPanel alignmentv)
1165   {
1166     if (!colourBySequence || !isLoadingFinished())
1167     {
1168       return;
1169     }
1170     if (getSsm() == null)
1171     {
1172       return;
1173     }
1174     String[] files = getStructureFiles();
1175
1176     SequenceRenderer sr = getSequenceRenderer(alignmentv);
1177     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
1178             sequence, sr, alignmentv);
1179
1180     List<StructureCommandI> colourBySequenceCommands = commandGenerator
1181             .colourBySequence(colourMap);
1182     executeCommands(colourBySequenceCommands, false, null);
1183   }
1184
1185   /**
1186    * Centre the display in the structure viewer
1187    */
1188   public void focusView()
1189   {
1190     executeCommand(commandGenerator.focusView(), false, null);
1191   }
1192
1193   /**
1194    * Generates and executes a command to show only specified chains in the
1195    * structure viewer. The list of chains to show should contain entries
1196    * formatted as "pdbid:chaincode".
1197    * 
1198    * @param toShow
1199    */
1200   public void showChains(List<String> toShow)
1201   {
1202     // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1203
1204     /*
1205      * Reformat the pdbid:chainCode values as modelNo:chainCode
1206      * since this is what is needed to construct the viewer command
1207      * todo: find a less messy way to do this
1208      */
1209     List<String> showThese = new ArrayList<>();
1210     for (String chainId : toShow)
1211     {
1212       String[] tokens = chainId.split("\\:");
1213       if (tokens.length == 2)
1214       {
1215         String pdbFile = getFileForChain(chainId);
1216         String model = getModelIdForFile(pdbFile);
1217         showThese.add(model + ":" + tokens[1]);
1218       }
1219     }
1220     executeCommands(commandGenerator.showChains(showThese), false, null);
1221   }
1222
1223   /**
1224    * Answers the structure viewer's model id given a PDB file name. Returns an
1225    * empty string if model id is not found.
1226    * 
1227    * @param chainId
1228    * @return
1229    */
1230   protected abstract String getModelIdForFile(String chainId);
1231
1232   public boolean hasFileLoadingError()
1233   {
1234     return fileLoadingError != null && fileLoadingError.length() > 0;
1235   }
1236
1237   /**
1238    * Returns the FeatureRenderer for the given alignment view, or null if
1239    * feature display is turned off in the view.
1240    * 
1241    * @param avp
1242    * @return
1243    */
1244   public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1245   {
1246     AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1247             : avp;
1248     return ap.getAlignViewport().isShowSequenceFeatures()
1249             ? ap.getFeatureRenderer()
1250             : null;
1251   }
1252
1253   protected void setStructureCommands(StructureCommandsI cmd)
1254   {
1255     commandGenerator = cmd;
1256   }
1257
1258   /**
1259    * Records association of one chain id (formatted as "pdbid:chainCode") with
1260    * the corresponding PDB file name
1261    * 
1262    * @param chainId
1263    * @param fileName
1264    */
1265   public void addChainFile(String chainId, String fileName)
1266   {
1267     chainFile.put(chainId, fileName);
1268   }
1269
1270   /**
1271    * Returns the PDB filename for the given chain id (formatted as
1272    * "pdbid:chainCode"), or null if not found
1273    * 
1274    * @param chainId
1275    * @return
1276    */
1277   protected String getFileForChain(String chainId)
1278   {
1279     return chainFile.get(chainId);
1280   }
1281
1282   @Override
1283   public void updateColours(Object source)
1284   {
1285     AlignmentViewPanel ap = (AlignmentViewPanel) source;
1286     // ignore events from panels not used to colour this view
1287     if (!getViewer().isUsedForColourBy(ap))
1288     {
1289       return;
1290     }
1291     if (!isLoadingFromArchive())
1292     {
1293       colourBySequence(ap);
1294     }
1295   }
1296
1297   public StructureCommandsI getCommandGenerator()
1298   {
1299     return commandGenerator;
1300   }
1301
1302   protected abstract ViewerType getViewerType();
1303
1304   /**
1305    * Send a structure viewer command asynchronously in a new thread. If the
1306    * progress message is not null, display this message while the command is
1307    * executing.
1308    * 
1309    * @param command
1310    * @param progressMsg
1311    */
1312   protected void sendAsynchronousCommand(StructureCommandI command,
1313           String progressMsg)
1314   {
1315     final JalviewStructureDisplayI theViewer = getViewer();
1316     final long handle = progressMsg == null ? 0
1317             : theViewer.startProgressBar(progressMsg);
1318     SwingUtilities.invokeLater(new Runnable()
1319     {
1320       @Override
1321       public void run()
1322       {
1323         try
1324         {
1325           executeCommand(command, false, null);
1326         } finally
1327         {
1328           if (progressMsg != null)
1329           {
1330             theViewer.stopProgressBar(null, handle);
1331           }
1332         }
1333       }
1334     });
1335
1336   }
1337
1338   /**
1339    * Builds a data structure which records mapped structure residues for each
1340    * colour. From this we can easily generate the viewer commands for colour by
1341    * sequence. Constructs and returns a map of {@code Color} to
1342    * {@code AtomSpecModel}, where the atomspec model holds
1343    * 
1344    * <pre>
1345    *   Model ids
1346    *     Chains
1347    *       Residue positions
1348    * </pre>
1349    * 
1350    * Ordering is by order of addition (for colours), natural ordering (for
1351    * models and chains)
1352    * 
1353    * @param ssm
1354    * @param files
1355    * @param sequence
1356    * @param sr
1357    * @param viewPanel
1358    * @return
1359    */
1360   protected Map<Object, AtomSpecModel> buildColoursMap(
1361           StructureSelectionManager ssm, String[] files,
1362           SequenceI[][] sequence, SequenceRenderer sr, AlignmentViewPanel viewPanel)
1363   {
1364     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1365     FeatureColourFinder finder = new FeatureColourFinder(fr);
1366     AlignViewportI viewport = viewPanel.getAlignViewport();
1367     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1368     AlignmentI al = viewport.getAlignment();
1369     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1370     Color lastColour = null;
1371   
1372     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1373     {
1374       // todo indirect this resolution / allow override
1375       final String modelId = getModelIdForFile(files[pdbfnum]);
1376       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1377   
1378       if (mapping == null || mapping.length < 1)
1379       {
1380         continue;
1381       }
1382   
1383       int startPos = -1, lastPos = -1;
1384       String lastChain = "";
1385       for (int s = 0; s < sequence[pdbfnum].length; s++)
1386       {
1387         for (int sp, m = 0; m < mapping.length; m++)
1388         {
1389           final SequenceI seq = sequence[pdbfnum][s];
1390           if (mapping[m].getSequence() == seq
1391                   && (sp = al.findIndex(seq)) > -1)
1392           {
1393             SequenceI asp = al.getSequenceAt(sp);
1394             for (int r = 0; r < asp.getLength(); r++)
1395             {
1396               // no mapping to gaps in sequence
1397               if (Comparison.isGap(asp.getCharAt(r)))
1398               {
1399                 continue;
1400               }
1401               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1402   
1403               if (pos < 1 || pos == lastPos)
1404               {
1405                 continue;
1406               }
1407   
1408               Color colour = sr.getResidueColour(seq, r, finder);
1409   
1410               /*
1411                * darker colour for hidden regions
1412                */
1413               if (!cs.isVisible(r))
1414               {
1415                 colour = Color.GRAY;
1416               }
1417   
1418               final String chain = mapping[m].getChain();
1419   
1420               /*
1421                * Just keep incrementing the end position for this colour range
1422                * _unless_ colour, PDB model or chain has changed, or there is a
1423                * gap in the mapped residue sequence
1424                */
1425               final boolean newColour = !colour.equals(lastColour);
1426               final boolean nonContig = lastPos + 1 != pos;
1427               final boolean newChain = !chain.equals(lastChain);
1428               if (newColour || nonContig || newChain)
1429               {
1430                 if (startPos != -1)
1431                 {
1432                   addAtomSpecRange(colourMap, lastColour, modelId,
1433                           startPos, lastPos, lastChain);
1434                 }
1435                 startPos = pos;
1436               }
1437               lastColour = colour;
1438               lastPos = pos;
1439               lastChain = chain;
1440             }
1441             // final colour range
1442             if (lastColour != null)
1443             {
1444               addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1445                       lastPos, lastChain);
1446             }
1447             // break;
1448           }
1449         }
1450       }
1451     }
1452     return colourMap;
1453   }
1454
1455   /**
1456    * todo better refactoring (map lookup or similar to get viewer structure id)
1457    * 
1458    * @param pdbfnum
1459    * @param file
1460    * @return
1461    */
1462   protected String getModelId(int pdbfnum, String file)
1463   {
1464     return String.valueOf(pdbfnum);
1465   }
1466
1467   /**
1468    * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1469    * full PDB file path
1470    * 
1471    * @param pdb
1472    * @param file
1473    */
1474   public void stashFoundChains(StructureFile pdb, String file)
1475   {
1476     for (int i = 0; i < pdb.getChains().size(); i++)
1477     {
1478       String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1479       addChainFile(chid, file);
1480       getChainNames().add(chid);
1481     }
1482   }
1483
1484   /**
1485    * Helper method to add one contiguous range to the AtomSpec model for the given
1486    * value (creating the model if necessary). As used by Jalview, {@code value} is
1487    * <ul>
1488    * <li>a colour, when building a 'colour structure by sequence' command</li>
1489    * <li>a feature value, when building a 'set Chimera attributes from features'
1490    * command</li>
1491    * </ul>
1492    * 
1493    * @param map
1494    * @param value
1495    * @param model
1496    * @param startPos
1497    * @param endPos
1498    * @param chain
1499    */
1500   public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1501           Object value,
1502           String model, int startPos, int endPos, String chain)
1503   {
1504     /*
1505      * Get/initialize map of data for the colour
1506      */
1507     AtomSpecModel atomSpec = map.get(value);
1508     if (atomSpec == null)
1509     {
1510       atomSpec = new AtomSpecModel();
1511       map.put(value, atomSpec);
1512     }
1513   
1514     atomSpec.addRange(model, startPos, endPos, chain);
1515   }
1516 }