all alignment sequences associated with a dataset sequence must have start-end update...
[jalview.git] / src / jalview / ws / DBRefFetcher.java
index 4b7c07e..73d106a 100644 (file)
@@ -19,6 +19,7 @@
 package jalview.ws;\r
 \r
 import jalview.analysis.AlignSeq;\r
+import jalview.bin.Cache;\r
 import jalview.datamodel.AlignmentI;\r
 import jalview.datamodel.DBRefEntry;\r
 import jalview.datamodel.DBRefSource;\r
@@ -59,6 +60,7 @@ public class DBRefFetcher implements Runnable
   StringBuffer sbuffer = new StringBuffer();\r
 \r
   boolean running = false;\r
+\r
   /**\r
    * picr client instance\r
    */\r
@@ -72,39 +74,45 @@ public class DBRefFetcher implements Runnable
 \r
   SequenceFetcher sfetcher;\r
 \r
+  private SequenceI[] alseqs;\r
+\r
   public DBRefFetcher()\r
   {\r
   }\r
 \r
   /**\r
-   * Creates a new SequenceFeatureFetcher object and fetches from the\r
-   * currently selected set of databases.\r
+   * Creates a new SequenceFeatureFetcher object and fetches from the currently\r
+   * selected set of databases.\r
    * \r
    * @param seqs\r
-   *                fetch references for these sequences\r
+   *          fetch references for these sequences\r
    * @param af\r
-   *                the parent alignframe for progress bar monitoring.\r
+   *          the parent alignframe for progress bar monitoring.\r
    */\r
   public DBRefFetcher(SequenceI[] seqs, AlignFrame af)\r
   {\r
     this(seqs, af, null);\r
   }\r
+\r
   /**\r
-   * Creates a new SequenceFeatureFetcher object and fetches from the\r
-   * currently selected set of databases.\r
+   * Creates a new SequenceFeatureFetcher object and fetches from the currently\r
+   * selected set of databases.\r
    * \r
    * @param seqs\r
-   *                fetch references for these sequences\r
+   *          fetch references for these sequences\r
    * @param af\r
-   *                the parent alignframe for progress bar monitoring.\r
-   * @param sources array of database source strings to query references from\r
+   *          the parent alignframe for progress bar monitoring.\r
+   * @param sources\r
+   *          array of database source strings to query references from\r
    */\r
   public DBRefFetcher(SequenceI[] seqs, AlignFrame af, String[] sources)\r
   {\r
     this.af = af;\r
+    alseqs = new SequenceI[seqs.length];\r
     SequenceI[] ds = new SequenceI[seqs.length];\r
     for (int i = 0; i < seqs.length; i++)\r
     {\r
+      alseqs[i] = seqs[i];\r
       if (seqs[i].getDatasetSequence() != null)\r
         ds[i] = seqs[i].getDatasetSequence();\r
       else\r
@@ -113,11 +121,13 @@ public class DBRefFetcher implements Runnable
     this.dataset = ds;\r
     // TODO Jalview 2.5 lots of this code should be in the gui package!\r
     sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);\r
-    if (sources==null)\r
+    if (sources == null)\r
     {\r
       // af.featureSettings_actionPerformed(null);\r
-      String[] defdb=null,otherdb = sfetcher.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);\r
-      Vector selsources = new Vector(), dasselsrc= (af.featureSettings!=null) ? af.featureSettings.getSelectedSources()\r
+      String[] defdb = null, otherdb = sfetcher\r
+              .getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);\r
+      Vector selsources = new Vector(), dasselsrc = (af.featureSettings != null) ? af.featureSettings\r
+              .getSelectedSources()\r
               : new jalview.gui.DasSourceBrowser().getSelectedSources();\r
       Enumeration en = dasselsrc.elements();\r
       while (en.hasMoreElements())\r
@@ -126,12 +136,14 @@ public class DBRefFetcher implements Runnable
         selsources.addElement(src.getNickname());\r
       }\r
       int osel = 0;\r
-      for (int o=0;otherdb!=null && o<otherdb.length;o++)\r
+      for (int o = 0; otherdb != null && o < otherdb.length; o++)\r
       {\r
         if (!selsources.contains(otherdb[o]))\r
         {\r
           otherdb[o] = null;\r
-        } else {\r
+        }\r
+        else\r
+        {\r
           osel++;\r
         }\r
       }\r
@@ -144,45 +156,56 @@ public class DBRefFetcher implements Runnable
       {\r
         defdb = DBRefSource.PROTEINDBS;\r
       }\r
-      // append the selected sequence sources to the default dbs \r
-      dbSources = new String[defdb.length+osel];\r
+      // append the selected sequence sources to the default dbs\r
+      dbSources = new String[defdb.length + osel];\r
       System.arraycopy(defdb, 0, dbSources, 0, defdb.length);\r
-      for (int o=0,op=defdb.length; otherdb!=null && o<otherdb.length; o++)\r
+      for (int o = 0, op = defdb.length; otherdb != null\r
+              && o < otherdb.length; o++)\r
       {\r
-        if (otherdb[o]!=null)\r
+        if (otherdb[o] != null)\r
         {\r
           dbSources[op++] = otherdb[o];\r
         }\r
       }\r
-    } else {\r
-      // we assume the caller knows what they're doing and ensured that all the db source names are valid\r
+    }\r
+    else\r
+    {\r
+      // we assume the caller knows what they're doing and ensured that all the\r
+      // db source names are valid\r
       dbSources = sources;\r
     }\r
   }\r
+\r
   /**\r
-   * retrieve all the das sequence sources and add them to the list of db sources to retrieve from \r
+   * retrieve all the das sequence sources and add them to the list of db\r
+   * sources to retrieve from\r
    */\r
   public void appendAllDasSources()\r
   {\r
     if (dbSources == null)\r
     {\r
-      dbSources = new String[] {};\r
+      dbSources = new String[]\r
+      {};\r
     }\r
     // append additional sources\r
-    String[] otherdb = sfetcher.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);\r
-    if (otherdb!=null && otherdb.length>0)\r
+    String[] otherdb = sfetcher\r
+            .getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);\r
+    if (otherdb != null && otherdb.length > 0)\r
     {\r
-      String[] newsrc = new String[dbSources.length+otherdb.length];\r
-      System.arraycopy(dbSources, 0, newsrc,0,dbSources.length);\r
-      System.arraycopy(otherdb, 0, newsrc,dbSources.length, otherdb.length);\r
+      String[] newsrc = new String[dbSources.length + otherdb.length];\r
+      System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);\r
+      System\r
+              .arraycopy(otherdb, 0, newsrc, dbSources.length,\r
+                      otherdb.length);\r
       dbSources = newsrc;\r
     }\r
   }\r
+\r
   /**\r
    * start the fetcher thread\r
    * \r
    * @param waitTillFinished\r
-   *                true to block until the fetcher has finished\r
+   *          true to block until the fetcher has finished\r
    */\r
   public void fetchDBRefs(boolean waitTillFinished)\r
   {\r
@@ -209,9 +232,9 @@ public class DBRefFetcher implements Runnable
    * could be either seq name or dbref id\r
    * \r
    * @param seq\r
-   *                SequenceI\r
+   *          SequenceI\r
    * @param key\r
-   *                String\r
+   *          String\r
    */\r
   void addSeqId(SequenceI seq, String key)\r
   {\r
@@ -254,8 +277,13 @@ public class DBRefFetcher implements Runnable
     running = true;\r
     long startTime = System.currentTimeMillis();\r
     af.setProgressBar("Fetching db refs", startTime);\r
-    try {\r
-      picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator().getAccessionMapperPort(); \r
+    try\r
+    {\r
+      if (Cache.getDefault("DBREFFETCH_USEPICR", false))\r
+      {\r
+        picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()\r
+                .getAccessionMapperPort();\r
+      }\r
     } catch (Exception e)\r
     {\r
       System.err.println("Couldn't locate PICR service instance.\n");\r
@@ -304,10 +332,10 @@ public class DBRefFetcher implements Runnable
         {\r
           // Still queries to make for current seqIndex\r
           StringBuffer queryString = new StringBuffer("");\r
-          int numq=0,nqSize = (maxqlen > queries.size()) ? queries.size()\r
-                  : maxqlen;\r
-          \r
-          while (queries.size()>0 && numq < nqSize)\r
+          int numq = 0, nqSize = (maxqlen > queries.size()) ? queries\r
+                  .size() : maxqlen;\r
+\r
+          while (queries.size() > 0 && numq < nqSize)\r
           {\r
             String query = (String) queries.elementAt(0);\r
             if (dbsource.isValidReference(query))\r
@@ -326,7 +354,9 @@ public class DBRefFetcher implements Runnable
           {\r
             if (jalview.bin.Cache.log.isDebugEnabled())\r
             {\r
-              jalview.bin.Cache.log.debug("Querying "+dbsource.getDbName()+" with : '"+queryString.toString()+"'");\r
+              jalview.bin.Cache.log.debug("Querying "\r
+                      + dbsource.getDbName() + " with : '"\r
+                      + queryString.toString() + "'");\r
             }\r
             retrieved = dbsource.getSequenceRecords(queryString.toString());\r
           } catch (Exception ex)\r
@@ -353,7 +383,7 @@ public class DBRefFetcher implements Runnable
                     { dbSources[db] }); // jalview.datamodel.DBRefSource.UNIPROT\r
             // });\r
             // check for existing dbrefs to use\r
-            if (uprefs != null && uprefs.length>0)\r
+            if (uprefs != null && uprefs.length > 0)\r
             {\r
               for (int j = 0; j < uprefs.length; j++)\r
               {\r
@@ -372,25 +402,39 @@ public class DBRefFetcher implements Runnable
               {\r
                 String token = st.nextToken();\r
                 UPEntry[] presp = null;\r
-                try {\r
-                  presp=picrClient.getUPIForAccession(token, null, picrClient.getMappedDatabaseNames(), null, true);\r
-                } catch (Exception e) {\r
-                  System.err.println("Exception with Picr for '"+token+"'\n");\r
-                  e.printStackTrace();\r
+                if (picrClient != null)\r
+                {\r
+                  // resolve the string against PICR to recover valid IDs\r
+                  try\r
+                  {\r
+                    presp = picrClient\r
+                            .getUPIForAccession(token, null, picrClient\r
+                                    .getMappedDatabaseNames(), null, true);\r
+                  } catch (Exception e)\r
+                  {\r
+                    System.err.println("Exception with Picr for '" + token\r
+                            + "'\n");\r
+                    e.printStackTrace();\r
+                  }\r
                 }\r
-                if (presp!=null && presp.length>0)\r
+                if (presp != null && presp.length > 0)\r
                 {\r
-                  for (int id=0;id<presp.length; id++)\r
+                  for (int id = 0; id < presp.length; id++)\r
                   {\r
-                    // construct sequences from response if sequences are present, and do a transferReferences\r
+                    // construct sequences from response if sequences are\r
+                    // present, and do a transferReferences\r
                     // otherwise transfer non sequence x-references directly.\r
                   }\r
-                  System.out.println("Validated ID against PICR... (for what its worth):"+token);\r
+                  System.out\r
+                          .println("Validated ID against PICR... (for what its worth):"\r
+                                  + token);\r
                   addSeqId(sequence, token);\r
                   queries.addElement(token.toUpperCase());\r
-                } else {\r
-                  //if ()\r
-                  //System.out.println("Not querying source with token="+token+"\n");\r
+                }\r
+                else\r
+                {\r
+                  // if ()\r
+                  // System.out.println("Not querying source with token="+token+"\n");\r
                   addSeqId(sequence, token);\r
                   queries.addElement(token.toUpperCase());\r
                 }\r
@@ -431,13 +475,15 @@ public class DBRefFetcher implements Runnable
           AlignmentI retrievedAl) // File\r
   // file)\r
   {\r
-\r
     if (retrievedAl == null || retrievedAl.getHeight() == 0)\r
     {\r
       return;\r
     }\r
-    SequenceI[] retrieved = recoverDbSequences(retrievedAl.getSequencesArray());\r
+    SequenceI[] retrieved = recoverDbSequences(retrievedAl\r
+            .getSequencesArray());\r
     SequenceI sequence = null;\r
+    boolean transferred = false;\r
+    StringBuffer messages = new StringBuffer();\r
 \r
     // Vector entries = new Uniprot().getUniprotEntries(file);\r
 \r
@@ -530,11 +576,11 @@ public class DBRefFetcher implements Runnable
           absStart = nonGapped.indexOf(entrySeq);\r
           if (absStart == -1)\r
           { // verification failed.\r
-            sbuffer.append(sequence.getName()\r
+            messages.append(sequence.getName()\r
                     + " SEQUENCE NOT %100 MATCH \n");\r
             continue;\r
           }\r
-\r
+          transferred = true;\r
           sbuffer.append(sequence.getName() + " HAS " + absStart\r
                   + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");\r
           //\r
@@ -554,6 +600,7 @@ public class DBRefFetcher implements Runnable
         }\r
         else\r
         {\r
+          transferred = true;\r
           // update start and end of local sequence to place it in entry's\r
           // reference frame.\r
           // apply identity map map from whole of local sequence to matching\r
@@ -565,8 +612,9 @@ public class DBRefFetcher implements Runnable
           // absStart+sequence.getStart()+entrySeq.length()-1},\r
           // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);\r
           // relocate local features for updated start\r
-          if (updateRefFrame && sequence.getSequenceFeatures() != null)\r
-          {\r
+          if (updateRefFrame) {\r
+            if (sequence.getSequenceFeatures() != null)\r
+            {\r
             SequenceFeature[] sf = sequence.getSequenceFeatures();\r
             int start = sequence.getStart();\r
             int end = sequence.getEnd();\r
@@ -581,6 +629,7 @@ public class DBRefFetcher implements Runnable
                 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);\r
               }\r
             }\r
+            }\r
           }\r
         }\r
 \r
@@ -595,39 +644,64 @@ public class DBRefFetcher implements Runnable
           // finally, update local sequence reference frame if we're allowed\r
           sequence.setStart(absStart);\r
           sequence.setEnd(absEnd);\r
+          // search for alignment sequences to update coordinate frame for\r
+          for (int alsq = 0; alsq<alseqs.length; alsq++)\r
+          {\r
+            if (alseqs[alsq].getDatasetSequence()==sequence)\r
+            {\r
+              String ngAlsq = AlignSeq.extractGaps("-. ",\r
+                      alseqs[alsq].getSequenceAsString()).toUpperCase();\r
+              int oldstrt = alseqs[alsq].getStart();\r
+              alseqs[alsq].setStart(sequence.getSequenceAsString().toUpperCase().indexOf(ngAlsq)+sequence.getStart());\r
+              if (oldstrt != alseqs[alsq].getStart()) {\r
+                alseqs[alsq].setEnd(ngAlsq.length()+alseqs[alsq].getStart()-1);\r
+              }\r
+            }\r
+          }\r
+          // TODO:  search for all other references to this dataset sequence, and update start/end\r
+          // TODO: update all AlCodonMappings which involve this alignment sequence (e.g. Q30167 cdna translation from exon2 product (vamsas demo)\r
         }\r
         // and remove it from the rest\r
         // TODO: decide if we should remove annotated sequence from set\r
         sdataset.remove(sequence);\r
-        // TODO: should we make a note of sequences that have received new DB ids, so we can query all enabled DAS servers for them ?\r
+        // TODO: should we make a note of sequences that have received new DB\r
+        // ids, so we can query all enabled DAS servers for them ?\r
       }\r
     }\r
+    if (!transferred)\r
+    {\r
+      // report the ID/sequence mismatches\r
+      sbuffer.append(messages);\r
+    }\r
   }\r
 \r
   /**\r
    * loop thru and collect additional sequences in Map.\r
+   * \r
    * @param sequencesArray\r
    * @return\r
    */\r
   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)\r
   {\r
     Vector nseq = new Vector();\r
-    for (int i=0;sequencesArray!=null && i<sequencesArray.length;i++)\r
+    for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)\r
     {\r
       nseq.addElement(sequencesArray[i]);\r
       DBRefEntry dbr[] = sequencesArray[i].getDBRef();\r
       jalview.datamodel.Mapping map = null;\r
-      for (int r=0;(dbr!=null) && r<dbr.length; r++) {\r
-        if ((map=dbr[r].getMap())!=null)\r
+      for (int r = 0; (dbr != null) && r < dbr.length; r++)\r
+      {\r
+        if ((map = dbr[r].getMap()) != null)\r
         {\r
-          if (!nseq.contains(map.getTo()))\r
+          if (map.getTo() != null && !nseq.contains(map.getTo()))\r
           {\r
             nseq.addElement(map.getTo());\r
           }\r
         }\r
       }\r
     }\r
-    if (nseq.size()>0) {\r
+    if (nseq.size() > 0)\r
+    {\r
       sequencesArray = new SequenceI[nseq.size()];\r
       nseq.toArray(sequencesArray);\r
     }\r