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
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);
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 select", false);
345 public void stopListening()
347 sendChimeraCommand("listen stop models; listen stop select", false);
351 * Select something in Chimera
354 * the selection command to pass to Chimera
356 public void select(String command)
358 sendChimeraCommand("listen stop select; " + command
359 + "; listen start select", false);
364 sendChimeraCommand("focus", false);
367 public void clearOnChimeraExit()
370 currentModelsMap.clear();
371 this.chimeraRestPort = 0;
372 structureManager.clearOnChimeraExit();
375 public void exitChimera()
377 if (isChimeraLaunched() && chimera != null)
379 sendChimeraCommand("stop really", false);
383 } catch (Exception ex)
388 clearOnChimeraExit();
391 public Map<Integer, ChimeraModel> getSelectedModels()
393 Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
394 List<String> chimeraReply = sendChimeraCommand(
395 "list selection level molecule", true);
396 if (chimeraReply != null)
398 for (String modelLine : chimeraReply)
400 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
401 Integer modelKey = ChimUtils.makeModelKey(
402 chimeraModel.getModelNumber(),
403 chimeraModel.getSubModelNumber());
404 selectedModelsMap.put(modelKey, chimeraModel);
407 return selectedModelsMap;
410 public List<String> getSelectedResidueSpecs()
412 List<String> selectedResidues = new ArrayList<String>();
413 List<String> chimeraReply = sendChimeraCommand(
414 "list selection level residue", true);
415 if (chimeraReply != null)
417 for (String inputLine : chimeraReply)
419 String[] inputLineParts = inputLine.split("\\s+");
420 if (inputLineParts.length == 5)
422 selectedResidues.add(inputLineParts[2]);
426 return selectedResidues;
429 public void getSelectedResidues(
430 Map<Integer, ChimeraModel> selectedModelsMap)
432 List<String> chimeraReply = sendChimeraCommand(
433 "list selection level residue", true);
434 if (chimeraReply != null)
436 for (String inputLine : chimeraReply)
438 ChimeraResidue r = new ChimeraResidue(inputLine);
439 Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
440 r.getSubModelNumber());
441 if (selectedModelsMap.containsKey(modelKey))
443 ChimeraModel model = selectedModelsMap.get(modelKey);
451 * Return the list of ChimeraModels currently open. Warning: if smiles model
452 * name too long, only part of it with "..." is printed.
455 * @return List of ChimeraModel's
457 // TODO: [Optional] Handle smiles names in a better way in Chimera?
458 public List<ChimeraModel> getModelList()
460 List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
461 List<String> list = sendChimeraCommand("list models type molecule",
465 for (String modelLine : list)
467 ChimeraModel chimeraModel = new ChimeraModel(modelLine);
468 modelList.add(chimeraModel);
475 * Return the list of depiction presets available from within Chimera. Chimera
476 * will return the list as a series of lines with the format: Preset type
477 * number "description"
479 * @return list of presets
481 public List<String> getPresets()
483 ArrayList<String> presetList = new ArrayList<String>();
484 List<String> output = sendChimeraCommand("preset list", true);
487 for (String preset : output)
489 preset = preset.substring(7); // Skip over the "Preset"
490 preset = preset.replaceFirst("\"", "(");
491 preset = preset.replaceFirst("\"", ")");
492 // string now looks like: type number (description)
493 presetList.add(preset);
499 public boolean isChimeraLaunched()
501 boolean launched = false;
507 // if we get here, process has ended
508 } catch (IllegalThreadStateException e)
510 // ok - not yet terminated
517 public boolean launchChimera(List<String> chimeraPaths)
519 // Do nothing if Chimera is already launched
520 if (isChimeraLaunched())
525 // Try to launch Chimera (eventually using one of the possible paths)
526 String error = "Error message: ";
527 String workingPath = "";
528 // iterate over possible paths for starting Chimera
529 for (String chimeraPath : chimeraPaths)
531 File path = new File(chimeraPath);
532 if (!path.canExecute())
534 error += "File '" + path + "' does not exist.\n";
539 List<String> args = new ArrayList<String>();
540 args.add(chimeraPath);
542 args.add("RESTServer");
543 ProcessBuilder pb = new ProcessBuilder(args);
544 chimera = pb.start();
546 workingPath = chimeraPath;
548 } catch (Exception e)
550 // Chimera could not be started
551 error += e.getMessage();
554 // If no error, then Chimera was launched successfully
555 if (error.length() == 0)
557 this.chimeraRestPort = getPortNumber();
558 System.out.println("Chimera REST API started on port "
560 // structureManager.initChimTable();
561 structureManager.setChimeraPathProperty(workingPath);
562 // TODO: [Optional] Check Chimera version and show a warning if below 1.8
563 // Ask Chimera to give us updates
568 // Tell the user that Chimera could not be started because of an error
574 * Read and return the port number returned in the reply to --start RESTServer
576 private int getPortNumber()
579 InputStream readChan = chimera.getInputStream();
580 BufferedReader lineReader = new BufferedReader(new InputStreamReader(
582 String response = null;
585 // expect: REST server on host 127.0.0.1 port port_number
586 response = lineReader.readLine();
587 String [] tokens = response.split(" ");
588 if (tokens.length == 7 && "port".equals(tokens[5])) {
589 port = Integer.parseInt(tokens[6]);
590 logger.info("Chimera REST service listening on port "
593 } catch (Exception e)
595 logger.error("Failed to get REST port number from " + response + ": "
602 } catch (IOException e2)
610 * Determine the color that Chimera is using for this model.
613 * the ChimeraModel we want to get the Color for
614 * @return the default model Color for this model in Chimera
616 public Color getModelColor(ChimeraModel model)
618 List<String> colorLines = sendChimeraCommand(
619 "list model spec " + model.toSpec() + " attribute color", true);
620 if (colorLines == null || colorLines.size() == 0)
624 return ChimUtils.parseModelColor(colorLines.get(0));
629 * Get information about the residues associated with a model. This uses the
630 * Chimera listr command. We don't return the resulting residues, but we add
631 * the residues to the model.
634 * the ChimeraModel to get residue information for
637 public void addResidues(ChimeraModel model)
639 int modelNumber = model.getModelNumber();
640 int subModelNumber = model.getSubModelNumber();
641 // Get the list -- it will be in the reply log
642 List<String> reply = sendChimeraCommand(
643 "list residues spec " + model.toSpec(), true);
648 for (String inputLine : reply)
650 ChimeraResidue r = new ChimeraResidue(inputLine);
651 if (r.getModelNumber() == modelNumber
652 || r.getSubModelNumber() == subModelNumber)
659 public List<String> getAttrList()
661 List<String> attributes = new ArrayList<String>();
662 final List<String> reply = sendChimeraCommand("list resattr", true);
665 for (String inputLine : reply)
667 String[] lineParts = inputLine.split("\\s");
668 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
670 attributes.add(lineParts[1]);
677 public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
680 Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
681 final List<String> reply = sendChimeraCommand("list residue spec "
682 + model.toSpec() + " attribute " + aCommand, true);
685 for (String inputLine : reply)
687 String[] lineParts = inputLine.split("\\s");
688 if (lineParts.length == 5)
690 ChimeraResidue residue = ChimUtils
691 .getResidue(lineParts[2], model);
692 String value = lineParts[4];
695 if (value.equals("None"))
699 if (value.equals("True") || value.equals("False"))
701 values.put(residue, Boolean.valueOf(value));
706 Double doubleValue = Double.valueOf(value);
707 values.put(residue, doubleValue);
708 } catch (NumberFormatException ex)
710 values.put(residue, value);
719 private volatile boolean busy = false;
722 * Send a command to Chimera.
725 * Command string to be send.
727 * Flag indicating whether the method should return the reply from
729 * @return List of Strings corresponding to the lines in the Chimera reply or
732 public List<String> sendChimeraCommand(String command, boolean reply)
734 if (!isChimeraLaunched() || command == null
735 || "".equals(command.trim()))
739 // TODO do we need a maximum wait time before aborting?
745 } catch (InterruptedException q)
750 long startTime = System.currentTimeMillis();
753 return sendRestCommand(command);
757 * Make sure busy flag is reset come what may!
762 System.out.println("Chimera command took "
763 + (System.currentTimeMillis() - startTime) + "ms: "
771 * Sends the command to Chimera's REST API, and returns any response lines.
776 protected List<String> sendRestCommand(String command)
778 // TODO start a separate thread to do this so we don't block?
779 String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
780 List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
781 commands.add(new BasicNameValuePair("command", command));
783 List<String> reply = new ArrayList<String>();
784 BufferedReader response = null;
786 response = HttpClientUtils
787 .doHttpUrlPost(restUrl, commands, 100, 2000);
789 while ((line = response.readLine()) != null) {
792 } catch (Exception e)
794 logger.error("REST call " + command + " failed: " + e.getMessage());
797 if (response != null)
802 } catch (IOException e)
811 * Send a command to stdin of Chimera process, and optionally read any
818 protected List<String> sendStdinCommand(String command, boolean readReply)
820 chimeraListenerThread.clearResponse(command);
821 String text = command.concat("\n");
825 chimera.getOutputStream().write(text.getBytes());
826 chimera.getOutputStream().flush();
827 } catch (IOException e)
829 // logger.info("Unable to execute command: " + text);
830 // logger.info("Exiting...");
831 logger.warn("Unable to execute command: " + text);
832 logger.warn("Exiting...");
833 clearOnChimeraExit();
840 List<String> rsp = chimeraListenerThread.getResponse(command);
844 public StructureManager getStructureManager()
846 return structureManager;
849 public boolean isBusy()