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