Merge JAL-2136_phyre2_integration to develop
[jalview.git] / src / jalview / io / AnnotationFile.java
index 9a4071d..b72184b 100755 (executable)
@@ -28,14 +28,19 @@ import jalview.datamodel.Annotation;
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.GraphLine;
 import jalview.datamodel.HiddenSequences;
+import jalview.datamodel.PDBEntry;
+import jalview.datamodel.PDBEntry.Type;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
+import jalview.gui.Desktop;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ColourSchemeProperty;
+import jalview.structure.StructureSelectionManager;
 import jalview.util.ColorUtils;
 
 import java.awt.Color;
 import java.io.BufferedReader;
+import java.io.File;
 import java.io.FileReader;
 import java.io.InputStreamReader;
 import java.io.StringReader;
@@ -687,21 +692,41 @@ public class AnnotationFile
   public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
           String file, DataSourceType sourceType)
   {
+    baseUri = "";
     BufferedReader in = null;
     try
     {
       if (sourceType == DataSourceType.FILE)
       {
         in = new BufferedReader(new FileReader(file));
+        baseUri = new File(file).getParent();
+        if (baseUri == null)
+        {
+          baseUri = "";
+        }
+        else
+        {
+          baseUri += "/";
+        }
       }
       else if (sourceType == DataSourceType.URL)
       {
         URL url = new URL(file);
         in = new BufferedReader(new InputStreamReader(url.openStream()));
+        String bs = url.toExternalForm();
+        baseUri = bs.substring(0, bs.indexOf(url.getHost())
+                + url.getHost().length());
+        baseUri += url.toURI().getPath();
+        if (baseUri.lastIndexOf("/") > -1)
+        {
+          baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
+        }
       }
       else if (sourceType == DataSourceType.PASTE)
       {
         in = new BufferedReader(new StringReader(file));
+        // TODO - support mimencoded PDBs for a paste.. ?
+        baseUri = "";
       }
       else if (sourceType == DataSourceType.CLASSLOADER)
       {
@@ -709,6 +734,8 @@ public class AnnotationFile
         if (is != null)
         {
           in = new BufferedReader(new java.io.InputStreamReader(is));
+          // TODO: this probably doesn't work for classloader - needs a test
+          baseUri = new File("/" + file).getParent() + "/";
         }
       }
       if (in != null)
@@ -734,7 +761,14 @@ public class AnnotationFile
 
   String lastread = "";
 
-  private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
+  /**
+   * used for resolving absolute references to resources relative to
+   * annotationFile location
+   */
+  String baseUri = "";
+
+  private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
+          STRUCTMODEL = "STRUCTMODEL";
 
   public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
           BufferedReader in) throws Exception
@@ -980,7 +1014,54 @@ public class AnnotationFile
           modified = true;
           continue;
         }
-
+        else if (token.equalsIgnoreCase(STRUCTMODEL))
+        {
+          boolean failedtoadd = true;
+          // expect
+          // STRUCTMODEL <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile>
+          // <Confidence> <%.I.D>
+          // <MatchStart> <MatchEnd> <Coverage> [<Other Information>]
+          String querySeqId = !st.hasMoreTokens() ? "" : st.nextToken();
+          SequenceI querySeq = al.findName(querySeqId);
+          if (st.hasMoreTokens()) {
+            refSeq = al.findName(refSeqId = st.nextToken());
+            if (refSeq == null)
+            {
+              System.err.println("Couldn't locate " + refSeqId
+                      + " in the alignment for STRUCTMODEL");
+              refSeqId = null;
+            }
+            else
+            {
+              String tempId = st.nextToken();
+              String fastaMapping = st.nextToken();
+              String confidence = !st.hasMoreTokens() ? "" : 100
+                      * Double.valueOf(st.nextToken()) + "";
+              String pid = !st.hasMoreTokens() ? "" : st.nextToken();
+              String alignRange = !st.hasMoreTokens() ? "" : st.nextToken()
+                      + "-" + st.nextToken();
+              String otherInfo = !st.hasMoreTokens() ? "" : st.nextToken();
+              String coverage = "";
+              if (add_structmodel(al, querySeq, refSeq, tempId,
+                      fastaMapping,
+                      alignRange, coverage,
+                      confidence, pid, otherInfo))
+              {
+                failedtoadd = false;
+              }
+            }
+          }
+          if (failedtoadd)
+          {
+            System.err
+                    .println("Need <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile> <Confidence> <%.I.D> <MatchStart> <MatchEnd> <Coverage> [<Other Information>] as tab separated fields after"
+                            + STRUCTMODEL
+                            + ".\nNote: other information could be provided in html format ");
+          } else {
+            modified = true;
+          }
+          continue;
+        }
         // Parse out the annotation row
         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
         label = st.nextToken();
@@ -1180,6 +1261,103 @@ public class AnnotationFile
     return modified;
   }
 
+  /**
+   * resolve a structural model and generate and add an alignment sequence for
+   * it
+   * 
+   * @param refSeq2
+   * @param tempId
+   * @param urlToModel
+   * @param urlToPairwise
+   * @return true if model and sequence was added
+   */
+  private boolean add_structmodel(AlignmentI al, SequenceI querySequence,
+          SequenceI templateSeq,
+          String modelFile, String fastaFile, String aRange,
+          String coverage, String confidence,
+          String pid, String otherInfo)
+  {
+    String warningMessage = null;
+    boolean added = false;
+    try {
+      String structureModelFile = resolveAbsolute(modelFile);
+      String fastaMappingFile = resolveAbsolute(fastaFile.replaceAll(
+              ".fasta.jal", ".fasta"));
+      // System.out.println("Model File >> " + structureModelFile);
+      // System.out.println("Fasta File >> " + fastaMappingFile);
+      PDBEntry phyre2PDBEntry = new PDBEntry(modelFile, null, Type.FILE,
+              structureModelFile);
+      String phyre2ModelDesc = generatePhyre2InfoHTMLTable(aRange,
+              coverage, confidence, pid, otherInfo);
+      phyre2PDBEntry.setProperty("PHYRE2_MODEL_INFO", phyre2ModelDesc);
+      templateSeq.getDatasetSequence().addPDBId(phyre2PDBEntry);
+      if (querySequence != null)
+      {
+        querySequence.getDatasetSequence().addPDBId(phyre2PDBEntry);
+      }
+      StructureSelectionManager ssm = StructureSelectionManager
+              .getStructureSelectionManager(Desktop.instance);
+      ssm.registerPhyre2Template(structureModelFile, fastaMappingFile);
+      added = true;
+
+    } catch (Exception x)
+    {
+      warningMessage = x.toString();
+    } finally {
+      if (warningMessage !=null)
+      {
+        System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
+      }
+    }
+    return added;
+  }
+
+  private String generatePhyre2InfoHTMLTable(String aRange,
+          String coverage, String confidence, String pid, String otherInfo)
+  {
+    StringBuilder phyre2InfoBuilder = new StringBuilder();
+    phyre2InfoBuilder.append("<html><table border=\"1\" width=100%>");
+    phyre2InfoBuilder
+            .append("<tr><td colspan=\"2\"><strong>Phyre2 Template Info</strong></td></tr>");
+    if (aRange != null && !aRange.isEmpty())
+    {
+      phyre2InfoBuilder.append("<tr><td>").append("Aligned range")
+              .append("</td><td>").append(aRange).append("</td></tr>");
+    }
+    if (coverage != null && !coverage.isEmpty())
+    {
+      phyre2InfoBuilder.append("<tr><td>").append("Coverage")
+              .append("</td><td>").append(coverage).append("</td></tr>");
+    }
+    if (confidence != null && !confidence.isEmpty())
+    {
+      phyre2InfoBuilder.append("<tr><td>").append("Confidence")
+              .append("</td><td>").append(confidence).append("</td></tr>");
+    }
+    if (pid != null && !pid.isEmpty())
+    {
+      phyre2InfoBuilder.append("<tr><td>").append("%.i.d")
+              .append("</td><td>").append(pid).append("</td></tr>");
+    }
+    if (otherInfo != null && !otherInfo.isEmpty())
+    {
+      phyre2InfoBuilder.append("<tr><td>").append("Other information")
+              .append("</td><td>").append(otherInfo).append("</td></tr>");
+    }
+    phyre2InfoBuilder.append("</table></html>");
+    return phyre2InfoBuilder.toString();
+  }
+
+  private String resolveAbsolute(String relURI)
+  {
+    if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
+            || "".equals(baseUri) || relURI.startsWith(baseUri))
+    {
+      return relURI;
+    }
+    return baseUri + relURI;
+  }
+
   private void parseHideCols(ColumnSelection colSel, String nextToken)
   {
     StringTokenizer inval = new StringTokenizer(nextToken, ",");