JAL-3070 pull up generic methods for an automatic alignment analysis web service...
[jalview.git] / src / jalview / project / Jalview2XML.java
index 74b6bf0..d5f6a5d 100644 (file)
@@ -38,7 +38,10 @@ import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
+import jalview.datamodel.DBRefEntry;
+import jalview.datamodel.GeneLocus;
 import jalview.datamodel.GraphLine;
+import jalview.datamodel.HiddenMarkovModel;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.Point;
 import jalview.datamodel.RnaViewerModel;
@@ -58,8 +61,6 @@ import jalview.gui.AlignmentPanel;
 import jalview.gui.AppVarna;
 import jalview.gui.ChimeraViewFrame;
 import jalview.gui.Desktop;
-import jalview.gui.FeatureRenderer;
-import jalview.gui.Jalview2XML_V1;
 import jalview.gui.JvOptionPane;
 import jalview.gui.OOMWarning;
 import jalview.gui.PCAPanel;
@@ -69,8 +70,10 @@ import jalview.gui.StructureViewer;
 import jalview.gui.StructureViewer.ViewerType;
 import jalview.gui.StructureViewerBase;
 import jalview.gui.TreePanel;
+import jalview.io.BackupFiles;
 import jalview.io.DataSourceType;
 import jalview.io.FileFormat;
+import jalview.io.HMMFile;
 import jalview.io.NewickFile;
 import jalview.math.Matrix;
 import jalview.math.MatrixI;
@@ -92,6 +95,7 @@ import jalview.util.matcher.Condition;
 import jalview.viewmodel.AlignmentViewport;
 import jalview.viewmodel.PCAModel;
 import jalview.viewmodel.ViewportRanges;
+import jalview.viewmodel.seqfeatures.FeatureRendererModel;
 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
 import jalview.ws.jws2.Jws2Discoverer;
@@ -212,6 +216,8 @@ public class Jalview2XML
 
   private static final String RNA_PREFIX = "rna_";
 
+  private static final String HMMER_PREFIX = "hmmer_";
+
   private static final String UTF_8 = "UTF-8";
 
   /**
@@ -551,24 +557,30 @@ public class Jalview2XML
   public void saveState(File statefile)
   {
     FileOutputStream fos = null;
+
     try
     {
+
       fos = new FileOutputStream(statefile);
+
       JarOutputStream jout = new JarOutputStream(fos);
       saveState(jout);
+      fos.close();
 
     } catch (Exception e)
     {
+      Cache.log.error("Couln't write Jalview state to " + statefile, e);
       // TODO: inform user of the problem - they need to know if their data was
       // not saved !
       if (errorMessage == null)
       {
-        errorMessage = "Couldn't write Jalview Archive to output file '"
+        errorMessage = "Did't write Jalview Archive to output file '"
                 + statefile + "' - See console error log for details";
       }
       else
       {
-        errorMessage += "(output file was '" + statefile + "')";
+        errorMessage += "(Didn't write Jalview Archive to output file '"
+                + statefile + ")";
       }
       e.printStackTrace();
     } finally
@@ -738,7 +750,11 @@ public class Jalview2XML
   {
     try
     {
-      FileOutputStream fos = new FileOutputStream(jarFile);
+      // create backupfiles object and get new temp filename destination
+      BackupFiles backupfiles = new BackupFiles(jarFile);
+      FileOutputStream fos = new FileOutputStream(
+              backupfiles.getTempFilePath());
+
       JarOutputStream jout = new JarOutputStream(fos);
       List<AlignFrame> frames = new ArrayList<>();
 
@@ -760,7 +776,12 @@ public class Jalview2XML
       }
       ;
       jout.close();
-      return true;
+      boolean success = true;
+
+      backupfiles.setWriteSuccess(success);
+      success = backupfiles.rollBackupsAndRenameTempFile();
+
+      return success;
     } catch (Exception ex)
     {
       errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
@@ -1035,6 +1056,9 @@ public class Jalview2XML
         jseq.getFeatures().add(features);
       }
 
+      /*
+       * save PDB entries for sequence
+       */
       if (jdatasq.getAllPDBEntries() != null)
       {
         Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
@@ -1127,6 +1151,11 @@ public class Jalview2XML
 
       saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
 
+      if (jds.hasHMMProfile())
+      {
+        saveHmmerProfile(jout, jseq, jds);
+      }
+
       // jms.addJSeq(jseq);
       object.getJSeq().add(jseq);
     }
@@ -1484,11 +1513,14 @@ public class Jalview2XML
       view.setFollowHighlight(av.isFollowHighlight());
       view.setFollowSelection(av.followSelection);
       view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
+      view.setShowComplementFeatures(av.isShowComplementFeatures());
+      view.setShowComplementFeaturesOnTop(
+              av.isShowComplementFeaturesOnTop());
       if (av.getFeaturesDisplayed() != null)
       {
         FeatureSettings fs = new FeatureSettings();
 
-        FeatureRenderer fr = ap.getSeqPanel().seqCanvas
+        FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
                 .getFeatureRenderer();
         String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
 
@@ -1671,7 +1703,39 @@ public class Jalview2XML
     }
     return object;
   }
+  /**
+   * Saves the HMMER profile associated with the sequence as a file in the jar,
+   * in HMMER format, and saves the name of the file as a child element of the
+   * XML sequence element
+   * 
+   * @param jout
+   * @param xmlSeq
+   * @param seq
+   */
+  protected void saveHmmerProfile(JarOutputStream jout, JSeq xmlSeq,
+          SequenceI seq)
+  {
+    HiddenMarkovModel profile = seq.getHMM();
+    if (profile == null)
+    {
+      warn("Want to save HMM profile for " + seq.getName()
+              + " but none found");
+      return;
+    }
+    HMMFile hmmFile = new HMMFile(profile);
+    String hmmAsString = hmmFile.print();
+    String jarEntryName = HMMER_PREFIX + nextCounter();
+    try
+    {
+      writeJarEntry(jout, jarEntryName, hmmAsString.getBytes());
+      xmlSeq.setHmmerProfile(jarEntryName);
+    } catch (IOException e)
+    {
+      warn("Error saving HMM profile: " + e.getMessage());
+    }
+  }
 
+    
   /**
    * Writes PCA viewer attributes and computed values to an XML model object and
    * adds it to the JalviewModel. Any exceptions are reported by logging.
@@ -2065,9 +2129,9 @@ public class Jalview2XML
       }
       else if (!matchedFile.equals(pdbentry.getFile()))
       {
-        Cache.log.warn(
-                "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
-                        + pdbentry.getFile());
+         Cache.log.warn(
+                  "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
+                          + pdbentry.getFile());
       }
       // record the
       // file so we
@@ -2382,7 +2446,7 @@ public class Jalview2XML
           argList = parmSet.getArguments();
           parmSet = null;
         }
-        AAConSettings settings = new AAConSettings(
+        AutoCalcSetting settings = new AAConSettings(
                 calcIdParam.isAutoUpdate(), service, parmSet, argList);
         av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
                 calcIdParam.isNeedsUpdate());
@@ -2490,21 +2554,29 @@ public class Jalview2XML
         parentseq = jds;
       }
     }
+
+    /*
+     * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
+     */
     if (dbrefs != null)
     {
       for (int d = 0; d < dbrefs.length; d++)
       {
         DBRef dbref = new DBRef();
-        dbref.setSource(dbrefs[d].getSource());
-        dbref.setVersion(dbrefs[d].getVersion());
-        dbref.setAccessionId(dbrefs[d].getAccessionId());
-        if (dbrefs[d].hasMap())
+        DBRefEntry dbRefEntry = dbrefs[d];
+        dbref.setSource(dbRefEntry.getSource());
+        dbref.setVersion(dbRefEntry.getVersion());
+        dbref.setAccessionId(dbRefEntry.getAccessionId());
+        if (dbRefEntry instanceof GeneLocus)
+        {
+          dbref.setLocus(true);
+        }
+        if (dbRefEntry.hasMap())
         {
-          Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
+          Mapping mp = createVamsasMapping(dbRefEntry.getMap(), parentseq,
                   jds, recurse);
           dbref.setMapping(mp);
         }
-        // vamsasSeq.addDBRef(dbref);
         vamsasSeq.getDBRef().add(dbref);
       }
     }
@@ -2882,16 +2954,7 @@ public class Jalview2XML
       ex.printStackTrace(System.err);
       if (attemptversion1parse)
       {
-        // Is Version 1 Jar file?
-        try
-        {
-          af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
-        } catch (Exception ex2)
-        {
-          System.err.println("Exception whilst loading as jalviewXMLV1:");
-          ex2.printStackTrace();
-          af = null;
-        }
+        // used to attempt to parse as V1 castor-generated xml
       }
       if (Desktop.instance != null)
       {
@@ -3144,25 +3207,25 @@ public class Jalview2XML
    * @param prefix
    *          a prefix for the temporary file name, must be at least three
    *          characters long
-   * @param origFile
+   * @param suffixModel
    *          null or original file - so new file can be given the same suffix
    *          as the old one
    * @return
    */
   protected String copyJarEntry(jarInputStreamProvider jprovider,
-          String jarEntryName, String prefix, String origFile)
+          String jarEntryName, String prefix, String suffixModel)
   {
     BufferedReader in = null;
     PrintWriter out = null;
     String suffix = ".tmp";
-    if (origFile == null)
+    if (suffixModel == null)
     {
-      origFile = jarEntryName;
+      suffixModel = jarEntryName;
     }
-    int sfpos = origFile.lastIndexOf(".");
-    if (sfpos > -1 && sfpos < (origFile.length() - 3))
+    int sfpos = suffixModel.lastIndexOf(".");
+    if (sfpos > -1 && sfpos < (suffixModel.length() - 1))
     {
-      suffix = "." + origFile.substring(sfpos + 1);
+      suffix = "." + suffixModel.substring(sfpos + 1);
     }
     try
     {
@@ -3567,6 +3630,18 @@ public class Jalview2XML
             }
           }
         }
+
+        /*
+         * load any HMMER profile
+         */
+        // TODO fix this
+
+        String hmmJarFile = jseqs.get(i).getHmmerProfile();
+        if (hmmJarFile != null && jprovider != null)
+        {
+          loadHmmerProfile(jprovider, hmmJarFile, al.getSequenceAt(i));
+        }
+
       }
     } // end !multipleview
 
@@ -3853,7 +3928,7 @@ public class Jalview2XML
           }
           else
           {
-            cs = ColourSchemeProperty.getColourScheme(al,
+            cs = ColourSchemeProperty.getColourScheme(null, al,
                     jGroup.getColour());
           }
         }
@@ -4041,6 +4116,31 @@ public class Jalview2XML
   }
 
   /**
+   * Loads a HMMER profile from a file stored in the project, and associates it
+   * with the specified sequence
+   * 
+   * @param jprovider
+   * @param hmmJarFile
+   * @param seq
+   */
+  protected void loadHmmerProfile(jarInputStreamProvider jprovider,
+          String hmmJarFile, SequenceI seq)
+  {
+    try
+    {
+      String hmmFile = copyJarEntry(jprovider, hmmJarFile, "hmm", null);
+      HMMFile parser = new HMMFile(hmmFile, DataSourceType.FILE);
+      HiddenMarkovModel hmmModel = parser.getHMM();
+      hmmModel = new HiddenMarkovModel(hmmModel, seq);
+      seq.setHMM(hmmModel);
+    } catch (IOException e)
+    {
+      warn("Error loading HMM profile for " + seq.getName() + ": "
+              + e.getMessage());
+    }
+  }
+
+  /**
    * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
    * panel is restored from separate jar entries, two (gapped and trimmed) per
    * sequence and secondary structure.
@@ -4181,10 +4281,8 @@ public class Jalview2XML
           // TODO: verify 'associate with all views' works still
           tp.getTreeCanvas().setViewport(av); // af.viewport;
           tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
-          // FIXME: should we use safeBoolean here ?
-          tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
-
         }
+        tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
         if (tp == null)
         {
           warn("There was a problem recovering stored Newick tree: \n"
@@ -4430,7 +4528,7 @@ public class Jalview2XML
      */
     String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
     chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
-            "chimera", null);
+            "chimera", ".py");
 
     Set<Entry<File, StructureData>> fileData = data.getFileData()
             .entrySet();
@@ -4516,7 +4614,7 @@ public class Jalview2XML
           String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
           filedat = oldFiles.get(new File(reformatedOldFilename));
         }
-        newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
+        newFileLoc.append(Platform.escapeBackslashes(filedat.getFilePath()));
         pdbfilenames.add(filedat.getFilePath());
         pdbids.add(filedat.getPdbId());
         seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
@@ -4967,25 +5065,27 @@ public class Jalview2XML
       }
       else
       {
-        cs = ColourSchemeProperty.getColourScheme(al, view.getBgColour());
+        cs = ColourSchemeProperty.getColourScheme(af.getViewport(), al,
+                view.getBgColour());
       }
     }
 
+    /*
+     * turn off 'alignment colour applies to all groups'
+     * while restoring global colour scheme
+     */
+    viewport.setColourAppliesToAllGroups(false);
     viewport.setGlobalColourScheme(cs);
     viewport.getResidueShading().setThreshold(pidThreshold,
             view.isIgnoreGapsinConsensus());
     viewport.getResidueShading()
             .setConsensus(viewport.getSequenceConsensusHash());
-    viewport.setColourAppliesToAllGroups(false);
-
     if (safeBoolean(view.isConservationSelected()) && cs != null)
     {
       viewport.getResidueShading()
               .setConservationInc(safeInt(view.getConsThreshold()));
     }
-
     af.changeColour(cs);
-
     viewport.setColourAppliesToAllGroups(true);
 
     viewport
@@ -5003,11 +5103,14 @@ public class Jalview2XML
     viewport.setShowNPFeats(safeBoolean(view.isShowNPfeatureTooltip()));
     viewport.setShowGroupConsensus(view.isShowGroupConsensus());
     viewport.setShowGroupConservation(view.isShowGroupConservation());
+    viewport.setShowComplementFeatures(view.isShowComplementFeatures());
+    viewport.setShowComplementFeaturesOnTop(
+            view.isShowComplementFeaturesOnTop());
 
     // recover feature settings
     if (jm.getFeatureSettings() != null)
     {
-      FeatureRenderer fr = af.alignPanel.getSeqPanel().seqCanvas
+      FeatureRendererModel fr = af.alignPanel.getSeqPanel().seqCanvas
               .getFeatureRenderer();
       FeaturesDisplayed fdi;
       viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
@@ -5061,7 +5164,8 @@ public class Jalview2XML
           float min = safeFloat(safeFloat(setting.getMin()));
           float max = setting.getMax() == null ? 1f
                   : setting.getMax().floatValue();
-          FeatureColourI gc = new FeatureColour(minColour, maxColour,
+          FeatureColourI gc = new FeatureColour(maxColour, minColour,
+                  maxColour,
                   noValueColour, min, max);
           if (setting.getAttributeName().size() > 0)
           {
@@ -5106,7 +5210,7 @@ public class Jalview2XML
         }
         else
         {
-          featureOrder.put(featureType, new Float(
+          featureOrder.put(featureType, Float.valueOf(
                   fs / jm.getFeatureSettings().getSetting().size()));
         }
         if (safeBoolean(setting.isDisplay()))
@@ -5118,7 +5222,7 @@ public class Jalview2XML
       for (int gs = 0; gs < jm.getFeatureSettings().getGroup().size(); gs++)
       {
         Group grp = jm.getFeatureSettings().getGroup().get(gs);
-        fgtable.put(grp.getName(), new Boolean(grp.isDisplay()));
+        fgtable.put(grp.getName(), Boolean.valueOf(grp.isDisplay()));
       }
       // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
       // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
@@ -5263,7 +5367,7 @@ public class Jalview2XML
     else
     {
       cs = new AnnotationColourGradient(matchedAnnotation,
-              ColourSchemeProperty.getColourScheme(al,
+              ColourSchemeProperty.getColourScheme(af.getViewport(), al,
                       viewAnnColour.getColourScheme()),
               safeInt(viewAnnColour.getAboveThreshold()));
     }
@@ -5424,10 +5528,10 @@ public class Jalview2XML
     String id = object.getViewport().get(0).getSequenceSetId();
     if (skipList.containsKey(id))
     {
-      if (Cache.log != null && Cache.log.isDebugEnabled())
-      {
-        Cache.log.debug("Skipping seuqence set id " + id);
-      }
+       if (Cache.log != null && Cache.log.isDebugEnabled())
+        {
+          Cache.log.debug("Skipping seuqence set id " + id);
+        }
       return true;
     }
     return false;
@@ -5791,13 +5895,29 @@ public class Jalview2XML
     return datasetId;
   }
 
+  /**
+   * Add any saved DBRefEntry's to the sequence. An entry flagged as 'locus' is
+   * constructed as a special subclass GeneLocus.
+   * 
+   * @param datasetSequence
+   * @param sequence
+   */
   private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
   {
     for (int d = 0; d < sequence.getDBRef().size(); d++)
     {
       DBRef dr = sequence.getDBRef().get(d);
-      jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
-              dr.getSource(), dr.getVersion(), dr.getAccessionId());
+      DBRefEntry entry;
+      if (dr.isLocus())
+      {
+        entry = new GeneLocus(dr.getSource(), dr.getVersion(),
+                dr.getAccessionId());
+      }
+      else
+      {
+        entry = new DBRefEntry(dr.getSource(), dr.getVersion(),
+                dr.getAccessionId());
+      }
       if (dr.getMapping() != null)
       {
         entry.setMap(addMapping(dr.getMapping()));
@@ -5829,15 +5949,16 @@ public class Jalview2XML
     jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
             fto, m.getMapFromUnit().intValue(),
             m.getMapToUnit().intValue());
-    // if (m.getMappingChoice() != null)
-    // {
-    // MappingChoice mc = m.getMappingChoice();
+
+    /*
+     * (optional) choice of dseqFor or Sequence
+     */
     if (m.getDseqFor() != null)
     {
       String dsfor = m.getDseqFor();
       if (seqRefIds.containsKey(dsfor))
       {
-        /**
+        /*
          * recover from hash
          */
         jmap.setTo(seqRefIds.get(dsfor));
@@ -5847,9 +5968,9 @@ public class Jalview2XML
         frefedSequence.add(newMappingRef(dsfor, jmap));
       }
     }
-    else
+    else if (m.getSequence() != null)
     {
-      /**
+      /*
        * local sequence definition
        */
       Sequence ms = m.getSequence();
@@ -5884,7 +6005,6 @@ public class Jalview2XML
         jmap.setTo(djs);
         incompleteSeqs.put(sqid, djs);
         seqRefIds.put(sqid, djs);
-
       }
       jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
       addDBRefs(djs, ms);
@@ -6068,7 +6188,7 @@ public class Jalview2XML
       }
       else
       {
-        Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
+          Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
       }
     }
   }
@@ -6542,7 +6662,7 @@ public class Jalview2XML
         maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
       } catch (Exception e)
       {
-        Cache.log.warn("Couldn't parse out graduated feature color.", e);
+          Cache.log.warn("Couldn't parse out graduated feature color.", e);
       }
   
       NoValueColour noCol = colourModel.getNoValueColour();
@@ -6555,7 +6675,7 @@ public class Jalview2XML
         noValueColour = maxcol;
       }
   
-      colour = new FeatureColour(mincol, maxcol, noValueColour,
+      colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
               safeFloat(colourModel.getMin()),
               safeFloat(colourModel.getMax()));
       final List<String> attributeName = colourModel.getAttributeName();