3 * Copyright (c) 2006 The Regents of the University of California.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions, and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions, and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
15 * 3. Redistributions must acknowledge that this software was
16 * originally developed by the UCSF Computer Graphics Laboratory
17 * under support by the NIH National Center for Research Resources,
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
21 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 package ext.edu.ucsf.rbvi.strucviz2;
35 import jalview.ws.HttpClientUtils;
37 import java.awt.Color;
38 import java.io.BufferedReader;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.nio.file.Paths;
44 import java.util.ArrayList;
45 import java.util.Collection;
46 import java.util.HashMap;
47 import java.util.List;
50 import org.apache.http.NameValuePair;
51 import org.apache.http.message.BasicNameValuePair;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
56 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
59 * This object maintains the Chimera communication information.
61 public class ChimeraManager
63 private static final int REST_REPLY_TIMEOUT_MS = 15000;
65 private static final int CONNECTION_TIMEOUT_MS = 100;
67 private static final boolean debug = false;
69 private int chimeraRestPort;
71 private Process chimera;
73 private ListenerThreads chimeraListenerThread;
75 private Map<Integer, ChimeraModel> currentModelsMap;
77 private Logger logger = LoggerFactory
78 .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
80 private StructureManager structureManager;
82 public ChimeraManager(StructureManager structureManager)
84 this.structureManager = structureManager;
86 chimeraListenerThread = null;
87 currentModelsMap = new HashMap<>();
91 public List<ChimeraModel> getChimeraModels(String modelName)
93 List<ChimeraModel> models = getChimeraModels(modelName,
95 models.addAll(getChimeraModels(modelName, ModelType.SMILES));
99 public List<ChimeraModel> getChimeraModels(String modelName,
102 List<ChimeraModel> models = new ArrayList<>();
103 for (ChimeraModel model : currentModelsMap.values())
105 if (modelName.equals(model.getModelName())
106 && modelType.equals(model.getModelType()))
114 public Map<String, List<ChimeraModel>> getChimeraModelsMap()
116 Map<String, List<ChimeraModel>> models = new HashMap<>();
117 for (ChimeraModel model : currentModelsMap.values())
119 String modelName = model.getModelName();
120 if (!models.containsKey(modelName))
122 models.put(modelName, new ArrayList<ChimeraModel>());
124 if (!models.get(modelName).contains(model))
126 models.get(modelName).add(model);
132 public ChimeraModel getChimeraModel(Integer modelNumber,
133 Integer subModelNumber)
135 Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
136 if (currentModelsMap.containsKey(key))
138 return currentModelsMap.get(key);
143 public ChimeraModel getChimeraModel()
145 return currentModelsMap.values().iterator().next();
148 public Collection<ChimeraModel> getChimeraModels()
150 // this method is invoked by the model navigator dialog
151 return currentModelsMap.values();
154 public int getChimeraModelsCount(boolean smiles)
156 // this method is invokes by the model navigator dialog
157 int counter = currentModelsMap.size();
163 for (ChimeraModel model : currentModelsMap.values())
165 if (model.getModelType() == ModelType.SMILES)
173 public boolean hasChimeraModel(Integer modelNubmer)
175 return hasChimeraModel(modelNubmer, 0);
178 public boolean hasChimeraModel(Integer modelNubmer, Integer subModelNumber)
180 return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
184 public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
187 currentModelsMap.put(
188 ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
191 public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
193 int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
194 if (currentModelsMap.containsKey(modelKey))
196 currentModelsMap.remove(modelKey);
200 public List<ChimeraModel> openModel(String modelPath, ModelType type)
202 return openModel(modelPath, getFileNameFromPath(modelPath), type);
206 * Overloaded method to allow Jalview to pass in a model name.
213 public List<ChimeraModel> openModel(String modelPath, String modelName,
216 logger.info("chimera open " + modelPath);
218 List<ChimeraModel> modelList = getModelList();
219 List<String> response = null;
220 // TODO: [Optional] Handle modbase models
221 if (type == ModelType.MODBASE_MODEL)
223 response = sendChimeraCommand("open modbase:" + modelPath, true);
224 // } else if (type == ModelType.SMILES) {
225 // response = sendChimeraCommand("open smiles:" + modelName, true);
226 // modelName = "smiles:" + modelName;
230 response = sendChimeraCommand("open " + modelPath, true);
232 if (response == null)
234 // something went wrong
235 logger.warn("Could not open " + modelPath);
239 // patch for Jalview - set model name in Chimera
240 // TODO: find a variant that works for sub-models
241 for (ChimeraModel newModel : getModelList())
243 if (!modelList.contains(newModel))
245 newModel.setModelName(modelName);
247 "setattr M name " + modelName + " #"
248 + newModel.getModelNumber(), false);
249 modelList.add(newModel);
253 // assign color and residues to open models
254 for (ChimeraModel chimeraModel : modelList)
257 Color modelColor = isChimeraX() ? null : getModelColor(chimeraModel);
258 if (modelColor != null)
260 chimeraModel.setModelColor(modelColor);
263 // Get our properties (default color scheme, etc.)
264 // Make the molecule look decent
265 // chimeraSend("repr stick "+newModel.toSpec());
267 // Create the information we need for the navigator
268 if (type != ModelType.SMILES && !isChimeraX())
270 addResidues(chimeraModel);
274 sendChimeraCommand("focus", false);
275 // startListening(); // see ChimeraListener
280 * Refactored method to extract the last (or only) element delimited by file
286 private String getFileNameFromPath(String modelPath)
288 String modelName = modelPath;
289 if (modelPath == null)
293 // TODO: [Optional] Convert path to name in a better way
294 if (modelPath.lastIndexOf(File.separator) > 0)
296 modelName = modelPath
297 .substring(modelPath.lastIndexOf(File.separator) + 1);
299 else if (modelPath.lastIndexOf("/") > 0)
301 modelName = modelPath.substring(modelPath.lastIndexOf("/") + 1);
306 public void closeModel(ChimeraModel model)
308 // int model = structure.modelNumber();
309 // int subModel = structure.subModelNumber();
310 // Integer modelKey = makeModelKey(model, subModel);
312 logger.info("chimera close model " + model.getModelName());
313 if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
314 model.getModelNumber(), model.getSubModelNumber())))
316 sendChimeraCommand("close " + model.toSpec(), false);
317 // currentModelNamesMap.remove(model.getModelName());
318 currentModelsMap.remove(ChimUtils.makeModelKey(
319 model.getModelNumber(), model.getSubModelNumber()));
320 // selectionList.remove(chimeraModel);
324 logger.warn("Could not find model " + model.getModelName()
330 public void startListening()
332 sendChimeraCommand("listen start models; listen start selection", false);
335 public void stopListening()
337 // TODO send this command when viewer connection is closed in Jalview
338 String command = isChimeraX
339 ? "info notify stop models jalview; info notify stop selection jalview"
340 : "listen stop models ; listen stop selection ";
341 sendChimeraCommand(command, false);
345 * Tell Chimera we are listening on the given URI
349 public void startListening(String uri)
352 * listen for model changes
354 String command = isChimeraX
355 ? ("info notify start models prefix ModelChanged jalview url "
357 : ("listen start models url " + uri);
358 sendChimeraCommand(command, false);
361 * listen for selection changes
364 ? ("info notify start selection jalview prefix SelectionChanged url "
366 : ("listen start select prefix SelectionChanged url " + uri);
367 sendChimeraCommand(command, false);
371 * Select something in Chimera
374 * the selection command to pass to Chimera
376 public void select(String command)
378 sendChimeraCommand("listen stop selection; " + command
379 + "; listen start selection", false);
384 sendChimeraCommand("focus", false);
387 public void clearOnChimeraExit()
390 currentModelsMap.clear();
391 this.chimeraRestPort = 0;
392 structureManager.clearOnChimeraExit();
395 public void exitChimera()
397 if (isChimeraLaunched() && chimera != null)
399 sendChimeraCommand("stop really", false);
402 // TODO is this too violent? could it force close the process
403 // before it has done an orderly shutdown?
405 } catch (Exception ex)
410 clearOnChimeraExit();
413 public Map<Integer, ChimeraModel> getSelectedModels()
415 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<>();
416 List<String> chimeraReply = sendChimeraCommand(
417 "list selection level molecule", true);
418 if (chimeraReply != null)
420 for (String modelLine : chimeraReply)
422 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
423 Integer modelKey = ChimUtils.makeModelKey(
424 chimeraModel.getModelNumber(),
425 chimeraModel.getSubModelNumber());
426 selectedModelsMap.put(modelKey, chimeraModel);
429 return selectedModelsMap;
433 * Sends a 'list selection level residue' command to Chimera and returns the
434 * list of selected atomspecs
438 public List<String> getSelectedResidueSpecs()
440 List<String> selectedResidues = new ArrayList<>();
443 * skip for now if ChimeraX - request times out
447 return selectedResidues;
450 // in fact 'listinfo' (undocumented) works in ChimeraX
451 String command = (isChimeraX
453 : "list") + " selection level residue";
454 List<String> chimeraReply = sendChimeraCommand(command, true);
455 if (chimeraReply != null)
458 * expect 0, 1 or more lines of the format either
460 * residue id #0:43.A type GLY
462 * residue id /A:89 name THR index 88
463 * We are only interested in the atomspec (third token of the reply)
465 for (String inputLine : chimeraReply)
467 String[] inputLineParts = inputLine.split("\\s+");
468 if (inputLineParts.length >= 5)
470 selectedResidues.add(inputLineParts[2]);
474 return selectedResidues;
477 public void getSelectedResidues(
478 Map<Integer, ChimeraModel> selectedModelsMap)
480 List<String> chimeraReply = sendChimeraCommand(
481 "list selection level residue", true);
482 if (chimeraReply != null)
484 for (String inputLine : chimeraReply)
486 ChimeraResidue r = new ChimeraResidue(inputLine);
487 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
488 r.getSubModelNumber());
489 if (selectedModelsMap.containsKey(modelKey))
491 ChimeraModel model = selectedModelsMap.get(modelKey);
499 * Return the list of ChimeraModels currently open. Warning: if smiles model
500 * name too long, only part of it with "..." is printed.
503 * @return List of ChimeraModel's
505 // TODO: [Optional] Handle smiles names in a better way in Chimera?
506 public List<ChimeraModel> getModelList()
508 List<ChimeraModel> modelList = new ArrayList<>();
509 String command = "list models type "
510 + (isChimeraX ? "AtomicStructure" : "molecule");
511 List<String> list = sendChimeraCommand(command, true);
514 for (String modelLine : list)
518 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
519 modelList.add(chimeraModel);
520 } catch (NullPointerException e)
530 * Return the list of depiction presets available from within Chimera. Chimera
531 * will return the list as a series of lines with the format: Preset type
532 * number "description"
534 * @return list of presets
536 public List<String> getPresets()
538 ArrayList<String> presetList = new ArrayList<>();
539 List<String> output = sendChimeraCommand("preset list", true);
542 for (String preset : output)
544 preset = preset.substring(7); // Skip over the "Preset"
545 preset = preset.replaceFirst("\"", "(");
546 preset = preset.replaceFirst("\"", ")");
547 // string now looks like: type number (description)
548 presetList.add(preset);
554 public boolean isChimeraLaunched()
556 boolean launched = false;
562 // if we get here, process has ended
563 } catch (IllegalThreadStateException e)
565 // ok - not yet terminated
573 * Launch Chimera, unless an instance linked to this object is already
574 * running. Returns true if chimera is successfully launched, or already
575 * running, else false.
577 * @param chimeraPaths
580 public boolean launchChimera(List<String> chimeraPaths)
582 // Do nothing if Chimera is already launched
583 if (isChimeraLaunched())
588 // Try to launch Chimera (eventually using one of the possible paths)
589 String error = "Error message: ";
590 String workingPath = "";
591 // iterate over possible paths for starting Chimera
592 for (String chimeraPath : chimeraPaths)
596 // ensure symbolic links are resolved
597 chimeraPath = Paths.get(chimeraPath).toRealPath().toString();
598 isChimeraX = chimeraPath.toLowerCase().contains("chimerax");
599 File path = new File(chimeraPath);
600 // uncomment the next line to simulate Chimera not installed
601 // path = new File(chimeraPath + "x");
602 if (!path.canExecute())
604 error += "File '" + path + "' does not exist.\n";
607 List<String> args = new ArrayList<>();
608 args.add(chimeraPath);
609 // shows Chimera output window but suppresses REST responses:
610 // args.add("--debug");
614 args.add("remote rest start");
619 args.add("RESTServer");
621 ProcessBuilder pb = new ProcessBuilder(args);
622 chimera = pb.start();
624 workingPath = chimeraPath;
626 } catch (Exception e)
628 // Chimera could not be started using this path
629 error += e.getMessage();
632 // If no error, then Chimera was launched successfully
633 if (error.length() == 0)
635 this.chimeraRestPort = getPortNumber();
636 System.out.println("Chimera REST API started on port "
638 // structureManager.initChimTable();
639 structureManager.setChimeraPathProperty(workingPath);
640 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
641 // Ask Chimera to give us updates
642 // startListening(); // later - see ChimeraListener
643 return (chimeraRestPort > 0);
646 // Tell the user that Chimera could not be started because of an error
652 * Read and return the port number returned in the reply to --start RESTServer
654 private int getPortNumber()
657 InputStream readChan = chimera.getInputStream();
658 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
660 StringBuilder responses = new StringBuilder();
663 String response = lineReader.readLine();
664 while (response != null)
666 responses.append("\n" + response);
667 // expect: REST server on host 127.0.0.1 port port_number
668 // ChimeraX is the same except "REST server started on host..."
669 if (response.startsWith("REST server"))
671 String[] tokens = response.split(" ");
672 for (int i = 0; i < tokens.length - 1; i++)
674 if ("port".equals(tokens[i]))
676 port = Integer.parseInt(tokens[i + 1]);
683 break; // hack for hanging readLine()
685 response = lineReader.readLine();
687 } catch (Exception e)
689 logger.error("Failed to get REST port number from " + responses
690 + ": " + e.getMessage());
696 } catch (IOException e2)
703 .println("Failed to start Chimera with REST service, response was: "
706 logger.info("Chimera REST service listening on port " + chimeraRestPort);
711 * Determine the color that Chimera is using for this model.
714 * the ChimeraModel we want to get the Color for
715 * @return the default model Color for this model in Chimera
717 public Color getModelColor(ChimeraModel model)
719 List<String> colorLines = sendChimeraCommand(
720 "list model spec " + model.toSpec() + " attribute color", true);
721 if (colorLines == null || colorLines.size() == 0)
725 return ChimUtils.parseModelColor(colorLines.get(0));
730 * Get information about the residues associated with a model. This uses the
731 * Chimera listr command. We don't return the resulting residues, but we add
732 * the residues to the model.
735 * the ChimeraModel to get residue information for
738 public void addResidues(ChimeraModel model)
740 int modelNumber = model.getModelNumber();
741 int subModelNumber = model.getSubModelNumber();
742 // Get the list -- it will be in the reply log
743 List<String> reply = sendChimeraCommand(
744 "list residues spec " + model.toSpec(), true);
749 for (String inputLine : reply)
751 ChimeraResidue r = new ChimeraResidue(inputLine);
752 if (r.getModelNumber() == modelNumber
753 || r.getSubModelNumber() == subModelNumber)
760 public List<String> getAttrList()
762 List<String> attributes = new ArrayList<>();
763 String command = (isChimeraX ? "info " : "list ") + "resattr";
764 final List<String> reply = sendChimeraCommand(command, true);
767 for (String inputLine : reply)
769 String[] lineParts = inputLine.split("\\s");
770 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
772 attributes.add(lineParts[1]);
779 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
782 Map<ChimeraResidue, Object> values = new HashMap<>();
783 final List<String> reply = sendChimeraCommand("list residue spec "
784 + model.toSpec() + " attribute " + aCommand, true);
787 for (String inputLine : reply)
789 String[] lineParts = inputLine.split("\\s");
790 if (lineParts.length == 5)
792 ChimeraResidue residue = ChimUtils
793 .getResidue(lineParts[2], model);
794 String value = lineParts[4];
797 if (value.equals("None"))
801 if (value.equals("True") || value.equals("False"))
803 values.put(residue, Boolean.valueOf(value));
808 Double doubleValue = Double.valueOf(value);
809 values.put(residue, doubleValue);
810 } catch (NumberFormatException ex)
812 values.put(residue, value);
821 private volatile boolean busy = false;
823 private boolean isChimeraX;
826 * Send a command to Chimera.
829 * Command string to be send.
831 * Flag indicating whether the method should return the reply from
833 * @return List of Strings corresponding to the lines in the Chimera reply or
836 public List<String> sendChimeraCommand(String command, boolean reply)
838 System.out.println("chimeradebug>> " + command);
839 if (!isChimeraLaunched() || command == null
840 || "".equals(command.trim()))
844 // TODO do we need a maximum wait time before aborting?
850 } catch (InterruptedException q)
855 long startTime = System.currentTimeMillis();
858 return sendRestCommand(command);
862 * Make sure busy flag is reset come what may!
867 System.out.println("Chimera command took "
868 + (System.currentTimeMillis() - startTime) + "ms: "
876 * Sends the command to Chimera's REST API, and returns any response lines.
881 protected List<String> sendRestCommand(String command)
883 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
884 List<NameValuePair> commands = new ArrayList<>(1);
885 String method = isChimeraX() ? "GET" : "POST";
886 if ("GET".equals(method))
888 command = command.replace(" ", "+").replace("#", "%23")
889 .replace("|", "%7C").replace(";", "%3B");
891 commands.add(new BasicNameValuePair("command", command));
893 List<String> reply = new ArrayList<>();
894 BufferedReader response = null;
897 response = "GET".equals(method)
898 ? HttpClientUtils.doHttpGet(restUrl, commands,
899 CONNECTION_TIMEOUT_MS, REST_REPLY_TIMEOUT_MS)
900 : HttpClientUtils.doHttpUrlPost(restUrl, commands,
901 CONNECTION_TIMEOUT_MS, REST_REPLY_TIMEOUT_MS);
903 while ((line = response.readLine()) != null)
907 } catch (Exception e)
909 logger.error("REST call '" + command + "' failed: " + e.getMessage());
912 if (response != null)
917 } catch (IOException e)
926 * Send a command to stdin of Chimera process, and optionally read any
933 protected List<String> sendStdinCommand(String command, boolean readReply)
935 chimeraListenerThread.clearResponse(command);
936 String text = command.concat("\n");
940 chimera.getOutputStream().write(text.getBytes());
941 chimera.getOutputStream().flush();
942 } catch (IOException e)
944 // logger.info("Unable to execute command: " + text);
945 // logger.info("Exiting...");
946 logger.warn("Unable to execute command: " + text);
947 logger.warn("Exiting...");
948 clearOnChimeraExit();
955 List<String> rsp = chimeraListenerThread.getResponse(command);
959 public StructureManager getStructureManager()
961 return structureManager;
964 public boolean isBusy()
969 public Process getChimeraProcess()
974 public boolean isChimeraX()
979 public void setChimeraX(boolean b)