549636bf42f5571c9b53a720729a6be832c1c299
[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       if (Cache.log.isDebugEnabled()) {
343         Cache.log.debug(
344               "Response from command ('" + cmd + "') was:\n" + lastReply); 
345       }
346     }
347
348     return reply;
349   }
350
351   @Override
352   public synchronized String[] getStructureFiles()
353   {
354     if (chimeraManager == null)
355     {
356       return new String[0];
357     }
358
359     return chimeraMaps.keySet()
360             .toArray(modelFileNames = new String[chimeraMaps.size()]);
361   }
362
363   /**
364    * Construct and send a command to highlight zero, one or more atoms. We do this
365    * by sending an "rlabel" command to show the residue label at that position.
366    */
367   @Override
368   public void highlightAtoms(List<AtomSpec> atoms)
369   {
370     if (atoms == null || atoms.size() == 0)
371     {
372       return;
373     }
374
375     boolean forChimeraX = chimeraManager.isChimeraX();
376     StringBuilder cmd = new StringBuilder(128);
377     boolean first = true;
378     boolean found = false;
379
380     for (AtomSpec atom : atoms)
381     {
382       int pdbResNum = atom.getPdbResNum();
383       String chain = atom.getChain();
384       String pdbfile = atom.getPdbFile();
385       List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
386       if (cms != null && !cms.isEmpty())
387       {
388         if (first)
389         {
390           cmd.append(forChimeraX ? "label #" : "rlabel #");
391         }
392         else
393         {
394           cmd.append(",");
395         }
396         first = false;
397         if (forChimeraX)
398         {
399           cmd.append(cms.get(0).getModelNumber())
400                   .append("/").append(chain).append(":").append(pdbResNum);
401         }
402         else
403         {
404           cmd.append(cms.get(0).getModelNumber())
405                   .append(":").append(pdbResNum);
406           if (!chain.equals(" ") && !forChimeraX)
407           {
408             cmd.append(".").append(chain);
409           }
410         }
411         found = true;
412       }
413     }
414     String command = cmd.toString();
415
416     /*
417      * avoid repeated commands for the same residue
418      */
419     if (command.equals(lastHighlightCommand))
420     {
421       return;
422     }
423
424     /*
425      * unshow the label for the previous residue
426      */
427     if (lastHighlightCommand != null)
428     {
429       chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
430     }
431     if (found)
432     {
433       chimeraManager.sendChimeraCommand(command, false);
434     }
435     this.lastHighlightCommand = command;
436   }
437
438   /**
439    * Query Chimera for its current selection, and highlight it on the alignment
440    */
441   public void highlightChimeraSelection()
442   {
443     /*
444      * Ask Chimera for its current selection
445      */
446     StructureCommandI command = getCommandGenerator().getSelectedResidues();
447     
448     Runnable action = new Runnable()
449     {
450       @Override
451       public void run()
452       {
453         List<String> chimeraReply = executeCommand(command, true);
454         
455         List<String> selectedResidues = new ArrayList<>();
456         if (chimeraReply != null)
457         {
458           /*
459            * expect 0, 1 or more lines of the format either
460            * Chimera:
461            * residue id #0:43.A type GLY
462            * ChimeraX:
463            * residue id /A:89 name THR index 88
464            * We are only interested in the atomspec (third token of the reply)
465            */
466           for (String inputLine : chimeraReply)
467           {
468             String[] inputLineParts = inputLine.split("\\s+");
469             if (inputLineParts.length >= 5)
470             {
471               selectedResidues.add(inputLineParts[2]);
472             }
473           }
474         }
475
476         /*
477          * Parse model number, residue and chain for each selected position,
478          * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
479          */
480         List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
481                 selectedResidues);
482
483         /*
484          * Broadcast the selection (which may be empty, if the user just cleared all
485          * selections)
486          */
487         getSsm().mouseOverStructure(atomSpecs);
488         
489       }
490     };
491     new Thread(action).start();
492   }
493
494   /**
495    * Converts a list of Chimera(X) atomspecs to a list of AtomSpec representing the
496    * corresponding residues (if any) in Jalview
497    * 
498    * @param structureSelection
499    * @return
500    */
501   protected List<AtomSpec> convertStructureResiduesToAlignment(
502           List<String> structureSelection)
503   {
504     List<AtomSpec> atomSpecs = new ArrayList<>();
505     for (String atomSpec : structureSelection)
506     {
507       try
508       {
509         AtomSpec spec = parseAtomSpec(atomSpec);
510         String pdbfilename = getPdbFileForModel(spec.getModelNumber());
511         spec.setPdbFile(pdbfilename);
512         atomSpecs.add(spec);
513       } catch (IllegalArgumentException e)
514       {
515         Cache.log.error("Failed to parse atomspec: " + atomSpec);
516       }
517     }
518     return atomSpecs;
519   }
520
521   /**
522    * @param modelId
523    * @return
524    */
525   protected String getPdbFileForModel(int modelId)
526   {
527     /*
528      * Work out the pdbfilename from the model number
529      */
530     String pdbfilename = modelFileNames[0];
531     findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
532     {
533       for (ChimeraModel cm : chimeraMaps.get(pdbfile))
534       {
535         if (cm.getModelNumber() == modelId)
536         {
537           pdbfilename = pdbfile;
538           break findfileloop;
539         }
540       }
541     }
542     return pdbfilename;
543   }
544
545   private void log(String message)
546   {
547     System.err.println("## Chimera log: " + message);
548   }
549
550   /**
551    * Constructs and send commands to Chimera to set attributes on residues for
552    * features visible in Jalview.
553    * <p>
554    * The syntax is: setattr r &lt;attName&gt; &lt;attValue&gt; &lt;atomSpec&gt;
555    * <p>
556    * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
557    * 
558    * @param avp
559    * @return
560    */
561   public int sendFeaturesToViewer(AlignmentViewPanel avp)
562   {
563     // TODO refactor as required to pull up to an interface
564
565     Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
566             avp);
567     List<StructureCommandI> commands = getCommandGenerator()
568             .setAttributes(featureValues);
569     if (commands.size() > 10)
570     {
571       sendCommandsByFile(commands);
572     }
573     else
574     {
575       for (StructureCommandI command : commands)
576       {
577         sendAsynchronousCommand(command, null);
578       }
579     }
580     return commands.size();
581   }
582
583   /**
584    * Write commands to a temporary file, and send a command to Chimera to open the
585    * file as a commands script. For use when sending a large number of separate
586    * commands would overload the REST interface mechanism.
587    * 
588    * @param commands
589    */
590   protected void sendCommandsByFile(List<StructureCommandI> commands)
591   {
592     try
593     {
594       File tmp = File.createTempFile("chim", getCommandFileExtension());
595       tmp.deleteOnExit();
596       PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
597       for (StructureCommandI command : commands)
598       {
599         out.println(command.getCommand());
600       }
601       out.flush();
602       out.close();
603       String path = tmp.getAbsolutePath();
604       StructureCommandI command = getCommandGenerator()
605               .openCommandFile(path);
606       sendAsynchronousCommand(command, null);
607     } catch (IOException e)
608     {
609       System.err.println("Sending commands to Chimera via file failed with "
610               + e.getMessage());
611     }
612   }
613
614   /**
615    * Returns the file extension required for a file of commands to be read by
616    * the structure viewer
617    * @return
618    */
619   protected String getCommandFileExtension()
620   {
621     return ".com";
622   }
623
624   /**
625    * Create features in Jalview for the given attribute name and structure
626    * residues.
627    * 
628    * <pre>
629    * The residue list should be 0, 1 or more reply lines of the format: 
630    *     residue id #0:5.A isHelix -155.000836316 index 5 
631    * or 
632    *     residue id #0:6.A isHelix None
633    * </pre>
634    * 
635    * @param attName
636    * @param residues
637    * @return the number of features added
638    */
639   protected int createFeaturesForAttributes(String attName,
640           List<String> residues)
641   {
642     int featuresAdded = 0;
643     String featureGroup = getViewerFeatureGroup();
644
645     for (String residue : residues)
646     {
647       AtomSpec spec = null;
648       String[] tokens = residue.split(" ");
649       if (tokens.length < 5)
650       {
651         continue;
652       }
653       String atomSpec = tokens[2];
654       String attValue = tokens[4];
655
656       /*
657        * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
658        */
659       if ("None".equalsIgnoreCase(attValue)
660               || "False".equalsIgnoreCase(attValue))
661       {
662         continue;
663       }
664
665       try
666       {
667         spec = parseAtomSpec(atomSpec);
668       } catch (IllegalArgumentException e)
669       {
670         Cache.log.error("Problem parsing atomspec " + atomSpec);
671         continue;
672       }
673
674       String chainId = spec.getChain();
675       String description = attValue;
676       float score = Float.NaN;
677       try
678       {
679         score = Float.valueOf(attValue);
680         description = chainId;
681       } catch (NumberFormatException e)
682       {
683         // was not a float value
684       }
685
686       String pdbFile = getPdbFileForModel(spec.getModelNumber());
687       spec.setPdbFile(pdbFile);
688
689       List<AtomSpec> atoms = Collections.singletonList(spec);
690
691       /*
692        * locate the mapped position in the alignment (if any)
693        */
694       SearchResultsI sr = getSsm()
695               .findAlignmentPositionsForStructurePositions(atoms);
696
697       /*
698        * expect one matched alignment position, or none 
699        * (if the structure position is not mapped)
700        */
701       for (SearchResultMatchI m : sr.getResults())
702       {
703         SequenceI seq = m.getSequence();
704         int start = m.getStart();
705         int end = m.getEnd();
706         SequenceFeature sf = new SequenceFeature(attName, description,
707                 start, end, score, featureGroup);
708         // todo: should SequenceFeature have an explicit property for chain?
709         // note: repeating the action shouldn't duplicate features
710         if (seq.addSequenceFeature(sf))
711         {
712           featuresAdded++;
713         }
714       }
715     }
716     return featuresAdded;
717   }
718
719   /**
720    * Answers the feature group name to apply to features created in Jalview from
721    * Chimera attributes
722    * 
723    * @return
724    */
725   protected String getViewerFeatureGroup()
726   {
727     // todo pull up to interface
728     return CHIMERA_FEATURE_GROUP;
729   }
730
731   @Override
732   public String getModelIdForFile(String pdbFile)
733   {
734     List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
735     if (foundModels != null && !foundModels.isEmpty())
736     {
737       return String.valueOf(foundModels.get(0).getModelNumber());
738     }
739     return "";
740   }
741
742   /**
743    * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
744    * any which were added from Jalview
745    * 
746    * @return
747    */
748   public List<String> getChimeraAttributes()
749   {
750     List<String> attributes = new ArrayList<>();
751     StructureCommandI command = getCommandGenerator().listResidueAttributes();
752     final List<String> reply = executeCommand(command, true);
753     if (reply != null)
754     {
755       for (String inputLine : reply)
756       {
757         String[] lineParts = inputLine.split("\\s");
758         if (lineParts.length == 2 && lineParts[0].equals("resattr"))
759         {
760           String attName = lineParts[1];
761           /*
762            * exclude attributes added from Jalview
763            */
764           if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
765           {
766             attributes.add(attName);
767           }
768         }
769       }
770     }
771     return attributes;
772   }
773
774   /**
775    * Returns the file extension to use for a saved viewer session file (.py)
776    * 
777    * @return
778    */
779   @Override
780   public String getSessionFileExtension()
781   {
782     return CHIMERA_SESSION_EXTENSION;
783   }
784
785   @Override
786   public String getHelpURL()
787   {
788     return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";
789   }
790 }