JAL-629 Adding PAE and TFType at structure loading time. Display PAE automatically
[jalview.git] / src / jalview / bin / Commands.java
1 package jalview.bin;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.AbstractMap;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Locale;
13 import java.util.Map;
14 import java.util.Map.Entry;
15
16 import jalview.analysis.AlignmentUtils;
17 import jalview.bin.argparser.Arg;
18 import jalview.bin.argparser.ArgParser;
19 import jalview.bin.argparser.ArgValue;
20 import jalview.bin.argparser.ArgValues;
21 import jalview.bin.argparser.ArgValuesMap;
22 import jalview.bin.argparser.SubVals;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.AlignmentPanel;
30 import jalview.gui.AssociatePdbFileWithSeq;
31 import jalview.gui.Desktop;
32 import jalview.gui.Preferences;
33 import jalview.gui.StructureChooser;
34 import jalview.gui.StructureViewer;
35 import jalview.io.AppletFormatAdapter;
36 import jalview.io.DataSourceType;
37 import jalview.io.FileFormat;
38 import jalview.io.FileFormatException;
39 import jalview.io.FileFormatI;
40 import jalview.io.FileLoader;
41 import jalview.io.HtmlSvgOutput;
42 import jalview.io.IdentifyFile;
43 import jalview.schemes.AnnotationColourGradient;
44 import jalview.structure.StructureImportSettings.TFType;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.util.HttpUtils;
47 import jalview.util.MessageManager;
48 import jalview.util.Platform;
49 import mc_view.PDBChain;
50
51 public class Commands
52 {
53   Desktop desktop;
54
55   private boolean headless;
56
57   private ArgParser argParser;
58
59   private Map<String, AlignFrame> afMap;
60
61   private boolean commandArgsProvided = false;
62
63   private boolean argsWereParsed = false;
64
65   public Commands(ArgParser argparser, boolean headless)
66   {
67     this(Desktop.instance, argparser, headless);
68   }
69
70   public Commands(Desktop d, ArgParser argparser, boolean h)
71   {
72     argParser = argparser;
73     headless = h;
74     desktop = d;
75     afMap = new HashMap<String, AlignFrame>();
76     if (argparser != null)
77     {
78       processArgs(argparser, headless);
79     }
80   }
81
82   private boolean processArgs(ArgParser argparser, boolean h)
83   {
84     argParser = argparser;
85     headless = h;
86     boolean theseArgsWereParsed = false;
87
88     if (argParser != null && argParser.linkedIds() != null)
89     {
90       for (String id : argParser.linkedIds())
91       {
92         ArgValuesMap avm = argParser.linkedArgs(id);
93         theseArgsWereParsed = true;
94         if (id == null)
95         {
96           theseArgsWereParsed &= processUnlinked(id);
97         }
98         else
99         {
100           theseArgsWereParsed &= processLinked(id);
101         }
102         theseArgsWereParsed &= processImages(id);
103
104         // close ap
105         if (avm.getBoolean(Arg.CLOSE))
106         {
107           AlignFrame af = afMap.get(id);
108           if (af != null)
109           {
110             af.closeMenuItem_actionPerformed(true);
111           }
112         }
113
114       }
115
116     }
117     if (argParser.getBool(Arg.QUIT))
118     {
119       Jalview.getInstance().quit();
120       return true;
121     }
122     // carry on with jalview.bin.Jalview
123     argsWereParsed = theseArgsWereParsed;
124     return argsWereParsed;
125   }
126
127   public boolean commandArgsProvided()
128   {
129     return commandArgsProvided;
130   }
131
132   public boolean argsWereParsed()
133   {
134     return argsWereParsed;
135   }
136
137   protected boolean processUnlinked(String id)
138   {
139     return processLinked(id);
140   }
141
142   protected boolean processLinked(String id)
143   {
144     boolean theseArgsWereParsed = false;
145     ArgValuesMap avm = argParser.linkedArgs(id);
146     if (avm == null)
147       return true;
148
149     /*
150      * // script to execute after all loading is completed one way or another String
151      * groovyscript = m.get(Arg.GROOVY) == null ? null :
152      * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
153      * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
154      * DataSourceType protocol = null;
155      */
156     if (avm.containsArg(Arg.OPEN) || avm.containsArg(Arg.OPENNEW))
157     {
158       commandArgsProvided = true;
159       long progress = -1;
160
161       boolean first = true;
162       boolean progressBarSet = false;
163       AlignFrame af;
164       // Combine the OPEN and OPENNEW files into one list, along with whether it
165       // was OPEN or OPENNEW
166       List<Entry<Arg, ArgValue>> openAvList = new ArrayList<>();
167       avm.getArgValueList(Arg.OPEN).stream()
168               .forEachOrdered(av -> openAvList.add(
169                       new AbstractMap.SimpleEntry<Arg, ArgValue>(Arg.OPEN,
170                               av)));
171       avm.getArgValueList(Arg.OPENNEW).stream()
172               .forEachOrdered(av -> openAvList
173                       .add(new AbstractMap.SimpleEntry<Arg, ArgValue>(
174                               Arg.OPENNEW, av)));
175       for (Entry<Arg, ArgValue> aav : openAvList)
176       {
177         Arg a = aav.getKey();
178         ArgValue av = aav.getValue();
179         String openFile = av.getValue();
180         if (openFile == null)
181           continue;
182
183         theseArgsWereParsed = true;
184         if (first)
185         {
186           first = false;
187           if (!headless && desktop != null)
188           {
189             desktop.setProgressBar(
190                     MessageManager.getString(
191                             "status.processing_commandline_args"),
192                     progress = System.currentTimeMillis());
193             progressBarSet = true;
194           }
195         }
196
197         if (!Platform.isJS())
198         /**
199          * ignore in JavaScript -- can't just file existence - could load it?
200          * 
201          * @j2sIgnore
202          */
203         {
204           if (!HttpUtils.startsWithHttpOrHttps(openFile))
205           {
206             if (!(new File(openFile)).exists())
207             {
208               Console.warn("Can't find file '" + openFile + "'");
209             }
210           }
211         }
212
213         DataSourceType protocol = AppletFormatAdapter
214                 .checkProtocol(openFile);
215
216         FileFormatI format = null;
217         try
218         {
219           format = new IdentifyFile().identify(openFile, protocol);
220         } catch (FileFormatException e1)
221         {
222           Console.error("Unknown file format for '" + openFile + "'");
223         }
224
225         af = afMap.get(id);
226         if (af == null || "true".equals(av.getSubVal("new"))
227                 || a == Arg.OPENNEW || format == FileFormat.Jalview)
228         {
229           /*
230            * this approach isn't working yet // get default annotations before opening
231            * AlignFrame if (m.get(Arg.SSANNOTATION) != null) {
232            * Console.debug("##### SSANNOTATION=" + m.get(Arg.SSANNOTATION).getBoolean());
233            * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
234            * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
235            * (m.get(Arg.SSANNOTATION) != null) ? m.get(Arg.SSANNOTATION).getBoolean() :
236            * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
237            * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
238            * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
239            * StructureSelectionManager ssm = StructureSelectionManager
240            * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
241            * ssm.setAddTempFacAnnot(showTemperatureFactor);
242            * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
243            */
244
245           Console.debug(
246                   "Opening '" + openFile + "' in new alignment frame");
247           FileLoader fileLoader = new FileLoader(!headless);
248
249           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
250                   format);
251
252           // wrap alignment?
253           if (avm.getBoolean(Arg.WRAP))
254           {
255             af.getCurrentView().setWrapAlignment(true);
256           }
257
258           // colour aligment?
259           if (avm.containsArg(Arg.COLOUR))
260           {
261             af.changeColour_actionPerformed(avm.getValue(Arg.COLOUR));
262           }
263
264           // change alignment frame title
265           if (avm.containsArg(Arg.TITLE))
266             af.setTitle(avm.getValue(Arg.TITLE));
267
268           /* hacky approach to hiding the annotations */
269           // show secondary structure annotations?
270           if (avm.getBoolean(Arg.SSANNOTATION))
271           {
272             // do this better (annotation types?)
273             AlignmentUtils.showOrHideSequenceAnnotations(
274                     af.getCurrentView().getAlignment(),
275                     Collections.singleton("Secondary Structure"), null,
276                     false, false);
277           }
278
279           // show temperature factor annotations?
280           if (avm.getBoolean(Arg.NOTEMPFAC))
281           {
282             // do this better (annotation types?)
283             List<String> hideThese = new ArrayList<>();
284             hideThese.add("Temperature Factor");
285             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
286             AlignmentUtils.showOrHideSequenceAnnotations(
287                     af.getCurrentView().getAlignment(), hideThese, null,
288                     false, false);
289           }
290           else
291           /*
292            * comment out hacky approach up to here and add this line: if
293            * (showTemperatureFactor)
294            */
295           {
296             if (avm.containsArg(Arg.TEMPFAC_LABEL))
297             {
298               AlignmentAnnotation aa = AlignmentUtils
299                       .getFirstSequenceAnnotationOfType(
300                               af.getCurrentView().getAlignment(),
301                               AlignmentAnnotation.LINE_GRAPH);
302               String label = avm.getValue(Arg.TEMPFAC_LABEL);
303               if (aa != null)
304               {
305                 aa.label = label;
306               }
307               else
308               {
309                 Console.info(
310                         "Could not find annotation to apply tempfac_label '"
311                                 + label);
312               }
313             }
314           }
315
316           // store the AlignFrame for this id
317           afMap.put(id, af);
318
319           // is it its own structure file?
320           if (format.isStructureFile())
321           {
322             StructureSelectionManager ssm = StructureSelectionManager
323                     .getStructureSelectionManager(Desktop.instance);
324             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
325             ssm.computeMapping(false, new SequenceI[] { seq }, null,
326                     openFile, DataSourceType.FILE, null, null, null);
327           }
328         }
329         else
330         {
331           Console.debug(
332                   "Opening '" + openFile + "' in existing alignment frame");
333           af.getCurrentView().addFile(new File(openFile), format, false);
334         }
335
336         Console.debug("Command " + Arg.OPEN + " executed successfully!");
337
338       }
339       if (first) // first=true means nothing opened
340       {
341         if (headless)
342         {
343           Jalview.exit("Could not open any files in headless mode", 1);
344         }
345         else
346         {
347           Console.warn("No more files to open");
348         }
349       }
350       if (progressBarSet && desktop != null)
351         desktop.setProgressBar(null, progress);
352
353     }
354
355     // open the structure (from same PDB file or given PDBfile)
356     if (!avm.getBoolean(Arg.NOSTRUCTURE))
357     {
358       AlignFrame af = afMap.get(id);
359       if (avm.containsArg(Arg.STRUCTURE))
360       {
361         commandArgsProvided = true;
362         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
363         {
364           String val = av.getValue();
365           SubVals subVals = av.getSubVals();
366           SequenceI seq = getSpecifiedSequence(af, subVals);
367           if (seq == null)
368           {
369             // Could not find sequence from subId, let's assume the first
370             // sequence in the alignframe
371             AlignmentI al = af.getCurrentView().getAlignment();
372             seq = al.getSequenceAt(0);
373           }
374
375           if (seq == null)
376           {
377             Console.warn("Could not find sequence for argument "
378                     + Arg.STRUCTURE.argString() + "=" + val);
379             // you probably want to continue here, not break
380             // break;
381             continue;
382           }
383           File structureFile = null;
384           if (subVals.getContent() != null
385                   && subVals.getContent().length() != 0)
386           {
387             structureFile = new File(subVals.getContent());
388             Console.debug("Using structure file (from argument) '"
389                     + structureFile.getAbsolutePath() + "'");
390           }
391           // TRY THIS
392           /*
393            * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
394            * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
395            * selectedSequence, true, Desktop.instance);
396            * 
397            * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
398            * SequenceI[] { selectedSequence });
399            * 
400            */
401           /* THIS DOESN'T WORK */
402           else if (seq.getAllPDBEntries() != null
403                   && seq.getAllPDBEntries().size() > 0)
404           {
405             structureFile = new File(
406                     seq.getAllPDBEntries().elementAt(0).getFile());
407             Console.debug("Using structure file (from sequence) '"
408                     + structureFile.getAbsolutePath() + "'");
409           }
410
411           if (structureFile == null)
412           {
413             Console.warn("Not provided structure file with '" + val + "'");
414             continue;
415           }
416
417           if (!structureFile.exists())
418           {
419             Console.warn("Structure file '"
420                     + structureFile.getAbsoluteFile() + "' not found.");
421             continue;
422           }
423
424           Console.debug("Using structure file "
425                   + structureFile.getAbsolutePath());
426
427           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
428                   .associatePdbWithSeq(structureFile.getAbsolutePath(),
429                           DataSourceType.FILE, seq, true, Desktop.instance);
430
431           // open structure view
432           AlignmentPanel ap = af.alignPanel;
433           if (headless)
434           {
435             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
436                     StructureViewer.ViewerType.JMOL.toString());
437           }
438
439           String structureFilepath = structureFile.getAbsolutePath();
440
441           // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
442           String paeFilepath = subVals.getWithSubstitutions(argParser, id,
443                   "paematrix");
444           String paeLabel = subVals.get("paelabel");
445           ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
446                   af, structureFilepath);
447           if (paeFilepath == null && paeAv != null)
448           {
449             SubVals sv = paeAv.getSubVals();
450             File paeFile = new File(sv.getContent());
451
452             paeLabel = sv.get("label");
453             try
454             {
455               paeFilepath = paeFile.getCanonicalPath();
456             } catch (IOException e)
457             {
458               paeFilepath = paeFile.getAbsolutePath();
459               Console.warn("Problem with the PAE file path: '"
460                       + paeFile.getPath() + "'");
461             }
462           }
463
464           // get TEMPFAC type from subvals or Arg.TEMPFAC
465           String tftString = subVals.get("tempfac");
466           TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
467                   : TFType.DEFAULT;
468           ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
469                   af, structureFilepath);
470           if (tftString == null && tftAv != null)
471           {
472             tftString = tftAv.getSubVals().getContent();
473           }
474           if (tftString != null)
475           {
476             // get kind of temperature factor annotation
477             try
478             {
479               tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
480               Console.debug("Obtained Temperature Factor type of '" + tft
481                       + "' for structure '" + structureFilepath + "'");
482             } catch (IllegalArgumentException e)
483             {
484               // Just an error message!
485               StringBuilder sb = new StringBuilder().append("Cannot set ")
486                       .append(Arg.TEMPFAC.argString()).append(" to '")
487                       .append(tft)
488                       .append("', ignoring.  Valid values are: ");
489               Iterator<TFType> it = Arrays.stream(TFType.values())
490                       .iterator();
491               while (it.hasNext())
492               {
493                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
494                 if (it.hasNext())
495                   sb.append(", ");
496               }
497               Console.warn(sb.toString());
498             }
499           }
500
501           // TODO pass PAE label
502           StructureChooser.openStructureFileForSequence(null, null, ap, seq,
503                   false, structureFilepath, tft, paeFilepath);
504         }
505       }
506     }
507
508     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
509     if (doShading)
510     {
511       AlignFrame af = afMap.get(id);
512       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
513               .findAnnotation(PDBChain.class.getName().toString()))
514       {
515         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
516                 af.alignPanel.av.getGlobalColourScheme(), 0);
517         acg.setSeqAssociated(true);
518         af.changeColour(acg);
519         Console.info("Changed colour " + acg.toString());
520       }
521     }
522
523     return theseArgsWereParsed;
524   }
525
526   protected boolean processImages(String id)
527   {
528     ArgValuesMap avm = argParser.linkedArgs(id);
529     AlignFrame af = afMap.get(id);
530
531     if (af == null)
532     {
533       Console.warn("Did not have an alignment window for id=" + id);
534       return false;
535     }
536
537     if (avm.containsArg(Arg.IMAGE))
538     {
539       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
540       {
541         String val = av.getValue();
542         SubVals subVal = av.getSubVals();
543         String type = "png"; // default
544         String fileName = subVal.getContent();
545         File file = new File(fileName);
546         if (subVal.has("type"))
547         {
548           type = subVal.get("type");
549         }
550         else if (fileName != null)
551         {
552           for (String ext : new String[] { "svg", "png", "html" })
553           {
554             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
555             {
556               type = ext;
557             }
558           }
559         }
560         // for moment we disable JSON export
561         Cache.setPropsAreReadOnly(true);
562         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
563
564         switch (type)
565         {
566         case "svg":
567           Console.debug("Outputting type '" + type + "' to " + fileName);
568           af.createSVG(file);
569           break;
570         case "png":
571           Console.debug("Outputting type '" + type + "' to " + fileName);
572           af.createPNG(file);
573           break;
574         case "html":
575           Console.debug("Outputting type '" + type + "' to " + fileName);
576           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
577           htmlSVG.exportHTML(fileName);
578           break;
579         default:
580           Console.warn(Arg.IMAGE.argString() + " type '" + type
581                   + "' not known. Ignoring");
582           break;
583         }
584       }
585     }
586     return true;
587   }
588
589   private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
590   {
591     if (subId == null)
592       return null;
593     AlignmentI al = af.getCurrentView().getAlignment();
594     if (subId.has("seqid"))
595     {
596       return al.findName(subId.get("seqid"));
597     }
598     else if (-1 < subId.getIndex()
599             && subId.getIndex() < al.getSequences().size())
600     {
601       return al.getSequenceAt(subId.getIndex());
602     }
603     return null;
604   }
605
606   // returns the first Arg value intended for the structure structFilename
607   // (in the given AlignFrame from the ArgValuesMap)
608   private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
609           AlignFrame af, String structFilename)
610   {
611     if (af != null)
612     {
613       for (ArgValue av : avm.getArgValueList(arg))
614       {
615         SubVals subVals = av.getSubVals();
616         String structid = subVals.get("structid");
617         String structfile = subVals.get("structfile");
618
619         // let's find a structure
620         if (structfile == null && structid == null)
621         {
622           ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
623                   Arg.STRUCTURE);
624           if (likelyStructure != null)
625           {
626             SubVals sv = likelyStructure.getSubVals();
627             if (sv != null && sv.has(ArgValues.ID))
628             {
629               structid = sv.get(ArgValues.ID);
630             }
631             else
632             {
633               structfile = likelyStructure.getValue();
634               Console.debug(
635                       "##### Comparing closest previous structure argument '"
636                               + structfile + "'");
637             }
638           }
639         }
640
641         if (structfile == null && structid != null)
642         {
643           StructureSelectionManager ssm = StructureSelectionManager
644                   .getStructureSelectionManager(Desktop.instance);
645           if (ssm != null)
646           {
647             structfile = ssm.findFileForPDBId(structid);
648           }
649         }
650         if (structfile != null && structfile.equals(structFilename))
651         {
652           return av;
653         }
654       }
655     }
656     return null;
657   }
658 }