1 package ext.edu.ucsf.rbvi.strucviz2;
3 import jalview.ws.HttpClientUtils;
6 import java.io.BufferedReader;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.HashMap;
14 import java.util.List;
17 import org.apache.http.NameValuePair;
18 import org.apache.http.message.BasicNameValuePair;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
23 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
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 // uncomment the next line to simulate Chimera not installed
558 // 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);
568 // shows Chimera output window but suppresses REST responses:
569 // args.add("--debug");
571 args.add("RESTServer");
572 ProcessBuilder pb = new ProcessBuilder(args);
573 chimera = pb.start();
575 workingPath = chimeraPath;
577 } catch (Exception e)
579 // Chimera could not be started
580 error += e.getMessage();
583 // If no error, then Chimera was launched successfully
584 if (error.length() == 0)
586 this.chimeraRestPort = getPortNumber();
587 System.out.println("Chimera REST API started on port "
589 // structureManager.initChimTable();
590 structureManager.setChimeraPathProperty(workingPath);
591 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
592 // Ask Chimera to give us updates
593 // startListening(); // later - see ChimeraListener
594 return (chimeraRestPort > 0);
597 // Tell the user that Chimera could not be started because of an error
603 * Read and return the port number returned in the reply to --start RESTServer
605 private int getPortNumber()
608 InputStream readChan = chimera.getInputStream();
609 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
611 StringBuilder responses = new StringBuilder();
614 String response = lineReader.readLine();
615 while (response != null)
617 responses.append("\n" + response);
618 // expect: REST server on host 127.0.0.1 port port_number
619 if (response.startsWith("REST server"))
621 String[] tokens = response.split(" ");
622 if (tokens.length == 7 && "port".equals(tokens[5]))
624 port = Integer.parseInt(tokens[6]);
628 response = lineReader.readLine();
630 } catch (Exception e)
632 logger.error("Failed to get REST port number from " + responses
640 } catch (IOException e2)
647 .println("Failed to start Chimera with REST service, response was: "
650 logger.info("Chimera REST service listening on port " + chimeraRestPort);
655 * Determine the color that Chimera is using for this model.
658 * the ChimeraModel we want to get the Color for
659 * @return the default model Color for this model in Chimera
661 public Color getModelColor(ChimeraModel model)
663 List<String> colorLines = sendChimeraCommand(
664 "list model spec " + model.toSpec() + " attribute color", true);
665 if (colorLines == null || colorLines.size() == 0)
669 return ChimUtils.parseModelColor(colorLines.get(0));
674 * Get information about the residues associated with a model. This uses the
675 * Chimera listr command. We don't return the resulting residues, but we add
676 * the residues to the model.
679 * the ChimeraModel to get residue information for
682 public void addResidues(ChimeraModel model)
684 int modelNumber = model.getModelNumber();
685 int subModelNumber = model.getSubModelNumber();
686 // Get the list -- it will be in the reply log
687 List<String> reply = sendChimeraCommand(
688 "list residues spec " + model.toSpec(), true);
693 for (String inputLine : reply)
695 ChimeraResidue r = new ChimeraResidue(inputLine);
696 if (r.getModelNumber() == modelNumber
697 || r.getSubModelNumber() == subModelNumber)
704 public List<String> getAttrList()
706 List<String> attributes = new ArrayList<String>();
707 final List<String> reply = sendChimeraCommand("list resattr", true);
710 for (String inputLine : reply)
712 String[] lineParts = inputLine.split("\\s");
713 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
715 attributes.add(lineParts[1]);
722 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
725 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
726 final List<String> reply = sendChimeraCommand("list residue spec "
727 + model.toSpec() + " attribute " + aCommand, true);
730 for (String inputLine : reply)
732 String[] lineParts = inputLine.split("\\s");
733 if (lineParts.length == 5)
735 ChimeraResidue residue = ChimUtils
736 .getResidue(lineParts[2], model);
737 String value = lineParts[4];
740 if (value.equals("None"))
744 if (value.equals("True") || value.equals("False"))
746 values.put(residue, Boolean.valueOf(value));
751 Double doubleValue = Double.valueOf(value);
752 values.put(residue, doubleValue);
753 } catch (NumberFormatException ex)
755 values.put(residue, value);
764 private volatile boolean busy = false;
767 * Send a command to Chimera.
770 * Command string to be send.
772 * Flag indicating whether the method should return the reply from
774 * @return List of Strings corresponding to the lines in the Chimera reply or
777 public List<String> sendChimeraCommand(String command, boolean reply)
779 // System.out.println("chimeradebug>> " + command);
780 if (!isChimeraLaunched() || command == null
781 || "".equals(command.trim()))
785 // TODO do we need a maximum wait time before aborting?
791 } catch (InterruptedException q)
796 long startTime = System.currentTimeMillis();
799 return sendRestCommand(command);
803 * Make sure busy flag is reset come what may!
808 System.out.println("Chimera command took "
809 + (System.currentTimeMillis() - startTime) + "ms: "
817 * Sends the command to Chimera's REST API, and returns any response lines.
822 protected List<String> sendRestCommand(String command)
824 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
825 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
826 commands.add(new BasicNameValuePair("command", command));
828 List<String> reply = new ArrayList<String>();
829 BufferedReader response = null;
831 response = HttpClientUtils
832 .doHttpUrlPost(restUrl, commands, 100, 5000);
834 while ((line = response.readLine()) != null) {
837 } catch (Exception e)
839 logger.error("REST call " + command + " failed: " + e.getMessage());
842 if (response != null)
847 } catch (IOException e)
856 * Send a command to stdin of Chimera process, and optionally read any
863 protected List<String> sendStdinCommand(String command, boolean readReply)
865 chimeraListenerThread.clearResponse(command);
866 String text = command.concat("\n");
870 chimera.getOutputStream().write(text.getBytes());
871 chimera.getOutputStream().flush();
872 } catch (IOException e)
874 // logger.info("Unable to execute command: " + text);
875 // logger.info("Exiting...");
876 logger.warn("Unable to execute command: " + text);
877 logger.warn("Exiting...");
878 clearOnChimeraExit();
885 List<String> rsp = chimeraListenerThread.getResponse(command);
889 public StructureManager getStructureManager()
891 return structureManager;
894 public boolean isBusy()