dcd6da8d09bce37eeca9fe53e045a7446e9f63c7
[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 java.awt.Color;
24 import java.io.File;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.BitSet;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.swing.SwingUtilities;
35
36 import jalview.api.AlignViewportI;
37 import jalview.api.AlignmentViewPanel;
38 import jalview.api.FeatureRenderer;
39 import jalview.api.SequenceRenderer;
40 import jalview.api.StructureSelectionManagerProvider;
41 import jalview.api.structures.JalviewStructureDisplayI;
42 import jalview.bin.Cache;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.HiddenColumns;
45 import jalview.datamodel.MappedFeatures;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.SequenceFeature;
48 import jalview.datamodel.SequenceI;
49 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
50 import jalview.gui.Desktop;
51 import jalview.gui.StructureViewer.ViewerType;
52 import jalview.io.DataSourceType;
53 import jalview.io.StructureFile;
54 import jalview.renderer.seqfeatures.FeatureColourFinder;
55 import jalview.schemes.ColourSchemeI;
56 import jalview.schemes.ResidueProperties;
57 import jalview.structure.AtomSpec;
58 import jalview.structure.AtomSpecModel;
59 import jalview.structure.StructureCommandI;
60 import jalview.structure.StructureCommandsI;
61 import jalview.structure.StructureListener;
62 import jalview.structure.StructureMapping;
63 import jalview.structure.StructureSelectionManager;
64 import jalview.util.Comparison;
65 import jalview.util.MessageManager;
66
67 /**
68  * 
69  * A base class to hold common function for protein structure model binding.
70  * Initial version created by refactoring JMol and Chimera binding models, but
71  * other structure viewers could in principle be accommodated in future.
72  * 
73  * @author gmcarstairs
74  *
75  */
76 public abstract class AAStructureBindingModel
77         extends SequenceStructureBindingModel
78         implements StructureListener, StructureSelectionManagerProvider
79 {
80   /**
81    * Data bean class to simplify parameterisation in superposeStructures
82    */
83   public static class SuperposeData
84   {
85     public String filename;
86   
87     public String pdbId;
88   
89     public String chain = "";
90   
91     public boolean isRna;
92   
93     /*
94      * The pdb residue number (if any) mapped to columns of the alignment
95      */
96     public int[] pdbResNo; // or use SparseIntArray?
97   
98     public String modelId;
99   
100     /**
101      * Constructor
102      * 
103      * @param width
104      *          width of alignment (number of columns that may potentially
105      *          participate in superposition)
106      * @param model
107      *          structure viewer model number
108      */
109     public SuperposeData(int width, String model)
110     {
111       pdbResNo = new int[width];
112       modelId = model;
113     }
114   }
115
116   private static final int MIN_POS_TO_SUPERPOSE = 4;
117
118   private static final String COLOURING_STRUCTURES = MessageManager
119           .getString("status.colouring_structures");
120
121   /*
122    * the Jalview panel through which the user interacts
123    * with the structure viewer
124    */
125   private JalviewStructureDisplayI viewer;
126
127   /*
128    * helper that generates command syntax
129    */
130   private StructureCommandsI commandGenerator;
131
132   private StructureSelectionManager ssm;
133
134   /*
135    * modelled chains, formatted as "pdbid:chainCode"
136    */
137   private List<String> chainNames;
138
139   /*
140    * lookup of pdb file name by key "pdbid:chainCode"
141    */
142   private Map<String, String> chainFile;
143
144   /*
145    * distinct PDB entries (pdb files) associated
146    * with sequences
147    */
148   private PDBEntry[] pdbEntry;
149
150   /*
151    * sequences mapped to each pdbentry
152    */
153   private SequenceI[][] sequence;
154
155   /*
156    * array of target chains for sequences - tied to pdbentry and sequence[]
157    */
158   private String[][] chains;
159
160   /*
161    * datasource protocol for access to PDBEntrylatest
162    */
163   DataSourceType protocol = null;
164
165   protected boolean colourBySequence = true;
166
167   private boolean nucleotide;
168
169   private boolean finishedInit = false;
170
171   /**
172    * current set of model filenames loaded in the viewer
173    */
174   protected String[] modelFileNames = null;
175
176   public String fileLoadingError;
177
178   /**
179    * Constructor
180    * 
181    * @param ssm
182    * @param seqs
183    */
184   public AAStructureBindingModel(StructureSelectionManager ssm,
185           SequenceI[][] seqs)
186   {
187     this.ssm = ssm;
188     this.sequence = seqs;
189     chainNames = new ArrayList<>();
190     chainFile = new HashMap<>();
191   }
192
193   /**
194    * Constructor
195    * 
196    * @param ssm
197    * @param pdbentry
198    * @param sequenceIs
199    * @param protocol
200    */
201   public AAStructureBindingModel(StructureSelectionManager ssm,
202           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
203           DataSourceType protocol)
204   {
205     this(ssm, sequenceIs);
206     this.nucleotide = Comparison.isNucleotide(sequenceIs);
207     this.pdbEntry = pdbentry;
208     this.protocol = protocol;
209     resolveChains();
210   }
211
212   private boolean resolveChains()
213   {
214     /**
215      * final count of chain mappings discovered
216      */
217     int chainmaps = 0;
218     // JBPNote: JAL-2693 - this should be a list of chain mappings per
219     // [pdbentry][sequence]
220     String[][] newchains = new String[pdbEntry.length][];
221     int pe = 0;
222     for (PDBEntry pdb : pdbEntry)
223     {
224       SequenceI[] seqsForPdb = sequence[pe];
225       if (seqsForPdb != null)
226       {
227         newchains[pe] = new String[seqsForPdb.length];
228         int se = 0;
229         for (SequenceI asq : seqsForPdb)
230         {
231           String chain = (chains != null && chains[pe] != null)
232                   ? chains[pe][se]
233                   : null;
234           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
235                   : asq.getDatasetSequence();
236           if (sq.getAllPDBEntries() != null)
237           {
238             for (PDBEntry pdbentry : sq.getAllPDBEntries())
239             {
240               if (pdb.getFile() != null && pdbentry.getFile() != null
241                       && pdb.getFile().equals(pdbentry.getFile()))
242               {
243                 String chaincode = pdbentry.getChainCode();
244                 if (chaincode != null && chaincode.length() > 0)
245                 {
246                   chain = chaincode;
247                   chainmaps++;
248                   break;
249                 }
250               }
251             }
252           }
253           newchains[pe][se] = chain;
254           se++;
255         }
256         pe++;
257       }
258     }
259
260     chains = newchains;
261     return chainmaps > 0;
262   }
263   public StructureSelectionManager getSsm()
264   {
265     return ssm;
266   }
267
268   /**
269    * Returns the i'th PDBEntry (or null)
270    * 
271    * @param i
272    * @return
273    */
274   public PDBEntry getPdbEntry(int i)
275   {
276     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
277   }
278
279   /**
280    * Answers true if this binding includes the given PDB id, else false
281    * 
282    * @param pdbId
283    * @return
284    */
285   public boolean hasPdbId(String pdbId)
286   {
287     if (pdbEntry != null)
288     {
289       for (PDBEntry pdb : pdbEntry)
290       {
291         if (pdb.getId().equals(pdbId))
292         {
293           return true;
294         }
295       }
296     }
297     return false;
298   }
299
300   /**
301    * Returns the number of modelled PDB file entries.
302    * 
303    * @return
304    */
305   public int getPdbCount()
306   {
307     return pdbEntry == null ? 0 : pdbEntry.length;
308   }
309
310   public SequenceI[][] getSequence()
311   {
312     return sequence;
313   }
314
315   public String[][] getChains()
316   {
317     return chains;
318   }
319
320   public DataSourceType getProtocol()
321   {
322     return protocol;
323   }
324
325   // TODO may remove this if calling methods can be pulled up here
326   protected void setPdbentry(PDBEntry[] pdbentry)
327   {
328     this.pdbEntry = pdbentry;
329   }
330
331   protected void setSequence(SequenceI[][] sequence)
332   {
333     this.sequence = sequence;
334   }
335
336   protected void setChains(String[][] chains)
337   {
338     this.chains = chains;
339   }
340
341   /**
342    * Construct a title string for the viewer window based on the data Jalview
343    * knows about
344    * 
345    * @param viewerName
346    *          TODO
347    * @param verbose
348    * 
349    * @return
350    */
351   public String getViewerTitle(String viewerName, boolean verbose)
352   {
353     if (getSequence() == null || getSequence().length < 1
354             || getPdbCount() < 1 || getSequence()[0].length < 1)
355     {
356       return ("Jalview " + viewerName + " Window");
357     }
358     // TODO: give a more informative title when multiple structures are
359     // displayed.
360     StringBuilder title = new StringBuilder(64);
361     final PDBEntry pdbe = getPdbEntry(0);
362     title.append(viewerName + " view for " + getSequence()[0][0].getName()
363             + ":" + pdbe.getId());
364
365     if (verbose)
366     {
367       String method = (String) pdbe.getProperty("method");
368       if (method != null)
369       {
370         title.append(" Method: ").append(method);
371       }
372       String chain = (String) pdbe.getProperty("chains");
373       if (chain != null)
374       {
375         title.append(" Chain:").append(chain);
376       }
377     }
378     return title.toString();
379   }
380
381   /**
382    * Called by after closeViewer is called, to release any resources and
383    * references so they can be garbage collected. Override if needed.
384    */
385   protected void releaseUIResources()
386   {
387   }
388
389   @Override
390   public void releaseReferences(Object svl)
391   {
392   }
393
394   public boolean isColourBySequence()
395   {
396     return colourBySequence;
397   }
398
399   /**
400    * Called when the binding thinks the UI needs to be refreshed after a
401    * structure viewer state change. This could be because structures were
402    * loaded, or because an error has occurred. Default does nothing, override as
403    * required.
404    */
405   public void refreshGUI()
406   {
407   }
408
409   /**
410    * Instruct the Jalview binding to update the pdbentries vector if necessary
411    * prior to matching the jmol view's contents to the list of structure files
412    * Jalview knows about. By default does nothing, override as required.
413    */
414   public void refreshPdbEntries()
415   {
416   }
417
418   public void setColourBySequence(boolean colourBySequence)
419   {
420     this.colourBySequence = colourBySequence;
421   }
422
423   protected void addSequenceAndChain(int pe, SequenceI[] seq,
424           String[] tchain)
425   {
426     if (pe < 0 || pe >= getPdbCount())
427     {
428       throw new Error(MessageManager.formatMessage(
429               "error.implementation_error_no_pdbentry_from_index",
430               new Object[]
431               { Integer.valueOf(pe).toString() }));
432     }
433     final String nullChain = "TheNullChain";
434     List<SequenceI> s = new ArrayList<>();
435     List<String> c = new ArrayList<>();
436     if (getChains() == null)
437     {
438       setChains(new String[getPdbCount()][]);
439     }
440     if (getSequence()[pe] != null)
441     {
442       for (int i = 0; i < getSequence()[pe].length; i++)
443       {
444         s.add(getSequence()[pe][i]);
445         if (getChains()[pe] != null)
446         {
447           if (i < getChains()[pe].length)
448           {
449             c.add(getChains()[pe][i]);
450           }
451           else
452           {
453             c.add(nullChain);
454           }
455         }
456         else
457         {
458           if (tchain != null && tchain.length > 0)
459           {
460             c.add(nullChain);
461           }
462         }
463       }
464     }
465     for (int i = 0; i < seq.length; i++)
466     {
467       if (!s.contains(seq[i]))
468       {
469         s.add(seq[i]);
470         if (tchain != null && i < tchain.length)
471         {
472           c.add(tchain[i] == null ? nullChain : tchain[i]);
473         }
474       }
475     }
476     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
477     getSequence()[pe] = tmp;
478     if (c.size() > 0)
479     {
480       String[] tch = c.toArray(new String[c.size()]);
481       for (int i = 0; i < tch.length; i++)
482       {
483         if (tch[i] == nullChain)
484         {
485           tch[i] = null;
486         }
487       }
488       getChains()[pe] = tch;
489     }
490     else
491     {
492       getChains()[pe] = null;
493     }
494   }
495
496   /**
497    * add structures and any known sequence associations
498    * 
499    * @returns the pdb entries added to the current set.
500    */
501   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
502           SequenceI[][] seq, String[][] chns)
503   {
504     List<PDBEntry> v = new ArrayList<>();
505     List<int[]> rtn = new ArrayList<>();
506     for (int i = 0; i < getPdbCount(); i++)
507     {
508       v.add(getPdbEntry(i));
509     }
510     for (int i = 0; i < pdbe.length; i++)
511     {
512       int r = v.indexOf(pdbe[i]);
513       if (r == -1 || r >= getPdbCount())
514       {
515         rtn.add(new int[] { v.size(), i });
516         v.add(pdbe[i]);
517       }
518       else
519       {
520         // just make sure the sequence/chain entries are all up to date
521         addSequenceAndChain(r, seq[i], chns[i]);
522       }
523     }
524     pdbe = v.toArray(new PDBEntry[v.size()]);
525     setPdbentry(pdbe);
526     if (rtn.size() > 0)
527     {
528       // expand the tied sequence[] and string[] arrays
529       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
530       String[][] sch = new String[getPdbCount()][];
531       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
532       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
533       setSequence(sqs);
534       setChains(sch);
535       pdbe = new PDBEntry[rtn.size()];
536       for (int r = 0; r < pdbe.length; r++)
537       {
538         int[] stri = (rtn.get(r));
539         // record the pdb file as a new addition
540         pdbe[r] = getPdbEntry(stri[0]);
541         // and add the new sequence/chain entries
542         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
543       }
544     }
545     else
546     {
547       pdbe = null;
548     }
549     return pdbe;
550   }
551
552   /**
553    * Add sequences to the pe'th pdbentry's sequence set.
554    * 
555    * @param pe
556    * @param seq
557    */
558   public void addSequence(int pe, SequenceI[] seq)
559   {
560     addSequenceAndChain(pe, seq, null);
561   }
562
563   /**
564    * add the given sequences to the mapping scope for the given pdb file handle
565    * 
566    * @param pdbFile
567    *          - pdbFile identifier
568    * @param seq
569    *          - set of sequences it can be mapped to
570    */
571   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
572   {
573     for (int pe = 0; pe < getPdbCount(); pe++)
574     {
575       if (getPdbEntry(pe).getFile().equals(pdbFile))
576       {
577         addSequence(pe, seq);
578       }
579     }
580   }
581
582   @Override
583   public abstract void highlightAtoms(List<AtomSpec> atoms);
584
585   protected boolean isNucleotide()
586   {
587     return this.nucleotide;
588   }
589
590   /**
591    * Returns a readable description of all mappings for the wrapped pdbfile to
592    * any mapped sequences
593    * 
594    * @param pdbfile
595    * @param seqs
596    * @return
597    */
598   public String printMappings()
599   {
600     if (pdbEntry == null)
601     {
602       return "";
603     }
604     StringBuilder sb = new StringBuilder(128);
605     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
606     {
607       String pdbfile = getPdbEntry(pdbe).getFile();
608       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
609       sb.append(getSsm().printMappings(pdbfile, seqs));
610     }
611     return sb.toString();
612   }
613
614   /**
615    * Returns the mapped structure position for a given aligned column of a given
616    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
617    * not mapped to structure.
618    * 
619    * @param seq
620    * @param alignedPos
621    * @param mapping
622    * @return
623    */
624   protected int getMappedPosition(SequenceI seq, int alignedPos,
625           StructureMapping mapping)
626   {
627     if (alignedPos >= seq.getLength())
628     {
629       return -1;
630     }
631
632     if (Comparison.isGap(seq.getCharAt(alignedPos)))
633     {
634       return -1;
635     }
636     int seqPos = seq.findPosition(alignedPos);
637     int pos = mapping.getPDBResNum(seqPos);
638     return pos;
639   }
640
641   /**
642    * Helper method to identify residues that can participate in a structure
643    * superposition command. For each structure, identify a sequence in the
644    * alignment which is mapped to the structure. Identify non-gapped columns in
645    * the sequence which have a mapping to a residue in the structure. Returns
646    * the index of the first structure that has a mapping to the alignment.
647    * 
648    * @param alignment
649    *          the sequence alignment which is the basis of structure
650    *          superposition
651    * @param matched
652    *          a BitSet, where bit j is set to indicate that every structure has
653    *          a mapped residue present in column j (so the column can
654    *          participate in structure alignment)
655    * @param structures
656    *          an array of data beans corresponding to pdb file index
657    * @return
658    */
659   protected int findSuperposableResidues(AlignmentI alignment,
660           BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
661   {
662     int refStructure = -1;
663     String[] files = getStructureFiles();
664     if (files == null)
665     {
666       return -1;
667     }
668     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
669     {
670       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
671       int lastPos = -1;
672
673       /*
674        * Find the first mapped sequence (if any) for this PDB entry which is in
675        * the alignment
676        */
677       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
678       for (int s = 0; s < seqCountForPdbFile; s++)
679       {
680         for (StructureMapping mapping : mappings)
681         {
682           final SequenceI theSequence = getSequence()[pdbfnum][s];
683           if (mapping.getSequence() == theSequence
684                   && alignment.findIndex(theSequence) > -1)
685           {
686             if (refStructure < 0)
687             {
688               refStructure = pdbfnum;
689             }
690             for (int r = 0; r < alignment.getWidth(); r++)
691             {
692               if (!matched.get(r))
693               {
694                 continue;
695               }
696               int pos = getMappedPosition(theSequence, r, mapping);
697               if (pos < 1 || pos == lastPos)
698               {
699                 matched.clear(r);
700                 continue;
701               }
702               lastPos = pos;
703               structures[pdbfnum].pdbResNo[r] = pos;
704             }
705             String chain = mapping.getChain();
706             if (chain != null && chain.trim().length() > 0)
707             {
708               structures[pdbfnum].chain = chain;
709             }
710             structures[pdbfnum].pdbId = mapping.getPdbId();
711             structures[pdbfnum].isRna = theSequence.getRNA() != null;
712
713             /*
714              * move on to next pdb file (ignore sequences for other chains
715              * for the same structure)
716              */
717             s = seqCountForPdbFile;
718             break; // fixme break out of two loops here!
719           }
720         }
721       }
722     }
723     return refStructure;
724   }
725
726   /**
727    * Returns true if the structure viewer has loaded all of the files of
728    * interest (identified by the file mapping having been set up), or false if
729    * any are still not loaded after a timeout interval.
730    * 
731    * @param files
732    */
733   protected boolean waitForFileLoad(String[] files)
734   {
735     /*
736      * give up after 10 secs plus 1 sec per file
737      */
738     long starttime = System.currentTimeMillis();
739     long endTime = 10000 + 1000 * files.length + starttime;
740     String notLoaded = null;
741
742     boolean waiting = true;
743     while (waiting && System.currentTimeMillis() < endTime)
744     {
745       waiting = false;
746       for (String file : files)
747       {
748         notLoaded = file;
749         if (file == null)
750         {
751           continue;
752         }
753         try
754         {
755           StructureMapping[] sm = getSsm().getMapping(file);
756           if (sm == null || sm.length == 0)
757           {
758             waiting = true;
759           }
760         } catch (Throwable x)
761         {
762           waiting = true;
763         }
764       }
765     }
766
767     if (waiting)
768     {
769       System.err.println(
770               "Timed out waiting for structure viewer to load file "
771                       + notLoaded);
772       return false;
773     }
774     return true;
775   }
776
777   @Override
778   public boolean isListeningFor(SequenceI seq)
779   {
780     if (sequence != null)
781     {
782       for (SequenceI[] seqs : sequence)
783       {
784         if (seqs != null)
785         {
786           for (SequenceI s : seqs)
787           {
788             if (s == seq || (s.getDatasetSequence() != null
789                     && s.getDatasetSequence() == seq.getDatasetSequence()))
790             {
791               return true;
792             }
793           }
794         }
795       }
796     }
797     return false;
798   }
799
800   public boolean isFinishedInit()
801   {
802     return finishedInit;
803   }
804
805   public void setFinishedInit(boolean fi)
806   {
807     this.finishedInit = fi;
808   }
809
810   /**
811    * Returns a list of chains mapped in this viewer, formatted as
812    * "pdbid:chainCode"
813    * 
814    * @return
815    */
816   public List<String> getChainNames()
817   {
818     return chainNames;
819   }
820
821   /**
822    * Returns the Jalview panel hosting the structure viewer (if any)
823    * 
824    * @return
825    */
826   public JalviewStructureDisplayI getViewer()
827   {
828     return viewer;
829   }
830
831   public void setViewer(JalviewStructureDisplayI v)
832   {
833     viewer = v;
834   }
835
836   /**
837    * Constructs and sends a command to align structures against a reference
838    * structure, based on one or more sequence alignments. May optionally return
839    * an error or warning message for the alignment command(s).
840    * 
841    * @param alignWith
842    *          an array of one or more alignment views to process
843    * @return
844    */
845   public String superposeStructures(List<AlignmentViewPanel> alignWith)
846   {
847     String error = "";
848     String[] files = getStructureFiles();
849
850     if (!waitForFileLoad(files))
851     {
852       return null;
853     }
854     refreshPdbEntries();
855
856     for (AlignmentViewPanel view : alignWith)
857     {
858       AlignmentI alignment = view.getAlignment();
859       HiddenColumns hiddenCols = alignment.getHiddenColumns();
860
861       /*
862        * 'matched' bit i will be set for visible alignment columns i where
863        * all sequences have a residue with a mapping to their PDB structure
864        */
865       BitSet matched = new BitSet();
866       final int width = alignment.getWidth();
867       for (int m = 0; m < width; m++)
868       {
869         if (hiddenCols == null || hiddenCols.isVisible(m))
870         {
871           matched.set(m);
872         }
873       }
874
875       AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
876       for (int f = 0; f < files.length; f++)
877       {
878         structures[f] = new AAStructureBindingModel.SuperposeData(width,
879                 getModelIdForFile(files[f]));
880       }
881
882       /*
883        * Calculate the superposable alignment columns ('matched'), and the
884        * corresponding structure residue positions (structures.pdbResNo)
885        */
886       int refStructure = findSuperposableResidues(alignment,
887               matched, structures);
888
889       /*
890        * require at least 4 positions to be able to execute superposition
891        */
892       int nmatched = matched.cardinality();
893       if (nmatched < MIN_POS_TO_SUPERPOSE)
894       {
895         String msg = MessageManager.formatMessage("label.insufficient_residues",
896                 nmatched);
897         error += view.getViewName() + ": " + msg + "; ";
898         continue;
899       }
900
901       /*
902        * get a model of the superposable residues in the reference structure 
903        */
904       AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
905               matched);
906
907       /*
908        * Show all as backbone before doing superposition(s)
909        * (residues used for matching will be shown as ribbon)
910        */
911       // todo better way to ensure synchronous than setting getReply true!!
912       executeCommands(commandGenerator.showBackbone(), true, null);
913
914       /*
915        * superpose each (other) structure to the reference in turn
916        */
917       for (int i = 0; i < structures.length; i++)
918       {
919         if (i != refStructure)
920         {
921           AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
922           List<StructureCommandI> commands = commandGenerator
923                   .superposeStructures(refAtoms, atomSpec);
924           List<String> replies = executeCommands(commands, true, null);
925           for (String reply : replies)
926           {
927             // return this error (Chimera only) to the user
928             if (reply.toLowerCase().contains("unequal numbers of atoms"))
929             {
930               error += "; " + reply;
931             }
932           }
933         }
934       }
935     }
936
937     return error;
938   }
939
940   private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
941           BitSet matched)
942   {
943     AtomSpecModel model = new AtomSpecModel();
944     int nextColumnMatch = matched.nextSetBit(0);
945     while (nextColumnMatch != -1)
946     {
947       int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
948       model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
949               superposeData.chain);
950       nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
951     }
952
953     return model;
954   }
955
956   /**
957    * returns the current sequenceRenderer that should be used to colour the
958    * structures
959    * 
960    * @param alignment
961    * 
962    * @return
963    */
964   public abstract SequenceRenderer getSequenceRenderer(
965           AlignmentViewPanel alignment);
966
967   /**
968    * Sends a command to the structure viewer to colour each chain with a
969    * distinct colour (to the extent supported by the viewer)
970    */
971   public void colourByChain()
972   {
973     colourBySequence = false;
974
975     // TODO: JAL-628 colour chains distinctly across all visible models
976
977     executeCommand(commandGenerator.colourByChain(), false,
978             COLOURING_STRUCTURES);
979   }
980
981   /**
982    * Sends a command to the structure viewer to colour each chain with a
983    * distinct colour (to the extent supported by the viewer)
984    */
985   public void colourByCharge()
986   {
987     colourBySequence = false;
988
989     executeCommands(commandGenerator.colourByCharge(), false,
990             COLOURING_STRUCTURES);
991   }
992
993   /**
994    * Sends a command to the structure to apply a colour scheme (defined in
995    * Jalview but not necessarily applied to the alignment), which defines a
996    * colour per residue letter. More complex schemes (e.g. that depend on
997    * consensus) cannot be used here and are ignored.
998    * 
999    * @param cs
1000    */
1001   public void colourByJalviewColourScheme(ColourSchemeI cs)
1002   {
1003     colourBySequence = false;
1004
1005     if (cs == null || !cs.isSimple())
1006     {
1007       return;
1008     }
1009     
1010     /*
1011      * build a map of {Residue3LetterCode, Color}
1012      */
1013     Map<String, Color> colours = new HashMap<>();
1014     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1015             false);
1016     for (String resName : residues)
1017     {
1018       char res = resName.length() == 3
1019               ? ResidueProperties.getSingleCharacterCode(resName)
1020               : resName.charAt(0);
1021       Color colour = cs.findColour(res, 0, null, null, 0f);
1022       colours.put(resName, colour);
1023     }
1024
1025     /*
1026      * pass to the command constructor, and send the command
1027      */
1028     List<StructureCommandI> cmd = commandGenerator
1029             .colourByResidues(colours);
1030     executeCommands(cmd, false, COLOURING_STRUCTURES);
1031   }
1032
1033   public void setBackgroundColour(Color col)
1034   {
1035     StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1036     executeCommand(cmd, false, null);
1037   }
1038
1039   /**
1040    * Sends one command to the structure viewer. If {@code getReply} is true, the
1041    * command is sent synchronously, otherwise in a deferred thread.
1042    * <p>
1043    * If a progress message is supplied, this is displayed before command
1044    * execution, and removed afterwards.
1045    * 
1046    * @param cmd
1047    * @param getReply
1048    * @param msg
1049    * @return
1050    */
1051   private List<String> executeCommand(StructureCommandI cmd,
1052           boolean getReply, String msg)
1053   {
1054     if (getReply)
1055     {
1056       /*
1057        * synchronous (same thread) execution so reply can be returned
1058        */
1059       final JalviewStructureDisplayI theViewer = getViewer();
1060       final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1061       try
1062       {
1063         return executeCommand(cmd, getReply);
1064       } finally
1065       {
1066         if (msg != null)
1067         {
1068           theViewer.stopProgressBar(null, handle);
1069         }
1070       }
1071     }
1072     else
1073     {
1074       /*
1075        * asynchronous (new thread) execution if no reply needed
1076        */
1077       final JalviewStructureDisplayI theViewer = getViewer();
1078       final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1079       
1080       SwingUtilities.invokeLater(new Runnable()
1081       {
1082         @Override
1083         public void run()
1084         {
1085           try
1086           {
1087             executeCommand(cmd, false);
1088           } finally
1089           {
1090             if (msg != null)
1091             {
1092               theViewer.stopProgressBar(null, handle);
1093             }
1094           }
1095         }
1096       });
1097       return null;
1098     }
1099   }
1100
1101   /**
1102    * Execute one structure viewer command. If {@code getReply} is true, may
1103    * optionally return one or more reply messages, else returns null.
1104    * 
1105    * @param cmd
1106    * @param getReply
1107    */
1108   protected abstract List<String> executeCommand(StructureCommandI cmd,
1109           boolean getReply);
1110
1111   /**
1112    * A helper method that converts list of commands to a vararg array
1113    * 
1114    * @param commands
1115    * @param getReply
1116    * @param msg
1117    */
1118   protected List<String> executeCommands(
1119           List<StructureCommandI> commands,
1120           boolean getReply, String msg)
1121   {
1122     return executeCommands(getReply, msg,
1123             commands.toArray(new StructureCommandI[commands.size()]));
1124   }
1125
1126   /**
1127    * Executes one or more structure viewer commands. If a progress message is
1128    * provided, it is shown first, and removed after all commands have been run.
1129    * 
1130    * @param getReply
1131    * @param msg
1132    * @param commands
1133    * @return
1134    */
1135   protected List<String> executeCommands(boolean getReply, String msg,
1136           StructureCommandI[] commands)
1137   {
1138     // todo: tidy this up
1139
1140     /*
1141      * show progress message if specified
1142      */
1143     final JalviewStructureDisplayI theViewer = getViewer();
1144     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1145
1146     List<String> response = getReply ? new ArrayList<>() : null;
1147     try
1148     {
1149       for (StructureCommandI cmd : commands)
1150       {
1151         List<String> replies = executeCommand(cmd, getReply, null);
1152         if (getReply && replies != null)
1153         {
1154           response.addAll(replies);
1155         }
1156       }
1157       return response;
1158     } finally
1159     {
1160       if (msg != null)
1161       {
1162         theViewer.stopProgressBar(null, handle);
1163       }
1164     }
1165   }
1166
1167   /**
1168    * Colours any structures associated with sequences in the given alignment as
1169    * coloured in the alignment view, provided colourBySequence is enabled
1170    */
1171   public void colourBySequence(AlignmentViewPanel alignmentv)
1172   {
1173     if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1174     {
1175       return;
1176     }
1177     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1178             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     if (ap == null)
1249     {
1250       return null;
1251     }
1252     return ap.getAlignViewport().isShowSequenceFeatures()
1253             ? ap.getFeatureRenderer()
1254             : null;
1255   }
1256
1257   protected void setStructureCommands(StructureCommandsI cmd)
1258   {
1259     commandGenerator = cmd;
1260   }
1261
1262   /**
1263    * Records association of one chain id (formatted as "pdbid:chainCode") with
1264    * the corresponding PDB file name
1265    * 
1266    * @param chainId
1267    * @param fileName
1268    */
1269   public void addChainFile(String chainId, String fileName)
1270   {
1271     chainFile.put(chainId, fileName);
1272   }
1273
1274   /**
1275    * Returns the PDB filename for the given chain id (formatted as
1276    * "pdbid:chainCode"), or null if not found
1277    * 
1278    * @param chainId
1279    * @return
1280    */
1281   protected String getFileForChain(String chainId)
1282   {
1283     return chainFile.get(chainId);
1284   }
1285
1286   @Override
1287   public void updateColours(Object source)
1288   {
1289     AlignmentViewPanel ap = (AlignmentViewPanel) source;
1290     // ignore events from panels not used to colour this view
1291     if (!getViewer().isUsedForColourBy(ap))
1292     {
1293       return;
1294     }
1295     if (!isLoadingFromArchive())
1296     {
1297       colourBySequence(ap);
1298     }
1299   }
1300
1301   public StructureCommandsI getCommandGenerator()
1302   {
1303     return commandGenerator;
1304   }
1305
1306   protected abstract ViewerType getViewerType();
1307
1308   /**
1309    * Send a structure viewer command asynchronously in a new thread. If the
1310    * progress message is not null, display this message while the command is
1311    * executing.
1312    * 
1313    * @param command
1314    * @param progressMsg
1315    */
1316   protected void sendAsynchronousCommand(StructureCommandI command,
1317           String progressMsg)
1318   {
1319     final JalviewStructureDisplayI theViewer = getViewer();
1320     final long handle = progressMsg == null ? 0
1321             : theViewer.startProgressBar(progressMsg);
1322     SwingUtilities.invokeLater(new Runnable()
1323     {
1324       @Override
1325       public void run()
1326       {
1327         try
1328         {
1329           executeCommand(command, false, null);
1330         } finally
1331         {
1332           if (progressMsg != null)
1333           {
1334             theViewer.stopProgressBar(null, handle);
1335           }
1336         }
1337       }
1338     });
1339
1340   }
1341
1342   /**
1343    * Builds a data structure which records mapped structure residues for each
1344    * colour. From this we can easily generate the viewer commands for colour by
1345    * sequence. Constructs and returns a map of {@code Color} to
1346    * {@code AtomSpecModel}, where the atomspec model holds
1347    * 
1348    * <pre>
1349    *   Model ids
1350    *     Chains
1351    *       Residue positions
1352    * </pre>
1353    * 
1354    * Ordering is by order of addition (for colours), natural ordering (for
1355    * models and chains)
1356    * 
1357    * @param ssm
1358    * @param sequence
1359    * @param viewPanel
1360    * @return
1361    */
1362   protected Map<Object, AtomSpecModel> buildColoursMap(
1363           StructureSelectionManager ssm, SequenceI[][] sequence,
1364           AlignmentViewPanel viewPanel)
1365   {
1366     String[] files = getStructureFiles();
1367     SequenceRenderer sr = getSequenceRenderer(viewPanel);
1368     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1369     FeatureColourFinder finder = new FeatureColourFinder(fr);
1370     AlignViewportI viewport = viewPanel.getAlignViewport();
1371     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1372     AlignmentI al = viewport.getAlignment();
1373     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1374     Color lastColour = null;
1375   
1376     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1377     {
1378       final String modelId = getModelIdForFile(files[pdbfnum]);
1379       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1380   
1381       if (mapping == null || mapping.length < 1)
1382       {
1383         continue;
1384       }
1385   
1386       int startPos = -1, lastPos = -1;
1387       String lastChain = "";
1388       for (int s = 0; s < sequence[pdbfnum].length; s++)
1389       {
1390         for (int sp, m = 0; m < mapping.length; m++)
1391         {
1392           final SequenceI seq = sequence[pdbfnum][s];
1393           if (mapping[m].getSequence() == seq
1394                   && (sp = al.findIndex(seq)) > -1)
1395           {
1396             SequenceI asp = al.getSequenceAt(sp);
1397             for (int r = 0; r < asp.getLength(); r++)
1398             {
1399               // no mapping to gaps in sequence
1400               if (Comparison.isGap(asp.getCharAt(r)))
1401               {
1402                 continue;
1403               }
1404               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1405   
1406               if (pos < 1 || pos == lastPos)
1407               {
1408                 continue;
1409               }
1410   
1411               Color colour = sr.getResidueColour(seq, r, finder);
1412   
1413               /*
1414                * darker colour for hidden regions
1415                */
1416               if (!cs.isVisible(r))
1417               {
1418                 colour = Color.GRAY;
1419               }
1420   
1421               final String chain = mapping[m].getChain();
1422   
1423               /*
1424                * Just keep incrementing the end position for this colour range
1425                * _unless_ colour, PDB model or chain has changed, or there is a
1426                * gap in the mapped residue sequence
1427                */
1428               final boolean newColour = !colour.equals(lastColour);
1429               final boolean nonContig = lastPos + 1 != pos;
1430               final boolean newChain = !chain.equals(lastChain);
1431               if (newColour || nonContig || newChain)
1432               {
1433                 if (startPos != -1)
1434                 {
1435                   addAtomSpecRange(colourMap, lastColour, modelId,
1436                           startPos, lastPos, lastChain);
1437                 }
1438                 startPos = pos;
1439               }
1440               lastColour = colour;
1441               lastPos = pos;
1442               lastChain = chain;
1443             }
1444             // final colour range
1445             if (lastColour != null)
1446             {
1447               addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1448                       lastPos, lastChain);
1449             }
1450             // break;
1451           }
1452         }
1453       }
1454     }
1455     return colourMap;
1456   }
1457
1458   /**
1459    * todo better refactoring (map lookup or similar to get viewer structure id)
1460    * 
1461    * @param pdbfnum
1462    * @param file
1463    * @return
1464    */
1465   protected String getModelId(int pdbfnum, String file)
1466   {
1467     return String.valueOf(pdbfnum);
1468   }
1469
1470   /**
1471    * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1472    * full PDB file path
1473    * 
1474    * @param pdb
1475    * @param file
1476    */
1477   public void stashFoundChains(StructureFile pdb, String file)
1478   {
1479     for (int i = 0; i < pdb.getChains().size(); i++)
1480     {
1481       String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1482       addChainFile(chid, file);
1483       getChainNames().add(chid);
1484     }
1485   }
1486
1487   /**
1488    * Helper method to add one contiguous range to the AtomSpec model for the given
1489    * value (creating the model if necessary). As used by Jalview, {@code value} is
1490    * <ul>
1491    * <li>a colour, when building a 'colour structure by sequence' command</li>
1492    * <li>a feature value, when building a 'set Chimera attributes from features'
1493    * command</li>
1494    * </ul>
1495    * 
1496    * @param map
1497    * @param value
1498    * @param model
1499    * @param startPos
1500    * @param endPos
1501    * @param chain
1502    */
1503   public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1504           Object value,
1505           String model, int startPos, int endPos, String chain)
1506   {
1507     /*
1508      * Get/initialize map of data for the colour
1509      */
1510     AtomSpecModel atomSpec = map.get(value);
1511     if (atomSpec == null)
1512     {
1513       atomSpec = new AtomSpecModel();
1514       map.put(value, atomSpec);
1515     }
1516   
1517     atomSpec.addRange(model, startPos, endPos, chain);
1518   }
1519
1520   /**
1521    * Returns the file extension (including '.' separator) to use for a saved
1522    * viewer session file. Default is to return null (not supported), override as
1523    * required.
1524    * 
1525    * @return
1526    */
1527   public String getSessionFileExtension()
1528   {
1529     return null;
1530   }
1531
1532   /**
1533    * If supported, saves the state of the structure viewer to a temporary file
1534    * and returns the file. Returns null and logs an error on any failure.
1535    * 
1536    * @return
1537    */
1538   public File saveSession()
1539   {
1540     String prefix = getViewerType().toString();
1541     String suffix = getSessionFileExtension();
1542     File f = null;
1543     try
1544     {
1545       f = File.createTempFile(prefix, suffix);
1546       saveSession(f);
1547     } catch (IOException e)
1548     {
1549       Cache.log.error(String.format("Error saving %s session: %s",
1550               prefix, e.toString()));
1551     }
1552
1553     return f;
1554   }
1555
1556   /**
1557    * Saves the structure viewer session to the given file
1558    * 
1559    * @param f
1560    */
1561   protected void saveSession(File f)
1562   {
1563     StructureCommandI cmd = commandGenerator
1564             .saveSession(f.getPath());
1565     if (cmd != null)
1566     {
1567       executeCommand(cmd, false);
1568     }
1569   }
1570
1571   /**
1572    * Returns true if the viewer is an external structure viewer for which the
1573    * process is still alive, else false (for Jmol, or an external viewer which
1574    * the user has independently closed)
1575    * 
1576    * @return
1577    */
1578   public boolean isViewerRunning()
1579   {
1580     return false;
1581   }
1582
1583   /**
1584    * Closes Jalview's structure viewer panel and releases associated resources.
1585    * If it is managing an external viewer program, and {@code forceClose} is
1586    * true, also shuts down that program.
1587    * 
1588    * @param forceClose
1589    */
1590   public void closeViewer(boolean forceClose)
1591   {
1592     getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1593     releaseUIResources();
1594
1595     // add external viewer shutdown in overrides
1596     // todo - or can maybe pull up to here
1597   }
1598
1599   /**
1600    * Returns the URL of a help page for the structure viewer, or null if none is
1601    * known
1602    * 
1603    * @return
1604    */
1605   public String getHelpURL()
1606   {
1607     return null;
1608   }
1609
1610   /**
1611    * <pre>
1612    * Helper method to build a map of 
1613    *   { featureType, { feature value, AtomSpecModel } }
1614    * </pre>
1615    * 
1616    * @param viewPanel
1617    * @return
1618    */
1619   protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1620           AlignmentViewPanel viewPanel)
1621   {
1622     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1623     String[] files = getStructureFiles();
1624     if (files == null)
1625     {
1626       return theMap;
1627     }
1628
1629     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1630     if (fr == null)
1631     {
1632       return theMap;
1633     }
1634   
1635     AlignViewportI viewport = viewPanel.getAlignViewport();
1636     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1637   
1638     /*
1639      * if alignment is showing features from complement, we also transfer
1640      * these features to the corresponding mapped structure residues
1641      */
1642     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1643     List<String> complementFeatures = new ArrayList<>();
1644     FeatureRenderer complementRenderer = null;
1645     if (showLinkedFeatures)
1646     {
1647       AlignViewportI comp = fr.getViewport().getCodingComplement();
1648       if (comp != null)
1649       {
1650         complementRenderer = Desktop.getAlignFrameFor(comp)
1651                 .getFeatureRenderer();
1652         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1653       }
1654     }
1655     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1656     {
1657       return theMap;
1658     }
1659   
1660     AlignmentI alignment = viewPanel.getAlignment();
1661     SequenceI[][] seqs = getSequence();
1662
1663     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1664     {
1665       String modelId = getModelIdForFile(files[pdbfnum]);
1666       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1667   
1668       if (mapping == null || mapping.length < 1)
1669       {
1670         continue;
1671       }
1672   
1673       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1674       {
1675         for (int m = 0; m < mapping.length; m++)
1676         {
1677           final SequenceI seq = seqs[pdbfnum][seqNo];
1678           int sp = alignment.findIndex(seq);
1679           StructureMapping structureMapping = mapping[m];
1680           if (structureMapping.getSequence() == seq && sp > -1)
1681           {
1682             /*
1683              * found a sequence with a mapping to a structure;
1684              * now scan its features
1685              */
1686             if (!visibleFeatures.isEmpty())
1687             {
1688               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1689                       theMap, modelId);
1690             }
1691             if (showLinkedFeatures)
1692             {
1693               scanComplementFeatures(complementRenderer, structureMapping,
1694                       seq, theMap, modelId);
1695             }
1696           }
1697         }
1698       }
1699     }
1700     return theMap;
1701   }
1702
1703   /**
1704    * Ask the structure viewer to open a session file. Returns true if
1705    * successful, else false (or not supported).
1706    * 
1707    * @param filepath
1708    * @return
1709    */
1710   public boolean openSession(String filepath)
1711   {
1712     StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1713     if (cmd == null)
1714     {
1715       return false;
1716     }
1717     executeCommand(cmd, true);
1718     // todo: test for failure - how?
1719     return true;
1720   }
1721
1722   /**
1723    * Scans visible features in mapped positions of the CDS/peptide complement, and
1724    * adds any found to the map of attribute values/structure positions
1725    * 
1726    * @param complementRenderer
1727    * @param structureMapping
1728    * @param seq
1729    * @param theMap
1730    * @param modelNumber
1731    */
1732   protected static void scanComplementFeatures(
1733           FeatureRenderer complementRenderer,
1734           StructureMapping structureMapping, SequenceI seq,
1735           Map<String, Map<Object, AtomSpecModel>> theMap,
1736           String modelNumber)
1737   {
1738     /*
1739      * for each sequence residue mapped to a structure position...
1740      */
1741     for (int seqPos : structureMapping.getMapping().keySet())
1742     {
1743       /*
1744        * find visible complementary features at mapped position(s)
1745        */
1746       MappedFeatures mf = complementRenderer
1747               .findComplementFeaturesAtResidue(seq, seqPos);
1748       if (mf != null)
1749       {
1750         for (SequenceFeature sf : mf.features)
1751         {
1752           String type = sf.getType();
1753   
1754           /*
1755            * Don't copy features which originated from Chimera
1756            */
1757           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1758                   .equals(sf.getFeatureGroup()))
1759           {
1760             continue;
1761           }
1762   
1763           /*
1764            * record feature 'value' (score/description/type) as at the
1765            * corresponding structure position
1766            */
1767           List<int[]> mappedRanges = structureMapping
1768                   .getPDBResNumRanges(seqPos, seqPos);
1769   
1770           if (!mappedRanges.isEmpty())
1771           {
1772             String value = sf.getDescription();
1773             if (value == null || value.length() == 0)
1774             {
1775               value = type;
1776             }
1777             float score = sf.getScore();
1778             if (score != 0f && !Float.isNaN(score))
1779             {
1780               value = Float.toString(score);
1781             }
1782             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1783             if (featureValues == null)
1784             {
1785               featureValues = new HashMap<>();
1786               theMap.put(type, featureValues);
1787             }
1788             for (int[] range : mappedRanges)
1789             {
1790               addAtomSpecRange(featureValues, value, modelNumber, range[0],
1791                       range[1], structureMapping.getChain());
1792             }
1793           }
1794         }
1795       }
1796     }
1797   }
1798
1799   /**
1800    * Inspect features on the sequence; for each feature that is visible,
1801    * determine its mapped ranges in the structure (if any) according to the
1802    * given mapping, and add them to the map.
1803    * 
1804    * @param visibleFeatures
1805    * @param mapping
1806    * @param seq
1807    * @param theMap
1808    * @param modelId
1809    */
1810   protected static void scanSequenceFeatures(List<String> visibleFeatures,
1811           StructureMapping mapping, SequenceI seq,
1812           Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1813   {
1814     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1815             visibleFeatures.toArray(new String[visibleFeatures.size()]));
1816     for (SequenceFeature sf : sfs)
1817     {
1818       String type = sf.getType();
1819   
1820       /*
1821        * Don't copy features which originated from Chimera
1822        */
1823       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1824               .equals(sf.getFeatureGroup()))
1825       {
1826         continue;
1827       }
1828   
1829       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1830               sf.getEnd());
1831   
1832       if (!mappedRanges.isEmpty())
1833       {
1834         String value = sf.getDescription();
1835         if (value == null || value.length() == 0)
1836         {
1837           value = type;
1838         }
1839         float score = sf.getScore();
1840         if (score != 0f && !Float.isNaN(score))
1841         {
1842           value = Float.toString(score);
1843         }
1844         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1845         if (featureValues == null)
1846         {
1847           featureValues = new HashMap<>();
1848           theMap.put(type, featureValues);
1849         }
1850         for (int[] range : mappedRanges)
1851         {
1852           addAtomSpecRange(featureValues, value, modelId, range[0],
1853                   range[1], mapping.getChain());
1854         }
1855       }
1856     }
1857   }
1858 }