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> chimeraModels = getModelList();
201 // assign color and residues to open models
202 for (ChimeraModel chimeraModel : chimeraModels)
204 // // patch for Jalview - set model name in Chimera
205 // // TODO: find a variant that works for sub-models
206 chimeraModel.setModelName(modelName);
208 "setattr M name " + modelName + " #"
209 + chimeraModel.getModelNumber(), false);
211 Color modelColor = getModelColor(chimeraModel);
212 if (modelColor != null)
214 chimeraModel.setModelColor(modelColor);
217 // Get our properties (default color scheme, etc.)
218 // Make the molecule look decent
219 // chimeraSend("repr stick "+newModel.toSpec());
221 // Create the information we need for the navigator
222 if (type != ModelType.SMILES)
224 addResidues(chimeraModel);
228 sendChimeraCommand("focus", false);
229 // startListening(); // see ChimeraListener
230 return chimeraModels;
234 * Refactored method to extract the last (or only) element delimited by file
240 private String getFileNameFromPath(String modelPath)
242 String modelName = modelPath;
243 if (modelPath == null)
247 // TODO: [Optional] Convert path to name in a better way
248 if (modelPath.lastIndexOf(File.separator) > 0)
250 modelName = modelPath
251 .substring(modelPath.lastIndexOf(File.separator) + 1);
253 else if (modelPath.lastIndexOf("/") > 0)
255 modelName = modelPath.substring(modelPath.lastIndexOf("/") + 1);
260 public void closeModel(ChimeraModel model)
262 // int model = structure.modelNumber();
263 // int subModel = structure.subModelNumber();
264 // Integer modelKey = makeModelKey(model, subModel);
266 logger.info("chimera close model " + model.getModelName());
267 if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
268 model.getModelNumber(), model.getSubModelNumber())))
270 sendChimeraCommand("close " + model.toSpec(), false);
271 // currentModelNamesMap.remove(model.getModelName());
272 currentModelsMap.remove(ChimUtils.makeModelKey(
273 model.getModelNumber(), model.getSubModelNumber()));
274 // selectionList.remove(chimeraModel);
278 logger.warn("Could not find model " + model.getModelName()
284 public void startListening()
286 sendChimeraCommand("listen start models; listen start selection", false);
289 public void stopListening()
291 sendChimeraCommand("listen stop models ; listen stop selection ", false);
295 * Tell Chimera we are listening on the given URI
299 public void startListening(String uri)
301 sendChimeraCommand("listen start models url " + uri
302 + ";listen start select prefix SelectionChanged url " + uri,
307 * Select something in Chimera
310 * the selection command to pass to Chimera
312 public void select(String command)
314 sendChimeraCommand("listen stop selection; " + command
315 + "; listen start selection", false);
320 sendChimeraCommand("focus", false);
323 public void clearOnChimeraExit()
326 currentModelsMap.clear();
327 this.chimeraRestPort = 0;
328 structureManager.clearOnChimeraExit();
331 public void exitChimera()
333 if (isChimeraLaunched() && chimera != null)
335 sendChimeraCommand("stop really", false);
339 } catch (Exception ex)
344 clearOnChimeraExit();
347 public Map<Integer, ChimeraModel> getSelectedModels()
349 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
350 List<String> chimeraReply = sendChimeraCommand(
351 "list selection level molecule", true);
352 if (chimeraReply != null)
354 for (String modelLine : chimeraReply)
356 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
357 Integer modelKey = ChimUtils.makeModelKey(
358 chimeraModel.getModelNumber(),
359 chimeraModel.getSubModelNumber());
360 selectedModelsMap.put(modelKey, chimeraModel);
363 return selectedModelsMap;
367 * Sends a 'list selection level residue' command to Chimera and returns the
368 * list of selected atomspecs
372 public List<String> getSelectedResidueSpecs()
374 List<String> selectedResidues = new ArrayList<String>();
375 List<String> chimeraReply = sendChimeraCommand(
376 "list selection level residue", true);
377 if (chimeraReply != null)
379 for (String inputLine : chimeraReply)
381 String[] inputLineParts = inputLine.split("\\s+");
382 if (inputLineParts.length == 5)
384 selectedResidues.add(inputLineParts[2]);
388 return selectedResidues;
391 public void getSelectedResidues(
392 Map<Integer, ChimeraModel> selectedModelsMap)
394 List<String> chimeraReply = sendChimeraCommand(
395 "list selection level residue", true);
396 if (chimeraReply != null)
398 for (String inputLine : chimeraReply)
400 ChimeraResidue r = new ChimeraResidue(inputLine);
401 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
402 r.getSubModelNumber());
403 if (selectedModelsMap.containsKey(modelKey))
405 ChimeraModel model = selectedModelsMap.get(modelKey);
413 * Return the list of ChimeraModels currently open. Warning: if smiles model
414 * name too long, only part of it with "..." is printed.
417 * @return List of ChimeraModel's
419 // TODO: [Optional] Handle smiles names in a better way in Chimera?
420 public List<ChimeraModel> getModelList()
422 List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
423 List<String> list = sendChimeraCommand("list models type molecule",
427 for (String modelLine : list)
429 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
430 modelList.add(chimeraModel);
437 * Return the list of depiction presets available from within Chimera. Chimera
438 * will return the list as a series of lines with the format: Preset type
439 * number "description"
441 * @return list of presets
443 public List<String> getPresets()
445 ArrayList<String> presetList = new ArrayList<String>();
446 List<String> output = sendChimeraCommand("preset list", true);
449 for (String preset : output)
451 preset = preset.substring(7); // Skip over the "Preset"
452 preset = preset.replaceFirst("\"", "(");
453 preset = preset.replaceFirst("\"", ")");
454 // string now looks like: type number (description)
455 presetList.add(preset);
461 public boolean isChimeraLaunched()
463 boolean launched = false;
469 // if we get here, process has ended
470 } catch (IllegalThreadStateException e)
472 // ok - not yet terminated
480 * Launch Chimera, unless an instance linked to this object is already
481 * running. Returns true if chimera is successfully launched, or already
482 * running, else false.
484 * @param chimeraPaths
487 public boolean launchChimera(List<String> chimeraPaths)
489 // Do nothing if Chimera is already launched
490 if (isChimeraLaunched())
495 // Try to launch Chimera (eventually using one of the possible paths)
496 String error = "Error message: ";
497 String workingPath = "";
498 // iterate over possible paths for starting Chimera
499 for (String chimeraPath : chimeraPaths)
501 File path = new File(chimeraPath);
502 // uncomment the next line to simulate Chimera not installed
503 // path = new File(chimeraPath + "x");
504 if (!path.canExecute())
506 error += "File '" + path + "' does not exist.\n";
511 List<String> args = new ArrayList<String>();
512 args.add(chimeraPath);
513 // shows Chimera output window but suppresses REST responses:
514 // args.add("--debug");
516 args.add("RESTServer");
517 ProcessBuilder pb = new ProcessBuilder(args);
518 chimera = pb.start();
520 workingPath = chimeraPath;
522 } catch (Exception e)
524 // Chimera could not be started
525 error += e.getMessage();
528 // If no error, then Chimera was launched successfully
529 if (error.length() == 0)
531 this.chimeraRestPort = getPortNumber();
532 System.out.println("Chimera REST API started on port "
534 // structureManager.initChimTable();
535 structureManager.setChimeraPathProperty(workingPath);
536 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
537 // Ask Chimera to give us updates
538 // startListening(); // later - see ChimeraListener
539 return (chimeraRestPort > 0);
542 // Tell the user that Chimera could not be started because of an error
548 * Read and return the port number returned in the reply to --start RESTServer
550 private int getPortNumber()
553 InputStream readChan = chimera.getInputStream();
554 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
556 StringBuilder responses = new StringBuilder();
559 String response = lineReader.readLine();
560 while (response != null)
562 responses.append("\n" + response);
563 // expect: REST server on host 127.0.0.1 port port_number
564 if (response.startsWith("REST server"))
566 String[] tokens = response.split(" ");
567 if (tokens.length == 7 && "port".equals(tokens[5]))
569 port = Integer.parseInt(tokens[6]);
573 response = lineReader.readLine();
575 } catch (Exception e)
577 logger.error("Failed to get REST port number from " + responses
578 + ": " + e.getMessage());
584 } catch (IOException e2)
591 .println("Failed to start Chimera with REST service, response was: "
594 logger.info("Chimera REST service listening on port " + chimeraRestPort);
599 * Determine the color that Chimera is using for this model.
602 * the ChimeraModel we want to get the Color for
603 * @return the default model Color for this model in Chimera
605 public Color getModelColor(ChimeraModel model)
607 List<String> colorLines = sendChimeraCommand(
608 "list model spec " + model.toSpec() + " attribute color", true);
609 if (colorLines == null || colorLines.size() == 0)
613 return ChimUtils.parseModelColor(colorLines.get(0));
618 * Get information about the residues associated with a model. This uses the
619 * Chimera listr command. We don't return the resulting residues, but we add
620 * the residues to the model.
623 * the ChimeraModel to get residue information for
626 public void addResidues(ChimeraModel model)
628 int modelNumber = model.getModelNumber();
629 int subModelNumber = model.getSubModelNumber();
630 // Get the list -- it will be in the reply log
631 List<String> reply = sendChimeraCommand(
632 "list residues spec " + model.toSpec(), true);
637 for (String inputLine : reply)
639 ChimeraResidue r = new ChimeraResidue(inputLine);
640 if (r.getModelNumber() == modelNumber
641 || r.getSubModelNumber() == subModelNumber)
648 public List<String> getAttrList()
650 List<String> attributes = new ArrayList<String>();
651 final List<String> reply = sendChimeraCommand("list resattr", true);
654 for (String inputLine : reply)
656 String[] lineParts = inputLine.split("\\s");
657 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
659 attributes.add(lineParts[1]);
666 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
669 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
670 final List<String> reply = sendChimeraCommand("list residue spec "
671 + model.toSpec() + " attribute " + aCommand, true);
674 for (String inputLine : reply)
676 String[] lineParts = inputLine.split("\\s");
677 if (lineParts.length == 5)
679 ChimeraResidue residue = ChimUtils
680 .getResidue(lineParts[2], model);
681 String value = lineParts[4];
684 if (value.equals("None"))
688 if (value.equals("True") || value.equals("False"))
690 values.put(residue, Boolean.valueOf(value));
695 Double doubleValue = Double.valueOf(value);
696 values.put(residue, doubleValue);
697 } catch (NumberFormatException ex)
699 values.put(residue, value);
708 private volatile boolean busy = false;
711 * Send a command to Chimera.
714 * Command string to be send.
716 * Flag indicating whether the method should return the reply from
718 * @return List of Strings corresponding to the lines in the Chimera reply or
721 public List<String> sendChimeraCommand(String command, boolean reply)
723 // System.out.println("chimeradebug>> " + command);
724 if (!isChimeraLaunched() || command == null
725 || "".equals(command.trim()))
729 // TODO do we need a maximum wait time before aborting?
735 } catch (InterruptedException q)
740 long startTime = System.currentTimeMillis();
743 return sendRestCommand(command);
747 * Make sure busy flag is reset come what may!
752 System.out.println("Chimera command took "
753 + (System.currentTimeMillis() - startTime) + "ms: "
761 * Sends the command to Chimera's REST API, and returns any response lines.
766 protected List<String> sendRestCommand(String command)
768 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
769 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
770 commands.add(new BasicNameValuePair("command", command));
772 List<String> reply = new ArrayList<String>();
773 BufferedReader response = null;
776 response = HttpClientUtils
777 .doHttpUrlPost(restUrl, commands, 100, 5000);
779 while ((line = response.readLine()) != null)
783 } catch (Exception e)
785 logger.error("REST call '" + command + "' failed: " + e.getMessage());
788 if (response != null)
793 } catch (IOException e)
802 * Send a command to stdin of Chimera process, and optionally read any
809 protected List<String> sendStdinCommand(String command, boolean readReply)
811 chimeraListenerThread.clearResponse(command);
812 String text = command.concat("\n");
816 chimera.getOutputStream().write(text.getBytes());
817 chimera.getOutputStream().flush();
818 } catch (IOException e)
820 // logger.info("Unable to execute command: " + text);
821 // logger.info("Exiting...");
822 logger.warn("Unable to execute command: " + text);
823 logger.warn("Exiting...");
824 clearOnChimeraExit();
831 List<String> rsp = chimeraListenerThread.getResponse(command);
835 public StructureManager getStructureManager()
837 return structureManager;
840 public boolean isBusy()