JAL-3518 separation of ChimeraXManager, pull up of closeViewer etc
[jalview.git] / src / jalview / ext / rbvi / chimera / JalviewChimeraBinding.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.ext.rbvi.chimera;
22
23 import java.io.File;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.PrintWriter;
27 import java.net.BindException;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Iterator;
31 import java.util.LinkedHashMap;
32 import java.util.List;
33 import java.util.Map;
34
35 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
36 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
37 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
38 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.bin.Cache;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SearchResultMatchI;
44 import jalview.datamodel.SearchResultsI;
45 import jalview.datamodel.SequenceFeature;
46 import jalview.datamodel.SequenceI;
47 import jalview.gui.StructureViewer.ViewerType;
48 import jalview.httpserver.AbstractRequestHandler;
49 import jalview.io.DataSourceType;
50 import jalview.structure.AtomSpec;
51 import jalview.structure.AtomSpecModel;
52 import jalview.structure.StructureCommand;
53 import jalview.structure.StructureCommandI;
54 import jalview.structure.StructureSelectionManager;
55 import jalview.structures.models.AAStructureBindingModel;
56
57 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
58 {
59   public static final String CHIMERA_SESSION_EXTENSION = ".py";
60
61   public static final String CHIMERA_FEATURE_GROUP = "Chimera";
62
63   /*
64    * Object through which we talk to Chimera
65    */
66   private ChimeraManager chimeraManager;
67
68   /*
69    * Object which listens to Chimera notifications
70    */
71   private AbstractRequestHandler chimeraListener;
72
73   /*
74    * Map of ChimeraModel objects keyed by PDB full local file name
75    */
76   protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
77
78   String lastHighlightCommand;
79
80   /**
81    * Returns a model of the structure positions described by the Chimera format atomspec
82    * @param atomSpec
83    * @return
84    */
85   protected  AtomSpec parseAtomSpec(String atomSpec)
86   {
87     return AtomSpec.fromChimeraAtomspec(atomSpec);
88   }
89
90   /**
91    * Open a PDB structure file in Chimera and set up mappings from Jalview.
92    * 
93    * We check if the PDB model id is already loaded in Chimera, if so don't reopen
94    * it. This is the case if Chimera has opened a saved session file.
95    * 
96    * @param pe
97    * @return
98    */
99   public boolean openFile(PDBEntry pe)
100   {
101     String file = pe.getFile();
102     try
103     {
104       List<ChimeraModel> modelsToMap = new ArrayList<>();
105       List<ChimeraModel> oldList = chimeraManager.getModelList();
106       boolean alreadyOpen = false;
107
108       /*
109        * If Chimera already has this model, don't reopen it, but do remap it.
110        */
111       for (ChimeraModel open : oldList)
112       {
113         if (open.getModelName().equals(pe.getId()))
114         {
115           alreadyOpen = true;
116           modelsToMap.add(open);
117         }
118       }
119
120       /*
121        * If Chimera doesn't yet have this model, ask it to open it, and retrieve
122        * the model name(s) added by Chimera.
123        */
124       if (!alreadyOpen)
125       {
126         chimeraManager.openModel(file, pe.getId(), ModelType.PDB_MODEL);
127         addChimeraModel(pe, modelsToMap);
128       }
129
130       chimeraMaps.put(file, modelsToMap);
131
132       if (getSsm() != null)
133       {
134         getSsm().addStructureViewerListener(this);
135       }
136       return true;
137     } catch (Exception q)
138     {
139       log("Exception when trying to open model " + file + "\n"
140               + q.toString());
141       q.printStackTrace();
142     }
143     return false;
144   }
145
146   /**
147    * Adds the ChimeraModel corresponding to the given PDBEntry, based on model
148    * name matching PDB id
149    * 
150    * @param pe
151    * @param modelsToMap
152    */
153   protected void addChimeraModel(PDBEntry pe,
154           List<ChimeraModel> modelsToMap)
155   {
156     /*
157      * Chimera: query for actual models and find the one with
158      * matching model name - already set in viewer.openModel()
159      */
160     List<ChimeraModel> newList = chimeraManager.getModelList();
161     // JAL-1728 newList.removeAll(oldList) does not work
162     for (ChimeraModel cm : newList)
163     {
164       if (cm.getModelName().equals(pe.getId()))
165       {
166         modelsToMap.add(cm);
167       }
168     }
169   }
170
171   /**
172    * Constructor
173    * 
174    * @param ssm
175    * @param pdbentry
176    * @param sequenceIs
177    * @param protocol
178    */
179   public JalviewChimeraBinding(StructureSelectionManager ssm,
180           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
181           DataSourceType protocol)
182   {
183     super(ssm, pdbentry, sequenceIs, protocol);
184     boolean chimeraX = ViewerType.CHIMERAX.equals(getViewerType());
185     chimeraManager = chimeraX ? new ChimeraXManager(new StructureManager(true)) : new ChimeraManager(new StructureManager(true));
186     setStructureCommands(chimeraX ? new ChimeraXCommands() : new ChimeraCommands());
187   }
188
189   @Override
190   protected ViewerType getViewerType()
191   {
192     return ViewerType.CHIMERA;
193   }
194
195   /**
196    * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
197    * to start listening
198    */
199   public void startChimeraListener()
200   {
201     try
202     {
203       chimeraListener = new ChimeraListener(this);
204       startListening(chimeraListener.getUri());
205     } catch (BindException e)
206     {
207       System.err.println(
208               "Failed to start Chimera listener: " + e.getMessage());
209     }
210   }
211
212   /**
213    * Close down the Jalview viewer and listener, and (optionally) the associated
214    * Chimera window.
215    */
216   @Override
217   public void closeViewer(boolean closeChimera)
218   {
219     super.closeViewer(closeChimera);
220     if (this.chimeraListener != null)
221     {
222       chimeraListener.shutdown();
223       chimeraListener = null;
224     }
225     
226     /*
227      * the following call should not be needed but is temporarily included,
228      * to avoid a stack trace error in Chimera after "stop really" is sent
229      */
230     if (closeChimera)
231     {
232       chimeraManager.getChimeraProcess().destroy();
233     }
234
235     chimeraManager.clearOnChimeraExit();
236     chimeraManager = null;
237   }
238
239   /**
240    * Helper method to construct model spec in Chimera format:
241    * <ul>
242    * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
243    * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
244    * <ul>
245    * Note for now we only ever choose the first of multiple models. This
246    * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
247    * future if there is a need to select specific sub-models.
248    * 
249    * @param pdbfnum
250    * @return
251    */
252   protected String getModelSpec(int pdbfnum)
253   {
254     if (pdbfnum < 0 || pdbfnum >= getPdbCount())
255     {
256       return "#" + pdbfnum; // temp hack for ChimeraX
257     }
258
259     /*
260      * For now, the test for having sub-models is whether multiple Chimera
261      * models are mapped for the PDB file; the models are returned as a response
262      * to the Chimera command 'list models type molecule', see
263      * ChimeraManager.getModelList().
264      */
265     List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
266     boolean hasSubModels = maps != null && maps.size() > 1;
267     return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
268   }
269
270   /**
271    * Launch Chimera, unless an instance linked to this object is already
272    * running. Returns true if Chimera is successfully launched, or already
273    * running, else false.
274    * 
275    * @return
276    */
277   public boolean launchChimera()
278   {
279     if (chimeraManager.isChimeraLaunched())
280     {
281       return true;
282     }
283
284     boolean launched = chimeraManager.launchChimera(getChimeraPaths());
285     if (launched)
286     {
287       startExternalViewerMonitor(chimeraManager.getChimeraProcess());
288     }
289     else
290     {
291       log("Failed to launch Chimera!");
292     }
293     return launched;
294   }
295
296   /**
297    * Returns a list of candidate paths to the Chimera program executable
298    * 
299    * @return
300    */
301   protected List<String> getChimeraPaths()
302   {
303     return StructureManager.getChimeraPaths(false);
304   }
305
306   /**
307    * Answers true if the Chimera process is still running, false if ended or not
308    * started.
309    * 
310    * @return
311    */
312   @Override
313   public boolean isViewerRunning()
314   {
315     return chimeraManager.isChimeraLaunched();
316   }
317
318   /**
319    * Send a command to Chimera, and optionally log and return any responses.
320    * 
321    * @param command
322    * @param getResponse
323    */
324   @Override
325   public List<String> executeCommand(final StructureCommandI command,
326           boolean getResponse)
327   {
328     if (chimeraManager == null || command == null)
329     {
330       // ? thread running after viewer shut down
331       return null;
332     }
333     List<String> reply = null;
334     // trim command or it may never find a match in the replyLog!!
335     String cmd = command.getCommand().trim();
336     List<String> lastReply = chimeraManager
337             .sendChimeraCommand(cmd, getResponse);
338     if (getResponse)
339     {
340       reply = lastReply;
341       Cache.log.debug(
342               "Response from command ('" + cmd + "') was:\n" + lastReply);
343     }
344
345     return reply;
346   }
347
348   @Override
349   public synchronized String[] getStructureFiles()
350   {
351     if (chimeraManager == null)
352     {
353       return new String[0];
354     }
355
356     return chimeraMaps.keySet()
357             .toArray(modelFileNames = new String[chimeraMaps.size()]);
358   }
359
360   /**
361    * Construct and send a command to highlight zero, one or more atoms. We do this
362    * by sending an "rlabel" command to show the residue label at that position.
363    */
364   @Override
365   public void highlightAtoms(List<AtomSpec> atoms)
366   {
367     if (atoms == null || atoms.size() == 0)
368     {
369       return;
370     }
371
372     boolean forChimeraX = chimeraManager.isChimeraX();
373     StringBuilder cmd = new StringBuilder(128);
374     boolean first = true;
375     boolean found = false;
376
377     for (AtomSpec atom : atoms)
378     {
379       int pdbResNum = atom.getPdbResNum();
380       String chain = atom.getChain();
381       String pdbfile = atom.getPdbFile();
382       List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
383       if (cms != null && !cms.isEmpty())
384       {
385         if (first)
386         {
387           cmd.append(forChimeraX ? "label #" : "rlabel #");
388         }
389         else
390         {
391           cmd.append(",");
392         }
393         first = false;
394         if (forChimeraX)
395         {
396           cmd.append(cms.get(0).getModelNumber())
397                   .append("/").append(chain).append(":").append(pdbResNum);
398         }
399         else
400         {
401           cmd.append(cms.get(0).getModelNumber())
402                   .append(":").append(pdbResNum);
403           if (!chain.equals(" ") && !forChimeraX)
404           {
405             cmd.append(".").append(chain);
406           }
407         }
408         found = true;
409       }
410     }
411     String command = cmd.toString();
412
413     /*
414      * avoid repeated commands for the same residue
415      */
416     if (command.equals(lastHighlightCommand))
417     {
418       return;
419     }
420
421     /*
422      * unshow the label for the previous residue
423      */
424     if (lastHighlightCommand != null)
425     {
426       chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
427     }
428     if (found)
429     {
430       chimeraManager.sendChimeraCommand(command, false);
431     }
432     this.lastHighlightCommand = command;
433   }
434
435   /**
436    * Query Chimera for its current selection, and highlight it on the alignment
437    */
438   public void highlightChimeraSelection()
439   {
440     /*
441      * Ask Chimera for its current selection
442      */
443     StructureCommandI command = getCommandGenerator().getSelectedResidues();
444     List<String> chimeraReply = executeCommand(command, true);
445     List<String> selectedResidues = new ArrayList<>();
446     if (chimeraReply != null)
447     {
448       /*
449        * expect 0, 1 or more lines of the format either
450        * Chimera:
451        * residue id #0:43.A type GLY
452        * ChimeraX:
453        * residue id /A:89 name THR index 88
454        * We are only interested in the atomspec (third token of the reply)
455        */
456       for (String inputLine : chimeraReply)
457       {
458         String[] inputLineParts = inputLine.split("\\s+");
459         if (inputLineParts.length >= 5)
460         {
461           selectedResidues.add(inputLineParts[2]);
462         }
463       }
464     }
465
466     /*
467      * Parse model number, residue and chain for each selected position,
468      * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
469      */
470     List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
471             selectedResidues);
472
473     /*
474      * Broadcast the selection (which may be empty, if the user just cleared all
475      * selections)
476      */
477     getSsm().mouseOverStructure(atomSpecs);
478   }
479
480   /**
481    * Converts a list of Chimera(X) atomspecs to a list of AtomSpec representing the
482    * corresponding residues (if any) in Jalview
483    * 
484    * @param structureSelection
485    * @return
486    */
487   protected List<AtomSpec> convertStructureResiduesToAlignment(
488           List<String> structureSelection)
489   {
490     List<AtomSpec> atomSpecs = new ArrayList<>();
491     for (String atomSpec : structureSelection)
492     {
493       try
494       {
495         AtomSpec spec = parseAtomSpec(atomSpec);
496         String pdbfilename = getPdbFileForModel(spec.getModelNumber());
497         spec.setPdbFile(pdbfilename);
498         atomSpecs.add(spec);
499       } catch (IllegalArgumentException e)
500       {
501         Cache.log.error("Failed to parse atomspec: " + atomSpec);
502       }
503     }
504     return atomSpecs;
505   }
506
507   /**
508    * @param modelId
509    * @return
510    */
511   protected String getPdbFileForModel(int modelId)
512   {
513     /*
514      * Work out the pdbfilename from the model number
515      */
516     String pdbfilename = modelFileNames[0];
517     findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
518     {
519       for (ChimeraModel cm : chimeraMaps.get(pdbfile))
520       {
521         if (cm.getModelNumber() == modelId)
522         {
523           pdbfilename = pdbfile;
524           break findfileloop;
525         }
526       }
527     }
528     return pdbfilename;
529   }
530
531   private void log(String message)
532   {
533     System.err.println("## Chimera log: " + message);
534   }
535
536   /**
537    * Send a 'show' command for all atoms in the currently selected columns
538    * 
539    * TODO: pull up to abstract structure viewer interface
540    * 
541    * @param vp
542    */
543   public void highlightSelection(AlignmentViewPanel vp)
544   {
545     List<Integer> cols = vp.getAlignViewport().getColumnSelection()
546             .getSelected();
547     AlignmentI alignment = vp.getAlignment();
548     StructureSelectionManager sm = getSsm();
549     for (SequenceI seq : alignment.getSequences())
550     {
551       /*
552        * convert selected columns into sequence positions
553        */
554       int[] positions = new int[cols.size()];
555       int i = 0;
556       for (Integer col : cols)
557       {
558         positions[i++] = seq.findPosition(col);
559       }
560       sm.highlightStructure(this, seq, positions);
561     }
562   }
563
564   /**
565    * Constructs and send commands to Chimera to set attributes on residues for
566    * features visible in Jalview.
567    * <p>
568    * The syntax is: setattr r &lt;attName&gt; &lt;attValue&gt; &lt;atomSpec&gt;
569    * <p>
570    * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
571    * 
572    * @param avp
573    * @return
574    */
575   public int sendFeaturesToViewer(AlignmentViewPanel avp)
576   {
577     // TODO refactor as required to pull up to an interface
578
579     Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
580             avp);
581     List<StructureCommandI> commands = getCommandGenerator()
582             .setAttributes(featureValues);
583     if (commands.size() > 10)
584     {
585       sendCommandsByFile(commands);
586     }
587     else
588     {
589       for (StructureCommandI command : commands)
590       {
591         sendAsynchronousCommand(command, null);
592       }
593     }
594     return commands.size();
595   }
596
597   /**
598    * Write commands to a temporary file, and send a command to Chimera to open the
599    * file as a commands script. For use when sending a large number of separate
600    * commands would overload the REST interface mechanism.
601    * 
602    * @param commands
603    */
604   protected void sendCommandsByFile(List<StructureCommandI> commands)
605   {
606     try
607     {
608       File tmp = File.createTempFile("chim", getCommandFileExtension());
609       tmp.deleteOnExit();
610       PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
611       for (StructureCommandI command : commands)
612       {
613         out.println(command.getCommand());
614       }
615       out.flush();
616       out.close();
617       String path = tmp.getAbsolutePath();
618       StructureCommandI command = getCommandGenerator()
619               .openCommandFile(path);
620       sendAsynchronousCommand(command, null);
621     } catch (IOException e)
622     {
623       System.err.println("Sending commands to Chimera via file failed with "
624               + e.getMessage());
625     }
626   }
627
628   /**
629    * Returns the file extension required for a file of commands to be read by
630    * the structure viewer
631    * @return
632    */
633   protected String getCommandFileExtension()
634   {
635     return ".com";
636   }
637
638   /**
639    * Get Chimera residues which have the named attribute, find the mapped
640    * positions in the Jalview sequence(s), and set as sequence features
641    * 
642    * @param attName
643    * @param alignmentPanel
644    */
645   public void copyStructureAttributesToFeatures(String attName,
646           AlignmentViewPanel alignmentPanel)
647   {
648     // todo pull up to AAStructureBindingModel (and interface?)
649
650     /*
651      * ask Chimera to list residues with the attribute, reporting its value
652      */
653     // this alternative command
654     // list residues spec ':*/attName' attr attName
655     // doesn't report 'None' values (which is good), but
656     // fails for 'average.bfactor' (which is bad):
657
658     String cmd = "list residues attr '" + attName + "'";
659     List<String> residues = executeCommand(new StructureCommand(cmd), true);
660
661     boolean featureAdded = createFeaturesForAttributes(attName, residues);
662     if (featureAdded)
663     {
664       alignmentPanel.getFeatureRenderer().featuresAdded();
665     }
666   }
667
668   /**
669    * Create features in Jalview for the given attribute name and structure
670    * residues.
671    * 
672    * <pre>
673    * The residue list should be 0, 1 or more reply lines of the format: 
674    *     residue id #0:5.A isHelix -155.000836316 index 5 
675    * or 
676    *     residue id #0:6.A isHelix None
677    * </pre>
678    * 
679    * @param attName
680    * @param residues
681    * @return
682    */
683   protected boolean createFeaturesForAttributes(String attName,
684           List<String> residues)
685   {
686     boolean featureAdded = false;
687     String featureGroup = getViewerFeatureGroup();
688
689     for (String residue : residues)
690     {
691       AtomSpec spec = null;
692       String[] tokens = residue.split(" ");
693       if (tokens.length < 5)
694       {
695         continue;
696       }
697       String atomSpec = tokens[2];
698       String attValue = tokens[4];
699
700       /*
701        * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
702        */
703       if ("None".equalsIgnoreCase(attValue)
704               || "False".equalsIgnoreCase(attValue))
705       {
706         continue;
707       }
708
709       try
710       {
711         spec = parseAtomSpec(atomSpec);
712       } catch (IllegalArgumentException e)
713       {
714         System.err.println("Problem parsing atomspec " + atomSpec);
715         continue;
716       }
717
718       String chainId = spec.getChain();
719       String description = attValue;
720       float score = Float.NaN;
721       try
722       {
723         score = Float.valueOf(attValue);
724         description = chainId;
725       } catch (NumberFormatException e)
726       {
727         // was not a float value
728       }
729
730       String pdbFile = getPdbFileForModel(spec.getModelNumber());
731       spec.setPdbFile(pdbFile);
732
733       List<AtomSpec> atoms = Collections.singletonList(spec);
734
735       /*
736        * locate the mapped position in the alignment (if any)
737        */
738       SearchResultsI sr = getSsm()
739               .findAlignmentPositionsForStructurePositions(atoms);
740
741       /*
742        * expect one matched alignment position, or none 
743        * (if the structure position is not mapped)
744        */
745       for (SearchResultMatchI m : sr.getResults())
746       {
747         SequenceI seq = m.getSequence();
748         int start = m.getStart();
749         int end = m.getEnd();
750         SequenceFeature sf = new SequenceFeature(attName, description,
751                 start, end, score, featureGroup);
752         // todo: should SequenceFeature have an explicit property for chain?
753         // note: repeating the action shouldn't duplicate features
754         featureAdded |= seq.addSequenceFeature(sf);
755       }
756     }
757     return featureAdded;
758   }
759
760   /**
761    * Answers the feature group name to apply to features created in Jalview from
762    * Chimera attributes
763    * 
764    * @return
765    */
766   protected String getViewerFeatureGroup()
767   {
768     // todo pull up to interface
769     return CHIMERA_FEATURE_GROUP;
770   }
771
772   @Override
773   public String getModelIdForFile(String pdbFile)
774   {
775     List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
776     if (foundModels != null && !foundModels.isEmpty())
777     {
778       return String.valueOf(foundModels.get(0).getModelNumber());
779     }
780     return "";
781   }
782
783   /**
784    * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
785    * any which were added from Jalview
786    * 
787    * @return
788    */
789   public List<String> getChimeraAttributes()
790   {
791     List<String> atts = chimeraManager.getAttrList();
792     Iterator<String> it = atts.iterator();
793     while (it.hasNext())
794     {
795       if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
796       {
797         /*
798          * attribute added from Jalview - exclude it
799          */
800         it.remove();
801       }
802     }
803     return atts;
804   }
805
806   /**
807    * Returns the file extension to use for a saved viewer session file (.py)
808    * 
809    * @return
810    */
811   @Override
812   public String getSessionFileExtension()
813   {
814     return CHIMERA_SESSION_EXTENSION;
815   }
816
817   @Override
818   public String getHelpURL()
819   {
820     return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";
821   }
822 }