c8875b48aab80aba906d3fee3e3a819f6702b718
[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 is added to avoid a stack trace error in Chimera
228      * after "stop really" is sent; Chimera > 1.14 will not need it; see also 
229      * http://plato.cgl.ucsf.edu/trac/chimera/ticket/17597
230      */
231     if (closeChimera && (getViewerType() == ViewerType.CHIMERA))
232     {
233       chimeraManager.getChimeraProcess().destroy();
234     }
235
236     chimeraManager.clearOnChimeraExit();
237     chimeraManager = null;
238   }
239
240   /**
241    * Helper method to construct model spec in Chimera format:
242    * <ul>
243    * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
244    * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
245    * <ul>
246    * Note for now we only ever choose the first of multiple models. This
247    * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
248    * future if there is a need to select specific sub-models.
249    * 
250    * @param pdbfnum
251    * @return
252    */
253   protected String getModelSpec(int pdbfnum)
254   {
255     if (pdbfnum < 0 || pdbfnum >= getPdbCount())
256     {
257       return "#" + pdbfnum; // temp hack for ChimeraX
258     }
259
260     /*
261      * For now, the test for having sub-models is whether multiple Chimera
262      * models are mapped for the PDB file; the models are returned as a response
263      * to the Chimera command 'list models type molecule', see
264      * ChimeraManager.getModelList().
265      */
266     List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
267     boolean hasSubModels = maps != null && maps.size() > 1;
268     return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
269   }
270
271   /**
272    * Launch Chimera, unless an instance linked to this object is already
273    * running. Returns true if Chimera is successfully launched, or already
274    * running, else false.
275    * 
276    * @return
277    */
278   public boolean launchChimera()
279   {
280     if (chimeraManager.isChimeraLaunched())
281     {
282       return true;
283     }
284
285     boolean launched = chimeraManager.launchChimera(getChimeraPaths());
286     if (launched)
287     {
288       startExternalViewerMonitor(chimeraManager.getChimeraProcess());
289     }
290     else
291     {
292       log("Failed to launch Chimera!");
293     }
294     return launched;
295   }
296
297   /**
298    * Returns a list of candidate paths to the Chimera program executable
299    * 
300    * @return
301    */
302   protected List<String> getChimeraPaths()
303   {
304     return StructureManager.getChimeraPaths(false);
305   }
306
307   /**
308    * Answers true if the Chimera process is still running, false if ended or not
309    * started.
310    * 
311    * @return
312    */
313   @Override
314   public boolean isViewerRunning()
315   {
316     return chimeraManager.isChimeraLaunched();
317   }
318
319   /**
320    * Send a command to Chimera, and optionally log and return any responses.
321    * 
322    * @param command
323    * @param getResponse
324    */
325   @Override
326   public List<String> executeCommand(final StructureCommandI command,
327           boolean getResponse)
328   {
329     if (chimeraManager == null || command == null)
330     {
331       // ? thread running after viewer shut down
332       return null;
333     }
334     List<String> reply = null;
335     // trim command or it may never find a match in the replyLog!!
336     String cmd = command.getCommand().trim();
337     List<String> lastReply = chimeraManager
338             .sendChimeraCommand(cmd, getResponse);
339     if (getResponse)
340     {
341       reply = lastReply;
342       Cache.log.debug(
343               "Response from command ('" + cmd + "') was:\n" + lastReply);
344     }
345
346     return reply;
347   }
348
349   @Override
350   public synchronized String[] getStructureFiles()
351   {
352     if (chimeraManager == null)
353     {
354       return new String[0];
355     }
356
357     return chimeraMaps.keySet()
358             .toArray(modelFileNames = new String[chimeraMaps.size()]);
359   }
360
361   /**
362    * Construct and send a command to highlight zero, one or more atoms. We do this
363    * by sending an "rlabel" command to show the residue label at that position.
364    */
365   @Override
366   public void highlightAtoms(List<AtomSpec> atoms)
367   {
368     if (atoms == null || atoms.size() == 0)
369     {
370       return;
371     }
372
373     boolean forChimeraX = chimeraManager.isChimeraX();
374     StringBuilder cmd = new StringBuilder(128);
375     boolean first = true;
376     boolean found = false;
377
378     for (AtomSpec atom : atoms)
379     {
380       int pdbResNum = atom.getPdbResNum();
381       String chain = atom.getChain();
382       String pdbfile = atom.getPdbFile();
383       List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
384       if (cms != null && !cms.isEmpty())
385       {
386         if (first)
387         {
388           cmd.append(forChimeraX ? "label #" : "rlabel #");
389         }
390         else
391         {
392           cmd.append(",");
393         }
394         first = false;
395         if (forChimeraX)
396         {
397           cmd.append(cms.get(0).getModelNumber())
398                   .append("/").append(chain).append(":").append(pdbResNum);
399         }
400         else
401         {
402           cmd.append(cms.get(0).getModelNumber())
403                   .append(":").append(pdbResNum);
404           if (!chain.equals(" ") && !forChimeraX)
405           {
406             cmd.append(".").append(chain);
407           }
408         }
409         found = true;
410       }
411     }
412     String command = cmd.toString();
413
414     /*
415      * avoid repeated commands for the same residue
416      */
417     if (command.equals(lastHighlightCommand))
418     {
419       return;
420     }
421
422     /*
423      * unshow the label for the previous residue
424      */
425     if (lastHighlightCommand != null)
426     {
427       chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
428     }
429     if (found)
430     {
431       chimeraManager.sendChimeraCommand(command, false);
432     }
433     this.lastHighlightCommand = command;
434   }
435
436   /**
437    * Query Chimera for its current selection, and highlight it on the alignment
438    */
439   public void highlightChimeraSelection()
440   {
441     /*
442      * Ask Chimera for its current selection
443      */
444     StructureCommandI command = getCommandGenerator().getSelectedResidues();
445     List<String> chimeraReply = executeCommand(command, true);
446     List<String> selectedResidues = new ArrayList<>();
447     if (chimeraReply != null)
448     {
449       /*
450        * expect 0, 1 or more lines of the format either
451        * Chimera:
452        * residue id #0:43.A type GLY
453        * ChimeraX:
454        * residue id /A:89 name THR index 88
455        * We are only interested in the atomspec (third token of the reply)
456        */
457       for (String inputLine : chimeraReply)
458       {
459         String[] inputLineParts = inputLine.split("\\s+");
460         if (inputLineParts.length >= 5)
461         {
462           selectedResidues.add(inputLineParts[2]);
463         }
464       }
465     }
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             selectedResidues);
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(X) 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     List<AtomSpec> atomSpecs = new ArrayList<>();
492     for (String atomSpec : structureSelection)
493     {
494       try
495       {
496         AtomSpec spec = parseAtomSpec(atomSpec);
497         String pdbfilename = getPdbFileForModel(spec.getModelNumber());
498         spec.setPdbFile(pdbfilename);
499         atomSpecs.add(spec);
500       } catch (IllegalArgumentException e)
501       {
502         Cache.log.error("Failed to parse atomspec: " + atomSpec);
503       }
504     }
505     return atomSpecs;
506   }
507
508   /**
509    * @param modelId
510    * @return
511    */
512   protected String getPdbFileForModel(int modelId)
513   {
514     /*
515      * Work out the pdbfilename from the model number
516      */
517     String pdbfilename = modelFileNames[0];
518     findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
519     {
520       for (ChimeraModel cm : chimeraMaps.get(pdbfile))
521       {
522         if (cm.getModelNumber() == modelId)
523         {
524           pdbfilename = pdbfile;
525           break findfileloop;
526         }
527       }
528     }
529     return pdbfilename;
530   }
531
532   private void log(String message)
533   {
534     System.err.println("## Chimera log: " + message);
535   }
536
537   /**
538    * Send a 'show' command for all atoms in the currently selected columns
539    * 
540    * TODO: pull up to abstract structure viewer interface
541    * 
542    * @param vp
543    */
544   public void highlightSelection(AlignmentViewPanel vp)
545   {
546     List<Integer> cols = vp.getAlignViewport().getColumnSelection()
547             .getSelected();
548     AlignmentI alignment = vp.getAlignment();
549     StructureSelectionManager sm = getSsm();
550     for (SequenceI seq : alignment.getSequences())
551     {
552       /*
553        * convert selected columns into sequence positions
554        */
555       int[] positions = new int[cols.size()];
556       int i = 0;
557       for (Integer col : cols)
558       {
559         positions[i++] = seq.findPosition(col);
560       }
561       sm.highlightStructure(this, seq, positions);
562     }
563   }
564
565   /**
566    * Constructs and send commands to Chimera to set attributes on residues for
567    * features visible in Jalview.
568    * <p>
569    * The syntax is: setattr r &lt;attName&gt; &lt;attValue&gt; &lt;atomSpec&gt;
570    * <p>
571    * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
572    * 
573    * @param avp
574    * @return
575    */
576   public int sendFeaturesToViewer(AlignmentViewPanel avp)
577   {
578     // TODO refactor as required to pull up to an interface
579
580     Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
581             avp);
582     List<StructureCommandI> commands = getCommandGenerator()
583             .setAttributes(featureValues);
584     if (commands.size() > 10)
585     {
586       sendCommandsByFile(commands);
587     }
588     else
589     {
590       for (StructureCommandI command : commands)
591       {
592         sendAsynchronousCommand(command, null);
593       }
594     }
595     return commands.size();
596   }
597
598   /**
599    * Write commands to a temporary file, and send a command to Chimera to open the
600    * file as a commands script. For use when sending a large number of separate
601    * commands would overload the REST interface mechanism.
602    * 
603    * @param commands
604    */
605   protected void sendCommandsByFile(List<StructureCommandI> commands)
606   {
607     try
608     {
609       File tmp = File.createTempFile("chim", getCommandFileExtension());
610       tmp.deleteOnExit();
611       PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
612       for (StructureCommandI command : commands)
613       {
614         out.println(command.getCommand());
615       }
616       out.flush();
617       out.close();
618       String path = tmp.getAbsolutePath();
619       StructureCommandI command = getCommandGenerator()
620               .openCommandFile(path);
621       sendAsynchronousCommand(command, null);
622     } catch (IOException e)
623     {
624       System.err.println("Sending commands to Chimera via file failed with "
625               + e.getMessage());
626     }
627   }
628
629   /**
630    * Returns the file extension required for a file of commands to be read by
631    * the structure viewer
632    * @return
633    */
634   protected String getCommandFileExtension()
635   {
636     return ".com";
637   }
638
639   /**
640    * Create features in Jalview for the given attribute name and structure
641    * residues.
642    * 
643    * <pre>
644    * The residue list should be 0, 1 or more reply lines of the format: 
645    *     residue id #0:5.A isHelix -155.000836316 index 5 
646    * or 
647    *     residue id #0:6.A isHelix None
648    * </pre>
649    * 
650    * @param attName
651    * @param residues
652    * @return the number of features added
653    */
654   protected int createFeaturesForAttributes(String attName,
655           List<String> residues)
656   {
657     int featuresAdded = 0;
658     String featureGroup = getViewerFeatureGroup();
659
660     for (String residue : residues)
661     {
662       AtomSpec spec = null;
663       String[] tokens = residue.split(" ");
664       if (tokens.length < 5)
665       {
666         continue;
667       }
668       String atomSpec = tokens[2];
669       String attValue = tokens[4];
670
671       /*
672        * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
673        */
674       if ("None".equalsIgnoreCase(attValue)
675               || "False".equalsIgnoreCase(attValue))
676       {
677         continue;
678       }
679
680       try
681       {
682         spec = parseAtomSpec(atomSpec);
683       } catch (IllegalArgumentException e)
684       {
685         Cache.log.error("Problem parsing atomspec " + atomSpec);
686         continue;
687       }
688
689       String chainId = spec.getChain();
690       String description = attValue;
691       float score = Float.NaN;
692       try
693       {
694         score = Float.valueOf(attValue);
695         description = chainId;
696       } catch (NumberFormatException e)
697       {
698         // was not a float value
699       }
700
701       String pdbFile = getPdbFileForModel(spec.getModelNumber());
702       spec.setPdbFile(pdbFile);
703
704       List<AtomSpec> atoms = Collections.singletonList(spec);
705
706       /*
707        * locate the mapped position in the alignment (if any)
708        */
709       SearchResultsI sr = getSsm()
710               .findAlignmentPositionsForStructurePositions(atoms);
711
712       /*
713        * expect one matched alignment position, or none 
714        * (if the structure position is not mapped)
715        */
716       for (SearchResultMatchI m : sr.getResults())
717       {
718         SequenceI seq = m.getSequence();
719         int start = m.getStart();
720         int end = m.getEnd();
721         SequenceFeature sf = new SequenceFeature(attName, description,
722                 start, end, score, featureGroup);
723         // todo: should SequenceFeature have an explicit property for chain?
724         // note: repeating the action shouldn't duplicate features
725         if (seq.addSequenceFeature(sf))
726         {
727           featuresAdded++;
728         }
729       }
730     }
731     return featuresAdded;
732   }
733
734   /**
735    * Answers the feature group name to apply to features created in Jalview from
736    * Chimera attributes
737    * 
738    * @return
739    */
740   protected String getViewerFeatureGroup()
741   {
742     // todo pull up to interface
743     return CHIMERA_FEATURE_GROUP;
744   }
745
746   @Override
747   public String getModelIdForFile(String pdbFile)
748   {
749     List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
750     if (foundModels != null && !foundModels.isEmpty())
751     {
752       return String.valueOf(foundModels.get(0).getModelNumber());
753     }
754     return "";
755   }
756
757   /**
758    * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
759    * any which were added from Jalview
760    * 
761    * @return
762    */
763   public List<String> getChimeraAttributes()
764   {
765     List<String> attributes = new ArrayList<>();
766     StructureCommandI command = getCommandGenerator().listResidueAttributes();
767     final List<String> reply = executeCommand(command, true);
768     if (reply != null)
769     {
770       for (String inputLine : reply)
771       {
772         String[] lineParts = inputLine.split("\\s");
773         if (lineParts.length == 2 && lineParts[0].equals("resattr"))
774         {
775           String attName = lineParts[1];
776           /*
777            * exclude attributes added from Jalview
778            */
779           if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
780           {
781             attributes.add(attName);
782           }
783         }
784       }
785     }
786     return attributes;
787   }
788
789   /**
790    * Returns the file extension to use for a saved viewer session file (.py)
791    * 
792    * @return
793    */
794   @Override
795   public String getSessionFileExtension()
796   {
797     return CHIMERA_SESSION_EXTENSION;
798   }
799
800   @Override
801   public String getHelpURL()
802   {
803     return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";
804   }
805 }