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 int REST_REPLY_TIMEOUT_MS = 15000;
32 private static final int CONNECTION_TIMEOUT_MS = 100;
34 private static final boolean debug = false;
36 private int chimeraRestPort;
38 private Process chimera;
40 private ListenerThreads chimeraListenerThread;
42 private Map<Integer, ChimeraModel> currentModelsMap;
44 private Logger logger = LoggerFactory
45 .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
47 private StructureManager structureManager;
49 public ChimeraManager(StructureManager structureManager)
51 this.structureManager = structureManager;
53 chimeraListenerThread = null;
54 currentModelsMap = new HashMap<Integer, ChimeraModel>();
58 public List<ChimeraModel> getChimeraModels(String modelName)
60 List<ChimeraModel> models = getChimeraModels(modelName,
62 models.addAll(getChimeraModels(modelName, ModelType.SMILES));
66 public List<ChimeraModel> getChimeraModels(String modelName,
69 List<ChimeraModel> models = new ArrayList<ChimeraModel>();
70 for (ChimeraModel model : currentModelsMap.values())
72 if (modelName.equals(model.getModelName())
73 && modelType.equals(model.getModelType()))
81 public Map<String, List<ChimeraModel>> getChimeraModelsMap()
83 Map<String, List<ChimeraModel>> models = new HashMap<String, List<ChimeraModel>>();
84 for (ChimeraModel model : currentModelsMap.values())
86 String modelName = model.getModelName();
87 if (!models.containsKey(modelName))
89 models.put(modelName, new ArrayList<ChimeraModel>());
91 if (!models.get(modelName).contains(model))
93 models.get(modelName).add(model);
99 public ChimeraModel getChimeraModel(Integer modelNumber,
100 Integer subModelNumber)
102 Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
103 if (currentModelsMap.containsKey(key))
105 return currentModelsMap.get(key);
110 public ChimeraModel getChimeraModel()
112 return currentModelsMap.values().iterator().next();
115 public Collection<ChimeraModel> getChimeraModels()
117 // this method is invoked by the model navigator dialog
118 return currentModelsMap.values();
121 public int getChimeraModelsCount(boolean smiles)
123 // this method is invokes by the model navigator dialog
124 int counter = currentModelsMap.size();
130 for (ChimeraModel model : currentModelsMap.values())
132 if (model.getModelType() == ModelType.SMILES)
140 public boolean hasChimeraModel(Integer modelNubmer)
142 return hasChimeraModel(modelNubmer, 0);
145 public boolean hasChimeraModel(Integer modelNubmer, Integer subModelNumber)
147 return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
151 public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
154 currentModelsMap.put(
155 ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
158 public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
160 int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
161 if (currentModelsMap.containsKey(modelKey))
163 currentModelsMap.remove(modelKey);
167 public List<ChimeraModel> openModel(String modelPath, ModelType type)
169 return openModel(modelPath, getFileNameFromPath(modelPath), type);
173 * Overloaded method to allow Jalview to pass in a model name.
180 public List<ChimeraModel> openModel(String modelPath, String modelName,
183 logger.info("chimera open " + modelPath);
185 List<ChimeraModel> modelList = getModelList();
186 List<String> response = null;
187 // TODO: [Optional] Handle modbase models
188 if (type == ModelType.MODBASE_MODEL)
190 response = sendChimeraCommand("open modbase:" + modelPath, true);
191 // } else if (type == ModelType.SMILES) {
192 // response = sendChimeraCommand("open smiles:" + modelName, true);
193 // modelName = "smiles:" + modelName;
197 response = sendChimeraCommand("open " + modelPath, true);
199 if (response == null)
201 // something went wrong
202 logger.warn("Could not open " + modelPath);
206 // patch for Jalview - set model name in Chimera
207 // TODO: find a variant that works for sub-models
208 for (ChimeraModel newModel : getModelList())
210 if (!modelList.contains(newModel))
212 newModel.setModelName(modelName);
214 "setattr M name " + modelName + " #"
215 + newModel.getModelNumber(), false);
216 modelList.add(newModel);
220 // assign color and residues to open models
221 for (ChimeraModel chimeraModel : modelList)
224 Color modelColor = getModelColor(chimeraModel);
225 if (modelColor != null)
227 chimeraModel.setModelColor(modelColor);
230 // Get our properties (default color scheme, etc.)
231 // Make the molecule look decent
232 // chimeraSend("repr stick "+newModel.toSpec());
234 // Create the information we need for the navigator
235 if (type != ModelType.SMILES)
237 addResidues(chimeraModel);
241 sendChimeraCommand("focus", false);
242 // startListening(); // see ChimeraListener
247 * Refactored method to extract the last (or only) element delimited by file
253 private String getFileNameFromPath(String modelPath)
255 String modelName = modelPath;
256 if (modelPath == null)
260 // TODO: [Optional] Convert path to name in a better way
261 if (modelPath.lastIndexOf(File.separator) > 0)
263 modelName = modelPath
264 .substring(modelPath.lastIndexOf(File.separator) + 1);
266 else if (modelPath.lastIndexOf("/") > 0)
268 modelName = modelPath.substring(modelPath.lastIndexOf("/") + 1);
273 public void closeModel(ChimeraModel model)
275 // int model = structure.modelNumber();
276 // int subModel = structure.subModelNumber();
277 // Integer modelKey = makeModelKey(model, subModel);
279 logger.info("chimera close model " + model.getModelName());
280 if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
281 model.getModelNumber(), model.getSubModelNumber())))
283 sendChimeraCommand("close " + model.toSpec(), false);
284 // currentModelNamesMap.remove(model.getModelName());
285 currentModelsMap.remove(ChimUtils.makeModelKey(
286 model.getModelNumber(), model.getSubModelNumber()));
287 // selectionList.remove(chimeraModel);
291 logger.warn("Could not find model " + model.getModelName()
297 public void startListening()
299 sendChimeraCommand("listen start models; listen start selection", false);
302 public void stopListening()
304 sendChimeraCommand("listen stop models ; listen stop selection ", false);
308 * Tell Chimera we are listening on the given URI
312 public void startListening(String uri)
314 sendChimeraCommand("listen start models url " + uri
315 + ";listen start select prefix SelectionChanged url " + uri,
320 * Select something in Chimera
323 * the selection command to pass to Chimera
325 public void select(String command)
327 sendChimeraCommand("listen stop selection; " + command
328 + "; listen start selection", false);
333 sendChimeraCommand("focus", false);
336 public void clearOnChimeraExit()
339 currentModelsMap.clear();
340 this.chimeraRestPort = 0;
341 structureManager.clearOnChimeraExit();
344 public void exitChimera()
346 if (isChimeraLaunched() && chimera != null)
348 sendChimeraCommand("stop really", false);
351 // TODO is this too violent? could it force close the process
352 // before it has done an orderly shutdown?
354 } catch (Exception ex)
359 clearOnChimeraExit();
362 public Map<Integer, ChimeraModel> getSelectedModels()
364 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
365 List<String> chimeraReply = sendChimeraCommand(
366 "list selection level molecule", true);
367 if (chimeraReply != null)
369 for (String modelLine : chimeraReply)
371 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
372 Integer modelKey = ChimUtils.makeModelKey(
373 chimeraModel.getModelNumber(),
374 chimeraModel.getSubModelNumber());
375 selectedModelsMap.put(modelKey, chimeraModel);
378 return selectedModelsMap;
382 * Sends a 'list selection level residue' command to Chimera and returns the
383 * list of selected atomspecs
387 public List<String> getSelectedResidueSpecs()
389 List<String> selectedResidues = new ArrayList<String>();
390 List<String> chimeraReply = sendChimeraCommand(
391 "list selection level residue", true);
392 if (chimeraReply != null)
394 for (String inputLine : chimeraReply)
396 String[] inputLineParts = inputLine.split("\\s+");
397 if (inputLineParts.length == 5)
399 selectedResidues.add(inputLineParts[2]);
403 return selectedResidues;
406 public void getSelectedResidues(
407 Map<Integer, ChimeraModel> selectedModelsMap)
409 List<String> chimeraReply = sendChimeraCommand(
410 "list selection level residue", true);
411 if (chimeraReply != null)
413 for (String inputLine : chimeraReply)
415 ChimeraResidue r = new ChimeraResidue(inputLine);
416 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
417 r.getSubModelNumber());
418 if (selectedModelsMap.containsKey(modelKey))
420 ChimeraModel model = selectedModelsMap.get(modelKey);
428 * Return the list of ChimeraModels currently open. Warning: if smiles model
429 * name too long, only part of it with "..." is printed.
432 * @return List of ChimeraModel's
434 // TODO: [Optional] Handle smiles names in a better way in Chimera?
435 public List<ChimeraModel> getModelList()
437 List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
438 List<String> list = sendChimeraCommand("list models type molecule",
442 for (String modelLine : list)
444 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
445 modelList.add(chimeraModel);
452 * Return the list of depiction presets available from within Chimera. Chimera
453 * will return the list as a series of lines with the format: Preset type
454 * number "description"
456 * @return list of presets
458 public List<String> getPresets()
460 ArrayList<String> presetList = new ArrayList<String>();
461 List<String> output = sendChimeraCommand("preset list", true);
464 for (String preset : output)
466 preset = preset.substring(7); // Skip over the "Preset"
467 preset = preset.replaceFirst("\"", "(");
468 preset = preset.replaceFirst("\"", ")");
469 // string now looks like: type number (description)
470 presetList.add(preset);
476 public boolean isChimeraLaunched()
478 boolean launched = false;
484 // if we get here, process has ended
485 } catch (IllegalThreadStateException e)
487 // ok - not yet terminated
495 * Launch Chimera, unless an instance linked to this object is already
496 * running. Returns true if chimera is successfully launched, or already
497 * running, else false.
499 * @param chimeraPaths
502 public boolean launchChimera(List<String> chimeraPaths)
504 // Do nothing if Chimera is already launched
505 if (isChimeraLaunched())
510 // Try to launch Chimera (eventually using one of the possible paths)
511 String error = "Error message: ";
512 String workingPath = "";
513 // iterate over possible paths for starting Chimera
514 for (String chimeraPath : chimeraPaths)
516 File path = new File(chimeraPath);
517 // uncomment the next line to simulate Chimera not installed
518 // path = new File(chimeraPath + "x");
519 if (!path.canExecute())
521 error += "File '" + path + "' does not exist.\n";
526 List<String> args = new ArrayList<String>();
527 args.add(chimeraPath);
528 // shows Chimera output window but suppresses REST responses:
529 // args.add("--debug");
531 args.add("RESTServer");
532 ProcessBuilder pb = new ProcessBuilder(args);
533 chimera = pb.start();
535 workingPath = chimeraPath;
537 } catch (Exception e)
539 // Chimera could not be started
540 error += e.getMessage();
543 // If no error, then Chimera was launched successfully
544 if (error.length() == 0)
546 this.chimeraRestPort = getPortNumber();
547 System.out.println("Chimera REST API started on port "
549 // structureManager.initChimTable();
550 structureManager.setChimeraPathProperty(workingPath);
551 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
552 // Ask Chimera to give us updates
553 // startListening(); // later - see ChimeraListener
554 return (chimeraRestPort > 0);
557 // Tell the user that Chimera could not be started because of an error
563 * Read and return the port number returned in the reply to --start RESTServer
565 private int getPortNumber()
568 InputStream readChan = chimera.getInputStream();
569 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
571 StringBuilder responses = new StringBuilder();
574 String response = lineReader.readLine();
575 while (response != null)
577 responses.append("\n" + response);
578 // expect: REST server on host 127.0.0.1 port port_number
579 if (response.startsWith("REST server"))
581 String[] tokens = response.split(" ");
582 if (tokens.length == 7 && "port".equals(tokens[5]))
584 port = Integer.parseInt(tokens[6]);
588 response = lineReader.readLine();
590 } catch (Exception e)
592 logger.error("Failed to get REST port number from " + responses
593 + ": " + e.getMessage());
599 } catch (IOException e2)
606 .println("Failed to start Chimera with REST service, response was: "
609 logger.info("Chimera REST service listening on port " + chimeraRestPort);
614 * Determine the color that Chimera is using for this model.
617 * the ChimeraModel we want to get the Color for
618 * @return the default model Color for this model in Chimera
620 public Color getModelColor(ChimeraModel model)
622 List<String> colorLines = sendChimeraCommand(
623 "list model spec " + model.toSpec() + " attribute color", true);
624 if (colorLines == null || colorLines.size() == 0)
628 return ChimUtils.parseModelColor(colorLines.get(0));
633 * Get information about the residues associated with a model. This uses the
634 * Chimera listr command. We don't return the resulting residues, but we add
635 * the residues to the model.
638 * the ChimeraModel to get residue information for
641 public void addResidues(ChimeraModel model)
643 int modelNumber = model.getModelNumber();
644 int subModelNumber = model.getSubModelNumber();
645 // Get the list -- it will be in the reply log
646 List<String> reply = sendChimeraCommand(
647 "list residues spec " + model.toSpec(), true);
652 for (String inputLine : reply)
654 ChimeraResidue r = new ChimeraResidue(inputLine);
655 if (r.getModelNumber() == modelNumber
656 || r.getSubModelNumber() == subModelNumber)
663 public List<String> getAttrList()
665 List<String> attributes = new ArrayList<String>();
666 final List<String> reply = sendChimeraCommand("list resattr", true);
669 for (String inputLine : reply)
671 String[] lineParts = inputLine.split("\\s");
672 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
674 attributes.add(lineParts[1]);
681 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
684 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
685 final List<String> reply = sendChimeraCommand("list residue spec "
686 + model.toSpec() + " attribute " + aCommand, true);
689 for (String inputLine : reply)
691 String[] lineParts = inputLine.split("\\s");
692 if (lineParts.length == 5)
694 ChimeraResidue residue = ChimUtils
695 .getResidue(lineParts[2], model);
696 String value = lineParts[4];
699 if (value.equals("None"))
703 if (value.equals("True") || value.equals("False"))
705 values.put(residue, Boolean.valueOf(value));
710 Double doubleValue = Double.valueOf(value);
711 values.put(residue, doubleValue);
712 } catch (NumberFormatException ex)
714 values.put(residue, value);
723 private volatile boolean busy = false;
726 * Send a command to Chimera.
729 * Command string to be send.
731 * Flag indicating whether the method should return the reply from
733 * @return List of Strings corresponding to the lines in the Chimera reply or
736 public List<String> sendChimeraCommand(String command, boolean reply)
738 // System.out.println("chimeradebug>> " + command);
739 if (!isChimeraLaunched() || command == null
740 || "".equals(command.trim()))
744 // TODO do we need a maximum wait time before aborting?
750 } catch (InterruptedException q)
755 long startTime = System.currentTimeMillis();
758 return sendRestCommand(command);
762 * Make sure busy flag is reset come what may!
767 System.out.println("Chimera command took "
768 + (System.currentTimeMillis() - startTime) + "ms: "
776 * Sends the command to Chimera's REST API, and returns any response lines.
781 protected List<String> sendRestCommand(String command)
783 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
784 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
785 commands.add(new BasicNameValuePair("command", command));
787 List<String> reply = new ArrayList<String>();
788 BufferedReader response = null;
791 response = HttpClientUtils.doHttpUrlPost(restUrl, commands, CONNECTION_TIMEOUT_MS,
792 REST_REPLY_TIMEOUT_MS);
794 while ((line = response.readLine()) != null)
798 } catch (Exception e)
800 logger.error("REST call '" + command + "' failed: " + e.getMessage());
803 if (response != null)
808 } catch (IOException e)
817 * Send a command to stdin of Chimera process, and optionally read any
824 protected List<String> sendStdinCommand(String command, boolean readReply)
826 chimeraListenerThread.clearResponse(command);
827 String text = command.concat("\n");
831 chimera.getOutputStream().write(text.getBytes());
832 chimera.getOutputStream().flush();
833 } catch (IOException e)
835 // logger.info("Unable to execute command: " + text);
836 // logger.info("Exiting...");
837 logger.warn("Unable to execute command: " + text);
838 logger.warn("Exiting...");
839 clearOnChimeraExit();
846 List<String> rsp = chimeraListenerThread.getResponse(command);
850 public StructureManager getStructureManager()
852 return structureManager;
855 public boolean isBusy()
860 public Process getChimeraProcess()