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.util.ArrayList;
44 import java.util.Collection;
45 import java.util.HashMap;
46 import java.util.List;
49 import org.apache.http.NameValuePair;
50 import org.apache.http.message.BasicNameValuePair;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
55 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
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<Integer, ChimeraModel>();
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<ChimeraModel>();
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<String, List<ChimeraModel>>();
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, Integer subModelNumber)
179 return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
183 public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
186 currentModelsMap.put(
187 ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
190 public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
192 int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
193 if (currentModelsMap.containsKey(modelKey))
195 currentModelsMap.remove(modelKey);
199 public List<ChimeraModel> openModel(String modelPath, ModelType type)
201 return openModel(modelPath, getFileNameFromPath(modelPath), type);
205 * Overloaded method to allow Jalview to pass in a model name.
212 public List<ChimeraModel> openModel(String modelPath, String modelName,
215 logger.info("chimera open " + modelPath);
217 List<ChimeraModel> modelList = getModelList();
218 List<String> response = null;
219 // TODO: [Optional] Handle modbase models
220 if (type == ModelType.MODBASE_MODEL)
222 response = sendChimeraCommand("open modbase:" + modelPath, true);
223 // } else if (type == ModelType.SMILES) {
224 // response = sendChimeraCommand("open smiles:" + modelName, true);
225 // modelName = "smiles:" + modelName;
229 response = sendChimeraCommand("open " + modelPath, true);
231 if (response == null)
233 // something went wrong
234 logger.warn("Could not open " + modelPath);
238 // patch for Jalview - set model name in Chimera
239 // TODO: find a variant that works for sub-models
240 for (ChimeraModel newModel : getModelList())
242 if (!modelList.contains(newModel))
244 newModel.setModelName(modelName);
246 "setattr M name " + modelName + " #"
247 + newModel.getModelNumber(), false);
248 modelList.add(newModel);
252 // assign color and residues to open models
253 for (ChimeraModel chimeraModel : modelList)
256 Color modelColor = getModelColor(chimeraModel);
257 if (modelColor != null)
259 chimeraModel.setModelColor(modelColor);
262 // Get our properties (default color scheme, etc.)
263 // Make the molecule look decent
264 // chimeraSend("repr stick "+newModel.toSpec());
266 // Create the information we need for the navigator
267 if (type != ModelType.SMILES)
269 addResidues(chimeraModel);
273 sendChimeraCommand("focus", false);
274 // startListening(); // see ChimeraListener
279 * Refactored method to extract the last (or only) element delimited by file
285 private String getFileNameFromPath(String modelPath)
287 String modelName = modelPath;
288 if (modelPath == null)
292 // TODO: [Optional] Convert path to name in a better way
293 if (modelPath.lastIndexOf(File.separator) > 0)
295 modelName = modelPath
296 .substring(modelPath.lastIndexOf(File.separator) + 1);
298 else if (modelPath.lastIndexOf("/") > 0)
300 modelName = modelPath.substring(modelPath.lastIndexOf("/") + 1);
305 public void closeModel(ChimeraModel model)
307 // int model = structure.modelNumber();
308 // int subModel = structure.subModelNumber();
309 // Integer modelKey = makeModelKey(model, subModel);
311 logger.info("chimera close model " + model.getModelName());
312 if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
313 model.getModelNumber(), model.getSubModelNumber())))
315 sendChimeraCommand("close " + model.toSpec(), false);
316 // currentModelNamesMap.remove(model.getModelName());
317 currentModelsMap.remove(ChimUtils.makeModelKey(
318 model.getModelNumber(), model.getSubModelNumber()));
319 // selectionList.remove(chimeraModel);
323 logger.warn("Could not find model " + model.getModelName()
329 public void startListening()
331 sendChimeraCommand("listen start models; listen start selection", false);
334 public void stopListening()
336 sendChimeraCommand("listen stop models ; listen stop selection ", false);
340 * Tell Chimera we are listening on the given URI
344 public void startListening(String uri)
346 sendChimeraCommand("listen start models url " + uri
347 + ";listen start select prefix SelectionChanged url " + uri,
352 * Select something in Chimera
355 * the selection command to pass to Chimera
357 public void select(String command)
359 sendChimeraCommand("listen stop selection; " + command
360 + "; listen start selection", false);
365 sendChimeraCommand("focus", false);
368 public void clearOnChimeraExit()
371 currentModelsMap.clear();
372 this.chimeraRestPort = 0;
373 structureManager.clearOnChimeraExit();
376 public void exitChimera()
378 if (isChimeraLaunched() && chimera != null)
380 sendChimeraCommand("stop really", false);
384 } catch (Exception ex)
389 clearOnChimeraExit();
392 public Map<Integer, ChimeraModel> getSelectedModels()
394 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
395 List<String> chimeraReply = sendChimeraCommand(
396 "list selection level molecule", true);
397 if (chimeraReply != null)
399 for (String modelLine : chimeraReply)
401 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
402 Integer modelKey = ChimUtils.makeModelKey(
403 chimeraModel.getModelNumber(),
404 chimeraModel.getSubModelNumber());
405 selectedModelsMap.put(modelKey, chimeraModel);
408 return selectedModelsMap;
412 * Sends a 'list selection level residue' command to Chimera and returns the
413 * list of selected atomspecs
417 public List<String> getSelectedResidueSpecs()
419 List<String> selectedResidues = new ArrayList<String>();
420 List<String> chimeraReply = sendChimeraCommand(
421 "list selection level residue", true);
422 if (chimeraReply != null)
425 * expect 0, 1 or more lines of the format
426 * residue id #0:43.A type GLY
427 * where we are only interested in the atomspec #0.43.A
429 for (String inputLine : chimeraReply)
431 String[] inputLineParts = inputLine.split("\\s+");
432 if (inputLineParts.length == 5)
434 selectedResidues.add(inputLineParts[2]);
438 return selectedResidues;
441 public void getSelectedResidues(
442 Map<Integer, ChimeraModel> selectedModelsMap)
444 List<String> chimeraReply = sendChimeraCommand(
445 "list selection level residue", true);
446 if (chimeraReply != null)
448 for (String inputLine : chimeraReply)
450 ChimeraResidue r = new ChimeraResidue(inputLine);
451 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
452 r.getSubModelNumber());
453 if (selectedModelsMap.containsKey(modelKey))
455 ChimeraModel model = selectedModelsMap.get(modelKey);
463 * Return the list of ChimeraModels currently open. Warning: if smiles model
464 * name too long, only part of it with "..." is printed.
467 * @return List of ChimeraModel's
469 // TODO: [Optional] Handle smiles names in a better way in Chimera?
470 public List<ChimeraModel> getModelList()
472 List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
473 List<String> list = sendChimeraCommand("list models type molecule",
477 for (String modelLine : list)
479 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
480 modelList.add(chimeraModel);
487 * Return the list of depiction presets available from within Chimera. Chimera
488 * will return the list as a series of lines with the format: Preset type
489 * number "description"
491 * @return list of presets
493 public List<String> getPresets()
495 ArrayList<String> presetList = new ArrayList<String>();
496 List<String> output = sendChimeraCommand("preset list", true);
499 for (String preset : output)
501 preset = preset.substring(7); // Skip over the "Preset"
502 preset = preset.replaceFirst("\"", "(");
503 preset = preset.replaceFirst("\"", ")");
504 // string now looks like: type number (description)
505 presetList.add(preset);
511 public boolean isChimeraLaunched()
513 boolean launched = false;
519 // if we get here, process has ended
520 } catch (IllegalThreadStateException e)
522 // ok - not yet terminated
530 * Launch Chimera, unless an instance linked to this object is already
531 * running. Returns true if chimera is successfully launched, or already
532 * running, else false.
534 * @param chimeraPaths
537 public boolean launchChimera(List<String> chimeraPaths)
539 // Do nothing if Chimera is already launched
540 if (isChimeraLaunched())
545 // Try to launch Chimera (eventually using one of the possible paths)
546 String error = "Error message: ";
547 String workingPath = "";
548 // iterate over possible paths for starting Chimera
549 for (String chimeraPath : chimeraPaths)
551 File path = new File(chimeraPath);
552 // uncomment the next line to simulate Chimera not installed
553 // path = new File(chimeraPath + "x");
554 if (!path.canExecute())
556 error += "File '" + path + "' does not exist.\n";
561 List<String> args = new ArrayList<String>();
562 args.add(chimeraPath);
563 // shows Chimera output window but suppresses REST responses:
564 // args.add("--debug");
566 args.add("RESTServer");
567 ProcessBuilder pb = new ProcessBuilder(args);
568 chimera = pb.start();
570 workingPath = chimeraPath;
572 } catch (Exception e)
574 // Chimera could not be started
575 error += e.getMessage();
578 // If no error, then Chimera was launched successfully
579 if (error.length() == 0)
581 this.chimeraRestPort = getPortNumber();
582 System.out.println("Chimera REST API started on port "
584 // structureManager.initChimTable();
585 structureManager.setChimeraPathProperty(workingPath);
586 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
587 // Ask Chimera to give us updates
588 // startListening(); // later - see ChimeraListener
589 return (chimeraRestPort > 0);
592 // Tell the user that Chimera could not be started because of an error
598 * Read and return the port number returned in the reply to --start RESTServer
600 private int getPortNumber()
603 InputStream readChan = chimera.getInputStream();
604 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
606 StringBuilder responses = new StringBuilder();
609 String response = lineReader.readLine();
610 while (response != null)
612 responses.append("\n" + response);
613 // expect: REST server on host 127.0.0.1 port port_number
614 if (response.startsWith("REST server"))
616 String[] tokens = response.split(" ");
617 if (tokens.length == 7 && "port".equals(tokens[5]))
619 port = Integer.parseInt(tokens[6]);
623 response = lineReader.readLine();
625 } catch (Exception e)
627 logger.error("Failed to get REST port number from " + responses
628 + ": " + e.getMessage());
634 } catch (IOException e2)
641 .println("Failed to start Chimera with REST service, response was: "
644 logger.info("Chimera REST service listening on port " + chimeraRestPort);
649 * Determine the color that Chimera is using for this model.
652 * the ChimeraModel we want to get the Color for
653 * @return the default model Color for this model in Chimera
655 public Color getModelColor(ChimeraModel model)
657 List<String> colorLines = sendChimeraCommand(
658 "list model spec " + model.toSpec() + " attribute color", true);
659 if (colorLines == null || colorLines.size() == 0)
663 return ChimUtils.parseModelColor(colorLines.get(0));
668 * Get information about the residues associated with a model. This uses the
669 * Chimera listr command. We don't return the resulting residues, but we add
670 * the residues to the model.
673 * the ChimeraModel to get residue information for
676 public void addResidues(ChimeraModel model)
678 int modelNumber = model.getModelNumber();
679 int subModelNumber = model.getSubModelNumber();
680 // Get the list -- it will be in the reply log
681 List<String> reply = sendChimeraCommand(
682 "list residues spec " + model.toSpec(), true);
687 for (String inputLine : reply)
689 ChimeraResidue r = new ChimeraResidue(inputLine);
690 if (r.getModelNumber() == modelNumber
691 || r.getSubModelNumber() == subModelNumber)
698 public List<String> getAttrList()
700 List<String> attributes = new ArrayList<String>();
701 final List<String> reply = sendChimeraCommand("list resattr", true);
704 for (String inputLine : reply)
706 String[] lineParts = inputLine.split("\\s");
707 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
709 attributes.add(lineParts[1]);
716 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
719 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
720 final List<String> reply = sendChimeraCommand("list residue spec "
721 + model.toSpec() + " attribute " + aCommand, true);
724 for (String inputLine : reply)
726 String[] lineParts = inputLine.split("\\s");
727 if (lineParts.length == 5)
729 ChimeraResidue residue = ChimUtils
730 .getResidue(lineParts[2], model);
731 String value = lineParts[4];
734 if (value.equals("None"))
738 if (value.equals("True") || value.equals("False"))
740 values.put(residue, Boolean.valueOf(value));
745 Double doubleValue = Double.valueOf(value);
746 values.put(residue, doubleValue);
747 } catch (NumberFormatException ex)
749 values.put(residue, value);
758 private volatile boolean busy = false;
761 * Send a command to Chimera.
764 * Command string to be send.
766 * Flag indicating whether the method should return the reply from
768 * @return List of Strings corresponding to the lines in the Chimera reply or
771 public List<String> sendChimeraCommand(String command, boolean reply)
773 // System.out.println("chimeradebug>> " + command);
774 if (!isChimeraLaunched() || command == null
775 || "".equals(command.trim()))
779 // TODO do we need a maximum wait time before aborting?
785 } catch (InterruptedException q)
790 long startTime = System.currentTimeMillis();
793 return sendRestCommand(command);
797 * Make sure busy flag is reset come what may!
802 System.out.println("Chimera command took "
803 + (System.currentTimeMillis() - startTime) + "ms: "
811 * Sends the command to Chimera's REST API, and returns any response lines.
816 protected List<String> sendRestCommand(String command)
818 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
819 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
820 commands.add(new BasicNameValuePair("command", command));
822 List<String> reply = new ArrayList<String>();
823 BufferedReader response = null;
826 response = HttpClientUtils.doHttpUrlPost(restUrl, commands, CONNECTION_TIMEOUT_MS,
827 REST_REPLY_TIMEOUT_MS);
829 while ((line = response.readLine()) != null)
833 } catch (Exception e)
835 logger.error("REST call '" + command + "' failed: " + e.getMessage());
838 if (response != null)
843 } catch (IOException e)
852 * Send a command to stdin of Chimera process, and optionally read any
859 protected List<String> sendStdinCommand(String command, boolean readReply)
861 chimeraListenerThread.clearResponse(command);
862 String text = command.concat("\n");
866 chimera.getOutputStream().write(text.getBytes());
867 chimera.getOutputStream().flush();
868 } catch (IOException e)
870 // logger.info("Unable to execute command: " + text);
871 // logger.info("Exiting...");
872 logger.warn("Unable to execute command: " + text);
873 logger.warn("Exiting...");
874 clearOnChimeraExit();
881 List<String> rsp = chimeraListenerThread.getResponse(command);
885 public StructureManager getStructureManager()
887 return structureManager;
890 public boolean isBusy()