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