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