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