JAL-1609 refactored colour by sequence command, now performs ok
[jalview.git] / src / ext / edu / ucsf / rbvi / strucviz2 / ChimeraManager.java
1 package ext.edu.ucsf.rbvi.strucviz2;
2
3 import jalview.ws.HttpClientUtils;
4
5 import java.awt.Color;
6 import java.io.BufferedReader;
7 import java.io.File;
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;
15 import java.util.Map;
16
17 import org.apache.http.NameValuePair;
18 import org.apache.http.message.BasicNameValuePair;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
23 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
24
25 /**
26  * This object maintains the Chimera communication information.
27  */
28 public class ChimeraManager
29 {
30   private static final boolean debug = true;
31
32   /*
33    * true: use REST API (recommended), false: use stdout/stdin (deprecated)
34    */
35   private static final boolean USE_REST = true;
36
37   // Port number for Chimera REST service
38   private int restPort;
39
40   private Process chimera;
41
42   private ListenerThreads chimeraListenerThread;
43
44   private Map<Integer, ChimeraModel> currentModelsMap;
45
46   private Logger logger = LoggerFactory
47           .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
48
49   private StructureManager structureManager;
50
51   public ChimeraManager(StructureManager structureManager)
52   {
53     this.structureManager = structureManager;
54     chimera = null;
55     chimeraListenerThread = null;
56     currentModelsMap = new HashMap<Integer, ChimeraModel>();
57
58   }
59
60   public List<ChimeraModel> getChimeraModels(String modelName)
61   {
62     List<ChimeraModel> models = getChimeraModels(modelName,
63             ModelType.PDB_MODEL);
64     models.addAll(getChimeraModels(modelName, ModelType.SMILES));
65     return models;
66   }
67
68   public List<ChimeraModel> getChimeraModels(String modelName,
69           ModelType modelType)
70   {
71     List<ChimeraModel> models = new ArrayList<ChimeraModel>();
72     for (ChimeraModel model : currentModelsMap.values())
73     {
74       if (modelName.equals(model.getModelName())
75               && modelType.equals(model.getModelType()))
76       {
77         models.add(model);
78       }
79     }
80     return models;
81   }
82
83   public Map<String, List<ChimeraModel>> getChimeraModelsMap()
84   {
85     Map<String, List<ChimeraModel>> models = new HashMap<String, List<ChimeraModel>>();
86     for (ChimeraModel model : currentModelsMap.values())
87     {
88       String modelName = model.getModelName();
89       if (!models.containsKey(modelName))
90       {
91         models.put(modelName, new ArrayList<ChimeraModel>());
92       }
93       if (!models.get(modelName).contains(model))
94       {
95         models.get(modelName).add(model);
96       }
97     }
98     return models;
99   }
100
101   public ChimeraModel getChimeraModel(Integer modelNumber,
102           Integer subModelNumber)
103   {
104     Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
105     if (currentModelsMap.containsKey(key))
106     {
107       return currentModelsMap.get(key);
108     }
109     return null;
110   }
111
112   public ChimeraModel getChimeraModel()
113   {
114     return currentModelsMap.values().iterator().next();
115   }
116
117   public Collection<ChimeraModel> getChimeraModels()
118   {
119     // this method is invoked by the model navigator dialog
120     return currentModelsMap.values();
121   }
122
123   public int getChimeraModelsCount(boolean smiles)
124   {
125     // this method is invokes by the model navigator dialog
126     int counter = currentModelsMap.size();
127     if (smiles)
128     {
129       return counter;
130     }
131
132     for (ChimeraModel model : currentModelsMap.values())
133     {
134       if (model.getModelType() == ModelType.SMILES)
135       {
136         counter--;
137       }
138     }
139     return counter;
140   }
141
142   public boolean hasChimeraModel(Integer modelNubmer)
143   {
144     return hasChimeraModel(modelNubmer, 0);
145   }
146
147   public boolean hasChimeraModel(Integer modelNubmer, Integer subModelNumber)
148   {
149     return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
150             subModelNumber));
151   }
152
153   public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
154           ChimeraModel model)
155   {
156     currentModelsMap.put(
157             ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
158   }
159
160   public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
161   {
162     int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
163     if (currentModelsMap.containsKey(modelKey))
164     {
165       currentModelsMap.remove(modelKey);
166     }
167   }
168
169   public List<ChimeraModel> openModel(String modelPath, ModelType type)
170   {
171     return openModel(modelPath, getFileNameFromPath(modelPath), type);
172   }
173
174   /**
175    * Overloaded method to allow Jalview to pass in a model name.
176    * 
177    * @param modelPath
178    * @param modelName
179    * @param type
180    * @return
181    */
182   public List<ChimeraModel> openModel(String modelPath, String modelName,
183           ModelType type)
184   {
185     logger.info("chimera open " + modelPath);
186     stopListening();
187     List<String> response = null;
188     // TODO: [Optional] Handle modbase models
189     if (type == ModelType.MODBASE_MODEL)
190     {
191       response = sendChimeraCommand("open modbase:" + modelPath, true);
192       // } else if (type == ModelType.SMILES) {
193       // response = sendChimeraCommand("open smiles:" + modelName, true);
194       // modelName = "smiles:" + modelName;
195     }
196     else
197     {
198       response = sendChimeraCommand("open " + modelPath, true);
199     }
200     if (response == null)
201     {
202       // something went wrong
203       logger.warn("Could not open " + modelPath);
204       return null;
205     }
206     List<ChimeraModel> models = new ArrayList<ChimeraModel>();
207     int[] modelNumbers = null;
208     if (type == ModelType.PDB_MODEL)
209     {
210       for (String line : response)
211       {
212         if (line.startsWith("#"))
213         {
214           modelNumbers = ChimUtils.parseOpenedModelNumber(line);
215           if (modelNumbers != null)
216           {
217             int modelNumber = ChimUtils.makeModelKey(modelNumbers[0],
218                     modelNumbers[1]);
219             if (currentModelsMap.containsKey(modelNumber))
220             {
221               continue;
222             }
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
231             modelNumbers = null;
232           }
233         }
234       }
235     }
236     else
237     {
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)
242       {
243         String openModelName = openModel.getModelName();
244         if (openModelName.endsWith("..."))
245         {
246           openModelName = openModelName.substring(0,
247                   openModelName.length() - 3);
248         }
249         if (modelPath.startsWith(openModelName))
250         {
251           openModel.setModelName(modelPath);
252           int modelNumber = ChimUtils
253                   .makeModelKey(openModel.getModelNumber(),
254                           openModel.getSubModelNumber());
255           if (!currentModelsMap.containsKey(modelNumber))
256           {
257             currentModelsMap.put(modelNumber, openModel);
258             models.add(openModel);
259           }
260         }
261       }
262     }
263
264     // assign color and residues to open models
265     for (ChimeraModel newModel : models)
266     {
267       // get model color
268       Color modelColor = getModelColor(newModel);
269       if (modelColor != null)
270       {
271         newModel.setModelColor(modelColor);
272       }
273
274       // Get our properties (default color scheme, etc.)
275       // Make the molecule look decent
276       // chimeraSend("repr stick "+newModel.toSpec());
277
278       // Create the information we need for the navigator
279       if (type != ModelType.SMILES)
280       {
281         addResidues(newModel);
282       }
283     }
284
285     sendChimeraCommand("focus", false);
286     startListening();
287     return models;
288   }
289
290   /**
291    * Refactored method to extract the last (or only) element delimited by file
292    * path separator.
293    * 
294    * @param modelPath
295    * @return
296    */
297   private String getFileNameFromPath(String modelPath)
298   {
299     String modelName = modelPath;
300     if (modelPath == null)
301     {
302       return null;
303     }
304     // TODO: [Optional] Convert path to name in a better way
305     if (modelPath.lastIndexOf(File.separator) > 0)
306     {
307       modelName = modelPath.substring(modelPath
308               .lastIndexOf(File.separator) + 1);
309     }
310     else if (modelPath.lastIndexOf("/") > 0)
311     {
312       modelName = modelPath
313               .substring(modelPath.lastIndexOf("/") + 1);
314     }
315     return modelName;
316   }
317
318   public void closeModel(ChimeraModel model)
319   {
320     // int model = structure.modelNumber();
321     // int subModel = structure.subModelNumber();
322     // Integer modelKey = makeModelKey(model, subModel);
323     stopListening();
324     logger.info("chimera close model " + model.getModelName());
325     if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
326             model.getModelNumber(), model.getSubModelNumber())))
327     {
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);
333     }
334     else
335     {
336       logger.warn("Could not find model " + model.getModelName()
337               + " to close.");
338     }
339     startListening();
340   }
341
342   public void startListening()
343   {
344     sendChimeraCommand("listen start models; listen start select", false);
345   }
346
347   public void stopListening()
348   {
349     sendChimeraCommand("listen stop models; listen stop select", false);
350   }
351
352   /**
353    * Select something in Chimera
354    * 
355    * @param command
356    *          the selection command to pass to Chimera
357    */
358   public void select(String command)
359   {
360     sendChimeraCommand("listen stop select; " + command
361             + "; listen start select", false);
362   }
363
364   public void focus()
365   {
366     sendChimeraCommand("focus", false);
367   }
368
369   public void clearOnChimeraExit()
370   {
371     chimera = null;
372     currentModelsMap.clear();
373     if (!USE_REST)
374     {
375       chimeraListenerThread.requestStop();
376       chimeraListenerThread = null;
377     }
378     structureManager.clearOnChimeraExit();
379   }
380
381   public void exitChimera()
382   {
383     if (isChimeraLaunched() && chimera != null)
384     {
385       sendChimeraCommand("stop really", false);
386       try
387       {
388         chimera.destroy();
389       } catch (Exception ex)
390       {
391         // ignore
392       }
393     }
394     clearOnChimeraExit();
395   }
396
397   public Map<Integer, ChimeraModel> getSelectedModels()
398   {
399     Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
400     List<String> chimeraReply = sendChimeraCommand(
401             "list selection level molecule", true);
402     if (chimeraReply != null)
403     {
404       for (String modelLine : chimeraReply)
405       {
406         ChimeraModel chimeraModel = new ChimeraModel(modelLine);
407         Integer modelKey = ChimUtils.makeModelKey(
408                 chimeraModel.getModelNumber(),
409                 chimeraModel.getSubModelNumber());
410         selectedModelsMap.put(modelKey, chimeraModel);
411       }
412     }
413     return selectedModelsMap;
414   }
415
416   public List<String> getSelectedResidueSpecs()
417   {
418     List<String> selectedResidues = new ArrayList<String>();
419     List<String> chimeraReply = sendChimeraCommand(
420             "list selection level residue", true);
421     if (chimeraReply != null)
422     {
423       for (String inputLine : chimeraReply)
424       {
425         String[] inputLineParts = inputLine.split("\\s+");
426         if (inputLineParts.length == 5)
427         {
428           selectedResidues.add(inputLineParts[2]);
429         }
430       }
431     }
432     return selectedResidues;
433   }
434
435   public void getSelectedResidues(
436           Map<Integer, ChimeraModel> selectedModelsMap)
437   {
438     List<String> chimeraReply = sendChimeraCommand(
439             "list selection level residue", true);
440     if (chimeraReply != null)
441     {
442       for (String inputLine : chimeraReply)
443       {
444         ChimeraResidue r = new ChimeraResidue(inputLine);
445         Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
446                 r.getSubModelNumber());
447         if (selectedModelsMap.containsKey(modelKey))
448         {
449           ChimeraModel model = selectedModelsMap.get(modelKey);
450           model.addResidue(r);
451         }
452       }
453     }
454   }
455
456   /**
457    * Return the list of ChimeraModels currently open. Warning: if smiles model
458    * name too long, only part of it with "..." is printed.
459    * 
460    * 
461    * @return List of ChimeraModel's
462    */
463   // TODO: [Optional] Handle smiles names in a better way in Chimera?
464   public List<ChimeraModel> getModelList()
465   {
466     List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
467     List<String> list = sendChimeraCommand("list models type molecule",
468             true);
469     if (list != null)
470     {
471       for (String modelLine : list)
472       {
473         ChimeraModel chimeraModel = new ChimeraModel(modelLine);
474         modelList.add(chimeraModel);
475       }
476     }
477     return modelList;
478   }
479
480   /**
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"
484    * 
485    * @return list of presets
486    */
487   public List<String> getPresets()
488   {
489     ArrayList<String> presetList = new ArrayList<String>();
490     List<String> output = sendChimeraCommand("preset list", true);
491     if (output != null)
492     {
493       for (String preset : output)
494       {
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);
500       }
501     }
502     return presetList;
503   }
504
505   public boolean isChimeraLaunched()
506   {
507     boolean launched = false;
508     if (chimera != null)
509     {
510       try
511       {
512         chimera.exitValue();
513         // if we get here, process has ended
514       } catch (IllegalThreadStateException e)
515       {
516         // ok - not yet terminated
517         launched = true;
518       }
519     }
520     return launched;
521   }
522
523   public boolean launchChimera(List<String> chimeraPaths)
524   {
525     // Do nothing if Chimera is already launched
526     if (isChimeraLaunched())
527     {
528       return true;
529     }
530
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)
536     {
537       File path = new File(chimeraPath);
538       if (!path.canExecute())
539       {
540         error += "File '" + path + "' does not exist.\n";
541         continue;
542       }
543       try
544       {
545         List<String> args = new ArrayList<String>();
546         args.add(chimeraPath);
547         args.add("--start");
548         args.add(USE_REST ? "RESTServer" : "ReadStdin");
549         ProcessBuilder pb = new ProcessBuilder(args);
550         chimera = pb.start();
551         error = "";
552         workingPath = chimeraPath;
553         logger.info("Starting " + chimeraPath + " with "
554                 + (USE_REST ? "REST API" : "stdin/stdout"));
555         break;
556       } catch (Exception e)
557       {
558         // Chimera could not be started
559         error += e.getMessage();
560       }
561     }
562     // If no error, then Chimera was launched successfully
563     if (error.length() == 0)
564     {
565       if (USE_REST)
566       {
567         this.restPort = getPortNumber();
568       }
569       else
570       {
571         // Initialize the listener threads
572         chimeraListenerThread = new ListenerThreads(chimera,
573                 structureManager);
574         chimeraListenerThread.start();
575       }
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
580       startListening();
581       return true;
582     }
583
584     // Tell the user that Chimera could not be started because of an error
585     logger.warn(error);
586     return false;
587   }
588
589   /**
590    * Read and return the port number returned in the reply to --start RESTServer
591    */
592   private int getPortNumber()
593   {
594     int port = 0;
595     InputStream readChan = chimera.getInputStream();
596     BufferedReader lineReader = new BufferedReader(new InputStreamReader(
597             readChan));
598     String response = null;
599     try
600     {
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);
607       }
608     } catch (Exception e)
609     {
610       logger.error("Failed to get REST port number from " + response + ": "
611               + e.getMessage());
612     } finally
613     {
614       try
615       {
616         lineReader.close();
617       } catch (IOException e2)
618       {
619       }
620     }
621     return port;
622   }
623
624   /**
625    * Determine the color that Chimera is using for this model.
626    * 
627    * @param model
628    *          the ChimeraModel we want to get the Color for
629    * @return the default model Color for this model in Chimera
630    */
631   public Color getModelColor(ChimeraModel model)
632   {
633     List<String> colorLines = sendChimeraCommand(
634             "list model spec " + model.toSpec() + " attribute color", true);
635     if (colorLines == null || colorLines.size() == 0)
636     {
637       return null;
638     }
639     return ChimUtils.parseModelColor(colorLines.get(0));
640   }
641
642   /**
643    * 
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.
647    * 
648    * @param model
649    *          the ChimeraModel to get residue information for
650    * 
651    */
652   public void addResidues(ChimeraModel model)
653   {
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);
659     if (reply == null)
660     {
661       return;
662     }
663     for (String inputLine : reply)
664     {
665       ChimeraResidue r = new ChimeraResidue(inputLine);
666       if (r.getModelNumber() == modelNumber
667               || r.getSubModelNumber() == subModelNumber)
668       {
669         model.addResidue(r);
670       }
671     }
672   }
673
674   public List<String> getAttrList()
675   {
676     List<String> attributes = new ArrayList<String>();
677     final List<String> reply = sendChimeraCommand("list resattr", true);
678     if (reply != null)
679     {
680       for (String inputLine : reply)
681       {
682         String[] lineParts = inputLine.split("\\s");
683         if (lineParts.length == 2 && lineParts[0].equals("resattr"))
684         {
685           attributes.add(lineParts[1]);
686         }
687       }
688     }
689     return attributes;
690   }
691
692   public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
693           ChimeraModel model)
694   {
695     Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
696     final List<String> reply = sendChimeraCommand("list residue spec "
697             + model.toSpec() + " attribute " + aCommand, true);
698     if (reply != null)
699     {
700       for (String inputLine : reply)
701       {
702         String[] lineParts = inputLine.split("\\s");
703         if (lineParts.length == 5)
704         {
705           ChimeraResidue residue = ChimUtils
706                   .getResidue(lineParts[2], model);
707           String value = lineParts[4];
708           if (residue != null)
709           {
710             if (value.equals("None"))
711             {
712               continue;
713             }
714             if (value.equals("True") || value.equals("False"))
715             {
716               values.put(residue, Boolean.valueOf(value));
717               continue;
718             }
719             try
720             {
721               Double doubleValue = Double.valueOf(value);
722               values.put(residue, doubleValue);
723             } catch (NumberFormatException ex)
724             {
725               values.put(residue, value);
726             }
727           }
728         }
729       }
730     }
731     return values;
732   }
733
734   private volatile boolean busy = false;
735
736   /**
737    * Send a command to Chimera.
738    * 
739    * @param command
740    *          Command string to be send.
741    * @param reply
742    *          Flag indicating whether the method should return the reply from
743    *          Chimera or not.
744    * @return List of Strings corresponding to the lines in the Chimera reply or
745    *         <code>null</code>.
746    */
747   public List<String> sendChimeraCommand(String command, boolean reply)
748   {
749     if (!isChimeraLaunched() || command == null
750             || "".equals(command.trim()))
751     {
752       return null;
753     }
754     // TODO do we need a maximum wait time before aborting?
755     while (busy)
756     {
757       try
758       {
759         Thread.sleep(25);
760       } catch (InterruptedException q)
761       {
762       }
763       ;
764     }
765     busy = true;
766     long startTime = System.currentTimeMillis();
767     try
768     {
769       if (USE_REST)
770       {
771         return sendRestCommand(command);
772       }
773       else
774       {
775         return sendStdinCommand(command, reply);
776       }
777     } finally
778     {
779       busy = false;
780       if (debug)
781       {
782         System.out.println("Chimera command took "
783                 + (System.currentTimeMillis() - startTime) + "ms: "
784                 + command);
785       }
786
787     }
788   }
789
790   /**
791    * Sends the command to Chimera's REST API, and returns any response lines.
792    * 
793    * @param command
794    * @return
795    */
796   protected List<String> sendRestCommand(String command)
797   {
798     // TODO start a separate thread to do this so we don't block?
799     String restUrl = "http://127.0.0.1:" + this.restPort + "/run";
800     List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
801     commands.add(new BasicNameValuePair("command", command));
802
803     List<String> reply = new ArrayList<String>();
804     BufferedReader response = null;
805     try {
806       response = HttpClientUtils.doHttpUrlPost(restUrl,
807               commands);
808       String line = "";
809       while ((line = response.readLine()) != null) {
810         reply.add(line);
811       }
812     } catch (Exception e)
813     {
814       logger.error("REST call " + command + " failed: " + e.getMessage());
815     } finally
816     {
817       if (response != null)
818       {
819         try
820         {
821           response.close();
822         } catch (IOException e)
823         {
824         }
825       }
826     }
827     return reply;
828   }
829
830   /**
831    * Send a command to stdin of Chimera process, and optionally read any
832    * responses.
833    * 
834    * @param command
835    * @param readReply
836    * @return
837    */
838   protected List<String> sendStdinCommand(String command, boolean readReply)
839   {
840     chimeraListenerThread.clearResponse(command);
841     String text = command.concat("\n");
842     try
843     {
844       // send the command
845       chimera.getOutputStream().write(text.getBytes());
846       chimera.getOutputStream().flush();
847     } catch (IOException e)
848     {
849       // logger.info("Unable to execute command: " + text);
850       // logger.info("Exiting...");
851       logger.warn("Unable to execute command: " + text);
852       logger.warn("Exiting...");
853       clearOnChimeraExit();
854       return null;
855     }
856     if (!readReply)
857     {
858       return null;
859     }
860     List<String> rsp = chimeraListenerThread.getResponse(command);
861     return rsp;
862   }
863
864   public StructureManager getStructureManager()
865   {
866     return structureManager;
867   }
868
869   public boolean isBusy()
870   {
871     return busy;
872   }
873
874 }