1 package ext.edu.ucsf.rbvi.strucviz2;
4 import java.io.BufferedReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.util.ArrayList;
10 import java.util.Collection;
11 import java.util.HashMap;
12 import java.util.List;
15 import org.apache.http.NameValuePair;
16 import org.apache.http.message.BasicNameValuePair;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
20 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
21 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
23 import jalview.ws.HttpClientUtils;
26 * This object maintains the Chimera communication information.
28 public class ChimeraManager
30 private static final boolean debug = false;
32 private int chimeraRestPort;
34 private Process chimera;
36 private ListenerThreads chimeraListenerThread;
38 private Map<Integer, ChimeraModel> currentModelsMap;
40 private Logger logger = LoggerFactory
41 .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
43 private StructureManager structureManager;
45 public ChimeraManager(StructureManager structureManager)
47 this.structureManager = structureManager;
49 chimeraListenerThread = null;
50 currentModelsMap = new HashMap<Integer, ChimeraModel>();
54 public List<ChimeraModel> getChimeraModels(String modelName)
56 List<ChimeraModel> models = getChimeraModels(modelName,
58 models.addAll(getChimeraModels(modelName, ModelType.SMILES));
62 public List<ChimeraModel> getChimeraModels(String modelName,
65 List<ChimeraModel> models = new ArrayList<ChimeraModel>();
66 for (ChimeraModel model : currentModelsMap.values())
68 if (modelName.equals(model.getModelName())
69 && modelType.equals(model.getModelType()))
77 public Map<String, List<ChimeraModel>> getChimeraModelsMap()
79 Map<String, List<ChimeraModel>> models = new HashMap<String, List<ChimeraModel>>();
80 for (ChimeraModel model : currentModelsMap.values())
82 String modelName = model.getModelName();
83 if (!models.containsKey(modelName))
85 models.put(modelName, new ArrayList<ChimeraModel>());
87 if (!models.get(modelName).contains(model))
89 models.get(modelName).add(model);
95 public ChimeraModel getChimeraModel(Integer modelNumber,
96 Integer subModelNumber)
98 Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
99 if (currentModelsMap.containsKey(key))
101 return currentModelsMap.get(key);
106 public ChimeraModel getChimeraModel()
108 return currentModelsMap.values().iterator().next();
111 public Collection<ChimeraModel> getChimeraModels()
113 // this method is invoked by the model navigator dialog
114 return currentModelsMap.values();
117 public int getChimeraModelsCount(boolean smiles)
119 // this method is invokes by the model navigator dialog
120 int counter = currentModelsMap.size();
126 for (ChimeraModel model : currentModelsMap.values())
128 if (model.getModelType() == ModelType.SMILES)
136 public boolean hasChimeraModel(Integer modelNubmer)
138 return hasChimeraModel(modelNubmer, 0);
141 public boolean hasChimeraModel(Integer modelNubmer, Integer subModelNumber)
143 return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
147 public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
150 currentModelsMap.put(
151 ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
154 public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
156 int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
157 if (currentModelsMap.containsKey(modelKey))
159 currentModelsMap.remove(modelKey);
163 public List<ChimeraModel> openModel(String modelPath, ModelType type)
165 return openModel(modelPath, getFileNameFromPath(modelPath), type);
169 * Overloaded method to allow Jalview to pass in a model name.
176 public List<ChimeraModel> openModel(String modelPath, String modelName,
179 logger.info("chimera open " + modelPath);
181 List<String> response = null;
182 // TODO: [Optional] Handle modbase models
183 if (type == ModelType.MODBASE_MODEL)
185 response = sendChimeraCommand("open modbase:" + modelPath, true);
186 // } else if (type == ModelType.SMILES) {
187 // response = sendChimeraCommand("open smiles:" + modelName, true);
188 // modelName = "smiles:" + modelName;
192 response = sendChimeraCommand("open " + modelPath, true);
194 if (response == null)
196 // something went wrong
197 logger.warn("Could not open " + modelPath);
200 List<ChimeraModel> models = new ArrayList<ChimeraModel>();
201 int[] modelNumbers = null;
202 if (type == ModelType.PDB_MODEL)
204 for (String line : response)
206 if (line.startsWith("#"))
208 modelNumbers = ChimUtils.parseOpenedModelNumber(line);
209 if (modelNumbers != null)
211 int modelNumber = ChimUtils.makeModelKey(modelNumbers[0],
213 if (currentModelsMap.containsKey(modelNumber))
217 ChimeraModel newModel = new ChimeraModel(modelName, type,
218 modelNumbers[0], modelNumbers[1]);
219 currentModelsMap.put(modelNumber, newModel);
220 models.add(newModel);
223 // patch for Jalview - set model name in Chimera
224 // TODO: find a variant that works for sub-models
225 sendChimeraCommand("setattr M name " + modelName + " #"
226 + modelNumbers[0], false);
227 // end patch for Jalview
236 // TODO: [Optional] Open smiles from file would fail. Do we need it?
237 // If parsing fails, iterate over all open models to get the right one
238 List<ChimeraModel> openModels = getModelList();
239 for (ChimeraModel openModel : openModels)
241 String openModelName = openModel.getModelName();
242 if (openModelName.endsWith("..."))
244 openModelName = openModelName.substring(0,
245 openModelName.length() - 3);
247 if (modelPath.startsWith(openModelName))
249 openModel.setModelName(modelPath);
250 int modelNumber = ChimUtils
251 .makeModelKey(openModel.getModelNumber(),
252 openModel.getSubModelNumber());
253 if (!currentModelsMap.containsKey(modelNumber))
255 currentModelsMap.put(modelNumber, openModel);
256 models.add(openModel);
262 // assign color and residues to open models
263 for (ChimeraModel newModel : models)
266 Color modelColor = getModelColor(newModel);
267 if (modelColor != null)
269 newModel.setModelColor(modelColor);
272 // Get our properties (default color scheme, etc.)
273 // Make the molecule look decent
274 // chimeraSend("repr stick "+newModel.toSpec());
276 // Create the information we need for the navigator
277 if (type != ModelType.SMILES)
279 addResidues(newModel);
283 sendChimeraCommand("focus", false);
284 // startListening(); // see ChimeraListener
289 * Refactored method to extract the last (or only) element delimited by file
295 private String getFileNameFromPath(String modelPath)
297 String modelName = modelPath;
298 if (modelPath == null)
302 // TODO: [Optional] Convert path to name in a better way
303 if (modelPath.lastIndexOf(File.separator) > 0)
305 modelName = modelPath.substring(modelPath
306 .lastIndexOf(File.separator) + 1);
308 else if (modelPath.lastIndexOf("/") > 0)
310 modelName = modelPath
311 .substring(modelPath.lastIndexOf("/") + 1);
316 public void closeModel(ChimeraModel model)
318 // int model = structure.modelNumber();
319 // int subModel = structure.subModelNumber();
320 // Integer modelKey = makeModelKey(model, subModel);
322 logger.info("chimera close model " + model.getModelName());
323 if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
324 model.getModelNumber(), model.getSubModelNumber())))
326 sendChimeraCommand("close " + model.toSpec(), false);
327 // currentModelNamesMap.remove(model.getModelName());
328 currentModelsMap.remove(ChimUtils.makeModelKey(
329 model.getModelNumber(), model.getSubModelNumber()));
330 // selectionList.remove(chimeraModel);
334 logger.warn("Could not find model " + model.getModelName()
340 public void startListening()
342 sendChimeraCommand("listen start models; listen start selection", false);
345 public void stopListening()
347 sendChimeraCommand("listen stop models ; listen stop selection ", false);
351 * Tell Chimera we are listening on the given URI
355 public void startListening(String uri)
357 sendChimeraCommand("listen start models url " + uri
358 + ";listen start select prefix SelectionChanged url " + uri, false);
362 * Select something in Chimera
365 * the selection command to pass to Chimera
367 public void select(String command)
369 sendChimeraCommand("listen stop selection; " + command
370 + "; listen start selection", false);
375 sendChimeraCommand("focus", false);
378 public void clearOnChimeraExit()
381 currentModelsMap.clear();
382 this.chimeraRestPort = 0;
383 structureManager.clearOnChimeraExit();
386 public void exitChimera()
388 if (isChimeraLaunched() && chimera != null)
390 sendChimeraCommand("stop really", false);
394 } catch (Exception ex)
399 clearOnChimeraExit();
402 public Map<Integer, ChimeraModel> getSelectedModels()
404 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
405 List<String> chimeraReply = sendChimeraCommand(
406 "list selection level molecule", true);
407 if (chimeraReply != null)
409 for (String modelLine : chimeraReply)
411 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
412 Integer modelKey = ChimUtils.makeModelKey(
413 chimeraModel.getModelNumber(),
414 chimeraModel.getSubModelNumber());
415 selectedModelsMap.put(modelKey, chimeraModel);
418 return selectedModelsMap;
422 * Sends a 'list selection level residue' command to Chimera and returns the
423 * list of selected atomspecs
427 public List<String> getSelectedResidueSpecs()
429 List<String> selectedResidues = new ArrayList<String>();
430 List<String> chimeraReply = sendChimeraCommand(
431 "list selection level residue", true);
432 if (chimeraReply != null)
434 for (String inputLine : chimeraReply)
436 String[] inputLineParts = inputLine.split("\\s+");
437 if (inputLineParts.length == 5)
439 selectedResidues.add(inputLineParts[2]);
443 return selectedResidues;
446 public void getSelectedResidues(
447 Map<Integer, ChimeraModel> selectedModelsMap)
449 List<String> chimeraReply = sendChimeraCommand(
450 "list selection level residue", true);
451 if (chimeraReply != null)
453 for (String inputLine : chimeraReply)
455 ChimeraResidue r = new ChimeraResidue(inputLine);
456 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
457 r.getSubModelNumber());
458 if (selectedModelsMap.containsKey(modelKey))
460 ChimeraModel model = selectedModelsMap.get(modelKey);
468 * Return the list of ChimeraModels currently open. Warning: if smiles model
469 * name too long, only part of it with "..." is printed.
472 * @return List of ChimeraModel's
474 // TODO: [Optional] Handle smiles names in a better way in Chimera?
475 public List<ChimeraModel> getModelList()
477 List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
478 List<String> list = sendChimeraCommand("list models type molecule",
482 for (String modelLine : list)
484 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
485 modelList.add(chimeraModel);
492 * Return the list of depiction presets available from within Chimera. Chimera
493 * will return the list as a series of lines with the format: Preset type
494 * number "description"
496 * @return list of presets
498 public List<String> getPresets()
500 ArrayList<String> presetList = new ArrayList<String>();
501 List<String> output = sendChimeraCommand("preset list", true);
504 for (String preset : output)
506 preset = preset.substring(7); // Skip over the "Preset"
507 preset = preset.replaceFirst("\"", "(");
508 preset = preset.replaceFirst("\"", ")");
509 // string now looks like: type number (description)
510 presetList.add(preset);
516 public boolean isChimeraLaunched()
518 boolean launched = false;
524 // if we get here, process has ended
525 } catch (IllegalThreadStateException e)
527 // ok - not yet terminated
535 * Launch Chimera, unless an instance linked to this object is already
536 * running. Returns true if chimera is successfully launched, or already
537 * running, else false.
539 * @param chimeraPaths
542 public boolean launchChimera(List<String> chimeraPaths)
544 // Do nothing if Chimera is already launched
545 if (isChimeraLaunched())
550 // Try to launch Chimera (eventually using one of the possible paths)
551 String error = "Error message: ";
552 String workingPath = "";
553 // iterate over possible paths for starting Chimera
554 for (String chimeraPath : chimeraPaths)
556 File path = new File(chimeraPath);
557 // enable the next line to simulate Chimera not installed
558 // File path = new File(chimeraPath + "x");
559 if (!path.canExecute())
561 error += "File '" + path + "' does not exist.\n";
566 List<String> args = new ArrayList<String>();
567 args.add(chimeraPath);
569 args.add("RESTServer");
570 ProcessBuilder pb = new ProcessBuilder(args);
571 chimera = pb.start();
573 workingPath = chimeraPath;
575 } catch (Exception e)
577 // Chimera could not be started
578 error += e.getMessage();
581 // If no error, then Chimera was launched successfully
582 if (error.length() == 0)
584 this.chimeraRestPort = getPortNumber();
585 System.out.println("Chimera REST API started on port "
587 // structureManager.initChimTable();
588 structureManager.setChimeraPathProperty(workingPath);
589 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
590 // Ask Chimera to give us updates
591 // startListening(); // later - see ChimeraListener
595 // Tell the user that Chimera could not be started because of an error
601 * Read and return the port number returned in the reply to --start RESTServer
603 private int getPortNumber()
606 InputStream readChan = chimera.getInputStream();
607 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
609 String response = null;
612 // expect: REST server on host 127.0.0.1 port port_number
613 response = lineReader.readLine();
614 String [] tokens = response.split(" ");
615 if (tokens.length == 7 && "port".equals(tokens[5])) {
616 port = Integer.parseInt(tokens[6]);
617 logger.info("Chimera REST service listening on port "
620 } catch (Exception e)
622 logger.error("Failed to get REST port number from " + response + ": "
629 } catch (IOException e2)
637 * Determine the color that Chimera is using for this model.
640 * the ChimeraModel we want to get the Color for
641 * @return the default model Color for this model in Chimera
643 public Color getModelColor(ChimeraModel model)
645 List<String> colorLines = sendChimeraCommand(
646 "list model spec " + model.toSpec() + " attribute color", true);
647 if (colorLines == null || colorLines.size() == 0)
651 return ChimUtils.parseModelColor(colorLines.get(0));
656 * Get information about the residues associated with a model. This uses the
657 * Chimera listr command. We don't return the resulting residues, but we add
658 * the residues to the model.
661 * the ChimeraModel to get residue information for
664 public void addResidues(ChimeraModel model)
666 int modelNumber = model.getModelNumber();
667 int subModelNumber = model.getSubModelNumber();
668 // Get the list -- it will be in the reply log
669 List<String> reply = sendChimeraCommand(
670 "list residues spec " + model.toSpec(), true);
675 for (String inputLine : reply)
677 ChimeraResidue r = new ChimeraResidue(inputLine);
678 if (r.getModelNumber() == modelNumber
679 || r.getSubModelNumber() == subModelNumber)
686 public List<String> getAttrList()
688 List<String> attributes = new ArrayList<String>();
689 final List<String> reply = sendChimeraCommand("list resattr", true);
692 for (String inputLine : reply)
694 String[] lineParts = inputLine.split("\\s");
695 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
697 attributes.add(lineParts[1]);
704 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
707 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
708 final List<String> reply = sendChimeraCommand("list residue spec "
709 + model.toSpec() + " attribute " + aCommand, true);
712 for (String inputLine : reply)
714 String[] lineParts = inputLine.split("\\s");
715 if (lineParts.length == 5)
717 ChimeraResidue residue = ChimUtils
718 .getResidue(lineParts[2], model);
719 String value = lineParts[4];
722 if (value.equals("None"))
726 if (value.equals("True") || value.equals("False"))
728 values.put(residue, Boolean.valueOf(value));
733 Double doubleValue = Double.valueOf(value);
734 values.put(residue, doubleValue);
735 } catch (NumberFormatException ex)
737 values.put(residue, value);
746 private volatile boolean busy = false;
749 * Send a command to Chimera.
752 * Command string to be send.
754 * Flag indicating whether the method should return the reply from
756 * @return List of Strings corresponding to the lines in the Chimera reply or
759 public List<String> sendChimeraCommand(String command, boolean reply)
761 // System.out.println("chimeradebug>> " + command);
762 if (!isChimeraLaunched() || command == null
763 || "".equals(command.trim()))
767 // TODO do we need a maximum wait time before aborting?
773 } catch (InterruptedException q)
778 long startTime = System.currentTimeMillis();
781 return sendRestCommand(command);
785 * Make sure busy flag is reset come what may!
790 System.out.println("Chimera command took "
791 + (System.currentTimeMillis() - startTime) + "ms: "
799 * Sends the command to Chimera's REST API, and returns any response lines.
804 protected List<String> sendRestCommand(String command)
806 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
807 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
808 commands.add(new BasicNameValuePair("command", command));
810 List<String> reply = new ArrayList<String>();
811 BufferedReader response = null;
813 response = HttpClientUtils
814 .doHttpUrlPost(restUrl, commands, 100, 5000);
816 while ((line = response.readLine()) != null) {
819 } catch (Exception e)
821 logger.error("REST call " + command + " failed: " + e.getMessage());
824 if (response != null)
829 } catch (IOException e)
838 * Send a command to stdin of Chimera process, and optionally read any
845 protected List<String> sendStdinCommand(String command, boolean readReply)
847 chimeraListenerThread.clearResponse(command);
848 String text = command.concat("\n");
852 chimera.getOutputStream().write(text.getBytes());
853 chimera.getOutputStream().flush();
854 } catch (IOException e)
856 // logger.info("Unable to execute command: " + text);
857 // logger.info("Exiting...");
858 logger.warn("Unable to execute command: " + text);
859 logger.warn("Exiting...");
860 clearOnChimeraExit();
867 List<String> rsp = chimeraListenerThread.getResponse(command);
871 public StructureManager getStructureManager()
873 return structureManager;
876 public boolean isBusy()