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 java.awt.Color;
36 import java.io.BufferedReader;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.nio.file.Paths;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.HashMap;
45 import java.util.List;
48 import org.apache.http.NameValuePair;
49 import org.apache.http.message.BasicNameValuePair;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
54 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
55 import jalview.ws.HttpClientUtils;
58 * This object maintains the Chimera communication information.
60 public class ChimeraManager
62 private static final int REST_REPLY_TIMEOUT_MS = 15000;
64 private static final int CONNECTION_TIMEOUT_MS = 100;
66 private static final boolean debug = false;
68 private int chimeraRestPort;
70 private Process chimera;
72 private ListenerThreads chimeraListenerThread;
74 private Map<Integer, ChimeraModel> currentModelsMap;
76 private Logger logger = LoggerFactory
77 .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
79 private StructureManager structureManager;
81 public ChimeraManager(StructureManager structureManager)
83 this.structureManager = structureManager;
85 chimeraListenerThread = null;
86 currentModelsMap = new HashMap<>();
90 public List<ChimeraModel> getChimeraModels(String modelName)
92 List<ChimeraModel> models = getChimeraModels(modelName,
94 models.addAll(getChimeraModels(modelName, ModelType.SMILES));
98 public List<ChimeraModel> getChimeraModels(String modelName,
101 List<ChimeraModel> models = new ArrayList<>();
102 for (ChimeraModel model : currentModelsMap.values())
104 if (modelName.equals(model.getModelName())
105 && modelType.equals(model.getModelType()))
113 public Map<String, List<ChimeraModel>> getChimeraModelsMap()
115 Map<String, List<ChimeraModel>> models = new HashMap<>();
116 for (ChimeraModel model : currentModelsMap.values())
118 String modelName = model.getModelName();
119 if (!models.containsKey(modelName))
121 models.put(modelName, new ArrayList<ChimeraModel>());
123 if (!models.get(modelName).contains(model))
125 models.get(modelName).add(model);
131 public ChimeraModel getChimeraModel(Integer modelNumber,
132 Integer subModelNumber)
134 Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
135 if (currentModelsMap.containsKey(key))
137 return currentModelsMap.get(key);
142 public ChimeraModel getChimeraModel()
144 return currentModelsMap.values().iterator().next();
147 public Collection<ChimeraModel> getChimeraModels()
149 // this method is invoked by the model navigator dialog
150 return currentModelsMap.values();
153 public int getChimeraModelsCount(boolean smiles)
155 // this method is invokes by the model navigator dialog
156 int counter = currentModelsMap.size();
162 for (ChimeraModel model : currentModelsMap.values())
164 if (model.getModelType() == ModelType.SMILES)
172 public boolean hasChimeraModel(Integer modelNubmer)
174 return hasChimeraModel(modelNubmer, 0);
177 public boolean hasChimeraModel(Integer modelNubmer,
178 Integer subModelNumber)
180 return currentModelsMap.containsKey(
181 ChimUtils.makeModelKey(modelNubmer, subModelNumber));
184 public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
187 currentModelsMap.put(
188 ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
191 public void removeChimeraModel(Integer modelNumber,
192 Integer subModelNumber)
194 int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
195 if (currentModelsMap.containsKey(modelKey))
197 currentModelsMap.remove(modelKey);
201 public List<ChimeraModel> openModel(String modelPath, ModelType type)
203 return openModel(modelPath, getFileNameFromPath(modelPath), type);
207 * Overloaded method to allow Jalview to pass in a model name.
214 public List<ChimeraModel> openModel(String modelPath, String modelName,
217 logger.info("chimera open " + modelPath);
219 List<ChimeraModel> modelList = getModelList();
220 List<String> response = null;
221 // TODO: [Optional] Handle modbase models
222 if (type == ModelType.MODBASE_MODEL)
224 response = sendChimeraCommand("open modbase:" + modelPath, true);
225 // } else if (type == ModelType.SMILES) {
226 // response = sendChimeraCommand("open smiles:" + modelName, true);
227 // modelName = "smiles:" + modelName;
231 response = sendChimeraCommand("open " + modelPath, true);
233 if (response == null)
235 // something went wrong
236 logger.warn("Could not open " + modelPath);
240 // patch for Jalview - set model name in Chimera
241 // TODO: find a variant that works for sub-models
242 for (ChimeraModel newModel : getModelList())
244 if (!modelList.contains(newModel))
246 newModel.setModelName(modelName);
247 sendChimeraCommand("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(model.getModelNumber(),
319 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",
336 public void stopListening()
338 String command = "listen stop models ; listen stop selection ";
339 sendChimeraCommand(command, false);
343 * Tell Chimera we are listening on the given URI
347 public void startListening(String uri)
350 * listen for model changes
352 String command = "listen start models url " + uri;
353 sendChimeraCommand(command, false);
356 * listen for selection changes
358 command = "listen start select prefix SelectionChanged url " + uri;
359 sendChimeraCommand(command, false);
363 * Select something in Chimera
366 * the selection command to pass to Chimera
368 public void select(String command)
370 sendChimeraCommand("listen stop selection; " + command
371 + "; listen start selection", false);
376 sendChimeraCommand("focus", false);
379 public void clearOnChimeraExit()
382 currentModelsMap.clear();
383 this.chimeraRestPort = 0;
384 structureManager.clearOnChimeraExit();
387 public void exitChimera()
389 if (isChimeraLaunched() && chimera != null)
391 sendChimeraCommand("stop really", false);
394 // TODO is this too violent? could it force close the process
395 // before it has done an orderly shutdown?
397 } catch (Exception ex)
402 clearOnChimeraExit();
405 public Map<Integer, ChimeraModel> getSelectedModels()
407 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<>();
408 List<String> chimeraReply = sendChimeraCommand(
409 "list selection level molecule", true);
410 if (chimeraReply != null)
412 for (String modelLine : chimeraReply)
414 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
415 Integer modelKey = ChimUtils.makeModelKey(
416 chimeraModel.getModelNumber(),
417 chimeraModel.getSubModelNumber());
418 selectedModelsMap.put(modelKey, chimeraModel);
421 return selectedModelsMap;
425 * Sends a 'list selection level residue' command to Chimera and returns the
426 * list of selected atomspecs
430 public List<String> getSelectedResidueSpecs()
432 List<String> selectedResidues = new ArrayList<>();
434 String command = "list selection level residue";
435 List<String> chimeraReply = sendChimeraCommand(command, true);
436 if (chimeraReply != null)
439 * expect 0, 1 or more lines of the format either
441 * residue id #0:43.A type GLY
443 * residue id /A:89 name THR index 88
444 * We are only interested in the atomspec (third token of the reply)
446 for (String inputLine : chimeraReply)
448 String[] inputLineParts = inputLine.split("\\s+");
449 if (inputLineParts.length >= 5)
451 selectedResidues.add(inputLineParts[2]);
455 return selectedResidues;
458 public void getSelectedResidues(
459 Map<Integer, ChimeraModel> selectedModelsMap)
461 List<String> chimeraReply = sendChimeraCommand(
462 "list selection level residue", true);
463 if (chimeraReply != null)
465 for (String inputLine : chimeraReply)
467 ChimeraResidue r = new ChimeraResidue(inputLine);
468 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
469 r.getSubModelNumber());
470 if (selectedModelsMap.containsKey(modelKey))
472 ChimeraModel model = selectedModelsMap.get(modelKey);
480 * Return the list of ChimeraModels currently open. Warning: if smiles model
481 * name too long, only part of it with "..." is printed.
484 * @return List of ChimeraModel's
486 // TODO: [Optional] Handle smiles names in a better way in Chimera?
487 public List<ChimeraModel> getModelList()
489 List<ChimeraModel> modelList = new ArrayList<>();
490 String command = "list models type "
491 + (isChimeraX() ? "AtomicStructure" : "molecule");
492 List<String> list = sendChimeraCommand(command, true);
495 for (String modelLine : list)
499 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
500 modelList.add(chimeraModel);
501 } catch (NullPointerException e)
511 * Return the list of depiction presets available from within Chimera. Chimera
512 * will return the list as a series of lines with the format: Preset type
513 * number "description"
515 * @return list of presets
517 public List<String> getPresets()
519 ArrayList<String> presetList = new ArrayList<>();
520 List<String> output = sendChimeraCommand("preset list", true);
523 for (String preset : output)
525 preset = preset.substring(7); // Skip over the "Preset"
526 preset = preset.replaceFirst("\"", "(");
527 preset = preset.replaceFirst("\"", ")");
528 // string now looks like: type number (description)
529 presetList.add(preset);
535 public boolean isChimeraLaunched()
537 boolean launched = false;
543 // if we get here, process has ended
544 } catch (IllegalThreadStateException e)
546 // ok - not yet terminated
554 * Launch Chimera, unless an instance linked to this object is already
555 * running. Returns true if chimera is successfully launched, or already
556 * running, else false.
558 * @param chimeraPaths
561 public boolean launchChimera(List<String> chimeraPaths)
563 // Do nothing if Chimera is already launched
564 if (isChimeraLaunched())
569 // Try to launch Chimera (eventually using one of the possible paths)
570 String error = "Error message: ";
571 String workingPath = "";
572 // iterate over possible paths for starting Chimera
573 for (String chimeraPath : chimeraPaths)
577 // ensure symbolic links are resolved
578 chimeraPath = Paths.get(chimeraPath).toRealPath().toString();
579 File path = new File(chimeraPath);
580 // uncomment the next line to simulate Chimera not installed
581 // path = new File(chimeraPath + "x");
582 if (!path.canExecute())
584 error += "File '" + path + "' does not exist.\n";
587 List<String> args = new ArrayList<>();
588 args.add(chimeraPath);
589 // shows Chimera output window but suppresses REST responses:
590 // args.add("--debug");
591 addLaunchArguments(args);
592 ProcessBuilder pb = new ProcessBuilder(args);
593 chimera = pb.start();
595 workingPath = chimeraPath;
597 } catch (Exception e)
599 // Chimera could not be started using this path
600 error += e.getMessage();
603 // If no error, then Chimera was launched successfully
604 if (error.length() == 0)
606 this.chimeraRestPort = getPortNumber();
608 "Chimera REST API started on port " + chimeraRestPort);
609 // structureManager.initChimTable();
610 structureManager.setChimeraPathProperty(workingPath);
611 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
612 // Ask Chimera to give us updates
613 // startListening(); // later - see ChimeraListener
614 return (chimeraRestPort > 0);
617 // Tell the user that Chimera could not be started because of an error
623 * Adds command-line arguments to start the REST server
625 * Method extracted for Jalview to allow override in ChimeraXManager
629 protected void addLaunchArguments(List<String> args)
632 args.add("RESTServer");
636 * Read and return the port number returned in the reply to --start RESTServer
638 private int getPortNumber()
641 InputStream readChan = chimera.getInputStream();
642 BufferedReader lineReader = new BufferedReader(
643 new InputStreamReader(readChan));
644 StringBuilder responses = new StringBuilder();
647 String response = lineReader.readLine();
648 while (response != null)
650 responses.append("\n" + response);
651 // expect: REST server on host 127.0.0.1 port port_number
652 // ChimeraX is the same except "REST server started on host..."
653 if (response.startsWith("REST server"))
655 String[] tokens = response.split(" ");
656 for (int i = 0; i < tokens.length - 1; i++)
658 if ("port".equals(tokens[i]))
660 port = Integer.parseInt(tokens[i + 1]);
667 break; // hack for hanging readLine()
669 response = lineReader.readLine();
671 } catch (Exception e)
673 logger.error("Failed to get REST port number from " + responses + ": "
680 } catch (IOException e2)
687 "Failed to start Chimera with REST service, response was: "
691 "Chimera REST service listening on port " + chimeraRestPort);
696 * Determine the color that Chimera is using for this model.
699 * the ChimeraModel we want to get the Color for
700 * @return the default model Color for this model in Chimera
702 public Color getModelColor(ChimeraModel model)
704 List<String> colorLines = sendChimeraCommand(
705 "list model spec " + model.toSpec() + " attribute color", true);
706 if (colorLines == null || colorLines.size() == 0)
710 return ChimUtils.parseModelColor(colorLines.get(0));
715 * Get information about the residues associated with a model. This uses the
716 * Chimera listr command. We don't return the resulting residues, but we add
717 * the residues to the model.
720 * the ChimeraModel to get residue information for
723 public void addResidues(ChimeraModel model)
725 int modelNumber = model.getModelNumber();
726 int subModelNumber = model.getSubModelNumber();
727 // Get the list -- it will be in the reply log
728 List<String> reply = sendChimeraCommand(
729 "list residues spec " + model.toSpec(), true);
734 for (String inputLine : reply)
736 ChimeraResidue r = new ChimeraResidue(inputLine);
737 if (r.getModelNumber() == modelNumber
738 || r.getSubModelNumber() == subModelNumber)
745 public List<String> getAttrList()
747 List<String> attributes = new ArrayList<>();
748 String command = (isChimeraX() ? "info " : "list ") + "resattr";
749 final List<String> reply = sendChimeraCommand(command, true);
752 for (String inputLine : reply)
754 String[] lineParts = inputLine.split("\\s");
755 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
757 attributes.add(lineParts[1]);
764 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
767 Map<ChimeraResidue, Object> values = new HashMap<>();
768 final List<String> reply = sendChimeraCommand("list residue spec "
769 + model.toSpec() + " attribute " + aCommand, true);
772 for (String inputLine : reply)
774 String[] lineParts = inputLine.split("\\s");
775 if (lineParts.length == 5)
777 ChimeraResidue residue = ChimUtils.getResidue(lineParts[2],
779 String value = lineParts[4];
782 if (value.equals("None"))
786 if (value.equals("True") || value.equals("False"))
788 values.put(residue, Boolean.valueOf(value));
793 Double doubleValue = Double.valueOf(value);
794 values.put(residue, doubleValue);
795 } catch (NumberFormatException ex)
797 values.put(residue, value);
806 private volatile boolean busy = false;
809 * Send a command to Chimera.
812 * Command string to be send.
814 * Flag indicating whether the method should return the reply from
816 * @return List of Strings corresponding to the lines in the Chimera reply or
819 public List<String> sendChimeraCommand(String command, boolean reply)
823 System.out.println("chimeradebug>> " + command);
825 if (!isChimeraLaunched() || command == null
826 || "".equals(command.trim()))
831 * set a maximum wait time before trying anyway
832 * to avoid hanging indefinitely
836 while (busy && waited < 1001)
842 } catch (InterruptedException q)
847 long startTime = System.currentTimeMillis();
850 return sendRestCommand(command);
854 * Make sure busy flag is reset come what may!
859 System.out.println("Chimera command took "
860 + (System.currentTimeMillis() - startTime) + "ms: "
867 * Sends the command to Chimera's REST API, and returns any response lines.
872 protected List<String> sendRestCommand(String command)
874 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
875 List<NameValuePair> commands = new ArrayList<>(1);
876 String method = getHttpRequestMethod();
877 if ("GET".equals(method))
879 command = command.replace(" ", "+").replace("#", "%23")
880 .replace("|", "%7C").replace(";", "%3B");
882 commands.add(new BasicNameValuePair("command", command));
884 List<String> reply = new ArrayList<>();
885 BufferedReader response = null;
888 response = "GET".equals(method)
889 ? HttpClientUtils.doHttpGet(restUrl, commands,
890 CONNECTION_TIMEOUT_MS, REST_REPLY_TIMEOUT_MS)
891 : HttpClientUtils.doHttpUrlPost(restUrl, commands,
892 CONNECTION_TIMEOUT_MS, REST_REPLY_TIMEOUT_MS);
894 while ((line = response.readLine()) != null)
898 } catch (Exception e)
900 logger.error("REST call '" + command + "' failed: " + e.getMessage());
903 if (response != null)
908 } catch (IOException e)
917 * Returns "POST" as the HTTP request method to use for REST service calls to
922 protected String getHttpRequestMethod()
928 * Send a command to stdin of Chimera process, and optionally read any
935 protected List<String> sendStdinCommand(String command, boolean readReply)
937 chimeraListenerThread.clearResponse(command);
938 String text = command.concat("\n");
942 chimera.getOutputStream().write(text.getBytes());
943 chimera.getOutputStream().flush();
944 } catch (IOException e)
946 // logger.info("Unable to execute command: " + text);
947 // logger.info("Exiting...");
948 logger.warn("Unable to execute command: " + text);
949 logger.warn("Exiting...");
950 clearOnChimeraExit();
957 List<String> rsp = chimeraListenerThread.getResponse(command);
961 public StructureManager getStructureManager()
963 return structureManager;
966 public boolean isBusy()
971 public Process getChimeraProcess()
976 public boolean isChimeraX()