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 = true;
33 * true: use REST API (recommended), false: use stdout/stdin (deprecated)
35 private static final boolean USE_REST = true;
37 // Port number for Chimera REST service
40 private Process chimera;
42 private ListenerThreads chimeraListenerThread;
44 private Map<Integer, ChimeraModel> currentModelsMap;
46 private Logger logger = LoggerFactory
47 .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
49 private StructureManager structureManager;
51 public ChimeraManager(StructureManager structureManager)
53 this.structureManager = structureManager;
55 chimeraListenerThread = null;
56 currentModelsMap = new HashMap<Integer, ChimeraModel>();
60 public List<ChimeraModel> getChimeraModels(String modelName)
62 List<ChimeraModel> models = getChimeraModels(modelName,
64 models.addAll(getChimeraModels(modelName, ModelType.SMILES));
68 public List<ChimeraModel> getChimeraModels(String modelName,
71 List<ChimeraModel> models = new ArrayList<ChimeraModel>();
72 for (ChimeraModel model : currentModelsMap.values())
74 if (modelName.equals(model.getModelName())
75 && modelType.equals(model.getModelType()))
83 public Map<String, List<ChimeraModel>> getChimeraModelsMap()
85 Map<String, List<ChimeraModel>> models = new HashMap<String, List<ChimeraModel>>();
86 for (ChimeraModel model : currentModelsMap.values())
88 String modelName = model.getModelName();
89 if (!models.containsKey(modelName))
91 models.put(modelName, new ArrayList<ChimeraModel>());
93 if (!models.get(modelName).contains(model))
95 models.get(modelName).add(model);
101 public ChimeraModel getChimeraModel(Integer modelNumber,
102 Integer subModelNumber)
104 Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
105 if (currentModelsMap.containsKey(key))
107 return currentModelsMap.get(key);
112 public ChimeraModel getChimeraModel()
114 return currentModelsMap.values().iterator().next();
117 public Collection<ChimeraModel> getChimeraModels()
119 // this method is invoked by the model navigator dialog
120 return currentModelsMap.values();
123 public int getChimeraModelsCount(boolean smiles)
125 // this method is invokes by the model navigator dialog
126 int counter = currentModelsMap.size();
132 for (ChimeraModel model : currentModelsMap.values())
134 if (model.getModelType() == ModelType.SMILES)
142 public boolean hasChimeraModel(Integer modelNubmer)
144 return hasChimeraModel(modelNubmer, 0);
147 public boolean hasChimeraModel(Integer modelNubmer, Integer subModelNumber)
149 return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
153 public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
156 currentModelsMap.put(
157 ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
160 public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
162 int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
163 if (currentModelsMap.containsKey(modelKey))
165 currentModelsMap.remove(modelKey);
169 public List<ChimeraModel> openModel(String modelPath, ModelType type)
171 return openModel(modelPath, getFileNameFromPath(modelPath), type);
175 * Overloaded method to allow Jalview to pass in a model name.
182 public List<ChimeraModel> openModel(String modelPath, String modelName,
185 logger.info("chimera open " + modelPath);
187 List<String> response = null;
188 // TODO: [Optional] Handle modbase models
189 if (type == ModelType.MODBASE_MODEL)
191 response = sendChimeraCommand("open modbase:" + modelPath, true);
192 // } else if (type == ModelType.SMILES) {
193 // response = sendChimeraCommand("open smiles:" + modelName, true);
194 // modelName = "smiles:" + modelName;
198 response = sendChimeraCommand("open " + modelPath, true);
200 if (response == null)
202 // something went wrong
203 logger.warn("Could not open " + modelPath);
206 List<ChimeraModel> models = new ArrayList<ChimeraModel>();
207 int[] modelNumbers = null;
208 if (type == ModelType.PDB_MODEL)
210 for (String line : response)
212 if (line.startsWith("#"))
214 modelNumbers = ChimUtils.parseOpenedModelNumber(line);
215 if (modelNumbers != null)
217 int modelNumber = ChimUtils.makeModelKey(modelNumbers[0],
219 if (currentModelsMap.containsKey(modelNumber))
223 ChimeraModel newModel = new ChimeraModel(modelName, type,
224 modelNumbers[0], modelNumbers[1]);
225 currentModelsMap.put(modelNumber, newModel);
226 models.add(newModel);
227 // patch for Jalview - set model name in Chimera
228 sendChimeraCommand("setattr M name " + modelName + " #"
229 + modelNumbers[0], false);
230 // end patch for Jalview
238 // TODO: [Optional] Open smiles from file would fail. Do we need it?
239 // If parsing fails, iterate over all open models to get the right one
240 List<ChimeraModel> openModels = getModelList();
241 for (ChimeraModel openModel : openModels)
243 String openModelName = openModel.getModelName();
244 if (openModelName.endsWith("..."))
246 openModelName = openModelName.substring(0,
247 openModelName.length() - 3);
249 if (modelPath.startsWith(openModelName))
251 openModel.setModelName(modelPath);
252 int modelNumber = ChimUtils
253 .makeModelKey(openModel.getModelNumber(),
254 openModel.getSubModelNumber());
255 if (!currentModelsMap.containsKey(modelNumber))
257 currentModelsMap.put(modelNumber, openModel);
258 models.add(openModel);
264 // assign color and residues to open models
265 for (ChimeraModel newModel : models)
268 Color modelColor = getModelColor(newModel);
269 if (modelColor != null)
271 newModel.setModelColor(modelColor);
274 // Get our properties (default color scheme, etc.)
275 // Make the molecule look decent
276 // chimeraSend("repr stick "+newModel.toSpec());
278 // Create the information we need for the navigator
279 if (type != ModelType.SMILES)
281 addResidues(newModel);
285 sendChimeraCommand("focus", false);
291 * Refactored method to extract the last (or only) element delimited by file
297 private String getFileNameFromPath(String modelPath)
299 String modelName = modelPath;
300 if (modelPath == null)
304 // TODO: [Optional] Convert path to name in a better way
305 if (modelPath.lastIndexOf(File.separator) > 0)
307 modelName = modelPath.substring(modelPath
308 .lastIndexOf(File.separator) + 1);
310 else if (modelPath.lastIndexOf("/") > 0)
312 modelName = modelPath
313 .substring(modelPath.lastIndexOf("/") + 1);
318 public void closeModel(ChimeraModel model)
320 // int model = structure.modelNumber();
321 // int subModel = structure.subModelNumber();
322 // Integer modelKey = makeModelKey(model, subModel);
324 logger.info("chimera close model " + model.getModelName());
325 if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
326 model.getModelNumber(), model.getSubModelNumber())))
328 sendChimeraCommand("close " + model.toSpec(), false);
329 // currentModelNamesMap.remove(model.getModelName());
330 currentModelsMap.remove(ChimUtils.makeModelKey(
331 model.getModelNumber(), model.getSubModelNumber()));
332 // selectionList.remove(chimeraModel);
336 logger.warn("Could not find model " + model.getModelName()
342 public void startListening()
344 sendChimeraCommand("listen start models; listen start select", false);
347 public void stopListening()
349 sendChimeraCommand("listen stop models; listen stop select", false);
353 * Select something in Chimera
356 * the selection command to pass to Chimera
358 public void select(String command)
360 sendChimeraCommand("listen stop select; " + command
361 + "; listen start select", false);
366 sendChimeraCommand("focus", false);
369 public void clearOnChimeraExit()
372 currentModelsMap.clear();
375 chimeraListenerThread.requestStop();
376 chimeraListenerThread = null;
378 structureManager.clearOnChimeraExit();
381 public void exitChimera()
383 if (isChimeraLaunched() && chimera != null)
385 sendChimeraCommand("stop really", false);
389 } catch (Exception ex)
394 clearOnChimeraExit();
397 public Map<Integer, ChimeraModel> getSelectedModels()
399 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
400 List<String> chimeraReply = sendChimeraCommand(
401 "list selection level molecule", true);
402 if (chimeraReply != null)
404 for (String modelLine : chimeraReply)
406 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
407 Integer modelKey = ChimUtils.makeModelKey(
408 chimeraModel.getModelNumber(),
409 chimeraModel.getSubModelNumber());
410 selectedModelsMap.put(modelKey, chimeraModel);
413 return selectedModelsMap;
416 public List<String> getSelectedResidueSpecs()
418 List<String> selectedResidues = new ArrayList<String>();
419 List<String> chimeraReply = sendChimeraCommand(
420 "list selection level residue", true);
421 if (chimeraReply != null)
423 for (String inputLine : chimeraReply)
425 String[] inputLineParts = inputLine.split("\\s+");
426 if (inputLineParts.length == 5)
428 selectedResidues.add(inputLineParts[2]);
432 return selectedResidues;
435 public void getSelectedResidues(
436 Map<Integer, ChimeraModel> selectedModelsMap)
438 List<String> chimeraReply = sendChimeraCommand(
439 "list selection level residue", true);
440 if (chimeraReply != null)
442 for (String inputLine : chimeraReply)
444 ChimeraResidue r = new ChimeraResidue(inputLine);
445 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
446 r.getSubModelNumber());
447 if (selectedModelsMap.containsKey(modelKey))
449 ChimeraModel model = selectedModelsMap.get(modelKey);
457 * Return the list of ChimeraModels currently open. Warning: if smiles model
458 * name too long, only part of it with "..." is printed.
461 * @return List of ChimeraModel's
463 // TODO: [Optional] Handle smiles names in a better way in Chimera?
464 public List<ChimeraModel> getModelList()
466 List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
467 List<String> list = sendChimeraCommand("list models type molecule",
471 for (String modelLine : list)
473 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
474 modelList.add(chimeraModel);
481 * Return the list of depiction presets available from within Chimera. Chimera
482 * will return the list as a series of lines with the format: Preset type
483 * number "description"
485 * @return list of presets
487 public List<String> getPresets()
489 ArrayList<String> presetList = new ArrayList<String>();
490 List<String> output = sendChimeraCommand("preset list", true);
493 for (String preset : output)
495 preset = preset.substring(7); // Skip over the "Preset"
496 preset = preset.replaceFirst("\"", "(");
497 preset = preset.replaceFirst("\"", ")");
498 // string now looks like: type number (description)
499 presetList.add(preset);
505 public boolean isChimeraLaunched()
507 boolean launched = false;
513 // if we get here, process has ended
514 } catch (IllegalThreadStateException e)
516 // ok - not yet terminated
523 public boolean launchChimera(List<String> chimeraPaths)
525 // Do nothing if Chimera is already launched
526 if (isChimeraLaunched())
531 // Try to launch Chimera (eventually using one of the possible paths)
532 String error = "Error message: ";
533 String workingPath = "";
534 // iterate over possible paths for starting Chimera
535 for (String chimeraPath : chimeraPaths)
537 File path = new File(chimeraPath);
538 if (!path.canExecute())
540 error += "File '" + path + "' does not exist.\n";
545 List<String> args = new ArrayList<String>();
546 args.add(chimeraPath);
548 args.add(USE_REST ? "RESTServer" : "ReadStdin");
549 ProcessBuilder pb = new ProcessBuilder(args);
550 chimera = pb.start();
552 workingPath = chimeraPath;
553 logger.info("Starting " + chimeraPath + " with "
554 + (USE_REST ? "REST API" : "stdin/stdout"));
556 } catch (Exception e)
558 // Chimera could not be started
559 error += e.getMessage();
562 // If no error, then Chimera was launched successfully
563 if (error.length() == 0)
567 this.restPort = getPortNumber();
571 // Initialize the listener threads
572 chimeraListenerThread = new ListenerThreads(chimera,
574 chimeraListenerThread.start();
576 // structureManager.initChimTable();
577 structureManager.setChimeraPathProperty(workingPath);
578 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
579 // Ask Chimera to give us updates
584 // Tell the user that Chimera could not be started because of an error
590 * Read and return the port number returned in the reply to --start RESTServer
592 private int getPortNumber()
595 InputStream readChan = chimera.getInputStream();
596 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
598 String response = null;
601 // expect: REST server on host 127.0.0.1 port port_number
602 response = lineReader.readLine();
603 String [] tokens = response.split(" ");
604 if (tokens.length == 7 && "port".equals(tokens[5])) {
605 port = Integer.parseInt(tokens[6]);
606 logger.info("Chimera REST service listening on port " + restPort);
608 } catch (Exception e)
610 logger.error("Failed to get REST port number from " + response + ": "
617 } catch (IOException e2)
625 * Determine the color that Chimera is using for this model.
628 * the ChimeraModel we want to get the Color for
629 * @return the default model Color for this model in Chimera
631 public Color getModelColor(ChimeraModel model)
633 List<String> colorLines = sendChimeraCommand(
634 "list model spec " + model.toSpec() + " attribute color", true);
635 if (colorLines == null || colorLines.size() == 0)
639 return ChimUtils.parseModelColor(colorLines.get(0));
644 * Get information about the residues associated with a model. This uses the
645 * Chimera listr command. We don't return the resulting residues, but we add
646 * the residues to the model.
649 * the ChimeraModel to get residue information for
652 public void addResidues(ChimeraModel model)
654 int modelNumber = model.getModelNumber();
655 int subModelNumber = model.getSubModelNumber();
656 // Get the list -- it will be in the reply log
657 List<String> reply = sendChimeraCommand(
658 "list residues spec " + model.toSpec(), true);
663 for (String inputLine : reply)
665 ChimeraResidue r = new ChimeraResidue(inputLine);
666 if (r.getModelNumber() == modelNumber
667 || r.getSubModelNumber() == subModelNumber)
674 public List<String> getAttrList()
676 List<String> attributes = new ArrayList<String>();
677 final List<String> reply = sendChimeraCommand("list resattr", true);
680 for (String inputLine : reply)
682 String[] lineParts = inputLine.split("\\s");
683 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
685 attributes.add(lineParts[1]);
692 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
695 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
696 final List<String> reply = sendChimeraCommand("list residue spec "
697 + model.toSpec() + " attribute " + aCommand, true);
700 for (String inputLine : reply)
702 String[] lineParts = inputLine.split("\\s");
703 if (lineParts.length == 5)
705 ChimeraResidue residue = ChimUtils
706 .getResidue(lineParts[2], model);
707 String value = lineParts[4];
710 if (value.equals("None"))
714 if (value.equals("True") || value.equals("False"))
716 values.put(residue, Boolean.valueOf(value));
721 Double doubleValue = Double.valueOf(value);
722 values.put(residue, doubleValue);
723 } catch (NumberFormatException ex)
725 values.put(residue, value);
734 private volatile boolean busy = false;
737 * Send a command to Chimera.
740 * Command string to be send.
742 * Flag indicating whether the method should return the reply from
744 * @return List of Strings corresponding to the lines in the Chimera reply or
747 public List<String> sendChimeraCommand(String command, boolean reply)
749 if (!isChimeraLaunched())
753 // TODO do we need a maximum wait time before aborting?
759 } catch (InterruptedException q)
765 long startTime = System.currentTimeMillis();
770 return sendRestCommand(command);
774 return sendStdinCommand(command, reply);
781 System.out.println("Chimera command took "
782 + (System.currentTimeMillis() - startTime) + "ms: "
790 * Sends the command to Chimera's REST API, and returns any response lines.
795 protected List<String> sendRestCommand(String command)
797 // TODO start a separate thread to do this so we don't block?
798 String restUrl = "http://127.0.0.1:" + this.restPort + "/run";
799 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
800 commands.add(new BasicNameValuePair("command", command));
802 List<String> reply = new ArrayList<String>();
803 BufferedReader response = null;
805 response = HttpClientUtils.doHttpUrlPost(restUrl,
808 while ((line = response.readLine()) != null) {
811 } catch (Exception e)
813 logger.error("REST call " + command + " failed: " + e.getMessage());
816 if (response != null)
821 } catch (IOException e)
830 * Send a command to stdin of Chimera process, and optionally read any
837 protected List<String> sendStdinCommand(String command, boolean readReply)
839 chimeraListenerThread.clearResponse(command);
840 String text = command.concat("\n");
844 chimera.getOutputStream().write(text.getBytes());
845 chimera.getOutputStream().flush();
846 } catch (IOException e)
848 // logger.info("Unable to execute command: " + text);
849 // logger.info("Exiting...");
850 logger.warn("Unable to execute command: " + text);
851 logger.warn("Exiting...");
852 clearOnChimeraExit();
859 List<String> rsp = chimeraListenerThread.getResponse(command);
863 public StructureManager getStructureManager()
865 return structureManager;
868 public boolean isBusy()