apply version 2.7 copyright
[jalview.git] / src / jalview / ws / DBRefFetcher.java
index 5400d4e..d235410 100644 (file)
@@ -1,24 +1,24 @@
 /*\r
- * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)\r
- * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle\r
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)\r
+ * Copyright (C) 2011 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle\r
  * \r
- * This program is free software; you can redistribute it and/or\r
- * modify it under the terms of the GNU General Public License\r
- * as published by the Free Software Foundation; either version 2\r
- * of the License, or (at your option) any later version.\r
+ * This file is part of Jalview.\r
  * \r
- * This program is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
+ * Jalview is free software: you can redistribute it and/or\r
+ * modify it under the terms of the GNU General Public License \r
+ * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r
  * \r
- * You should have received a copy of the GNU General Public License\r
- * along with this program; if not, write to the Free Software\r
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\r
+ * Jalview is distributed in the hope that it will be useful, but \r
+ * WITHOUT ANY WARRANTY; without even the implied warranty \r
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR \r
+ * PURPOSE.  See the GNU General Public License for more details.\r
+ * \r
+ * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.\r
  */\r
 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
@@ -31,6 +31,7 @@ import jalview.gui.Desktop;
 import jalview.gui.IProgressIndicator;\r
 import jalview.gui.OOMWarning;\r
 \r
+import java.lang.reflect.Array;\r
 import java.util.Enumeration;\r
 import java.util.Hashtable;\r
 import java.util.StringTokenizer;\r
@@ -58,6 +59,7 @@ public class DBRefFetcher implements Runnable
   StringBuffer sbuffer = new StringBuffer();\r
 \r
   boolean running = false;\r
+\r
   /**\r
    * picr client instance\r
    */\r
@@ -71,39 +73,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
@@ -112,12 +120,14 @@ 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
-              : new jalview.gui.DasSourceBrowser().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() : new jalview.gui.DasSourceBrowser()\r
+              .getSelectedSources();\r
       Enumeration en = dasselsrc.elements();\r
       while (en.hasMoreElements())\r
       {\r
@@ -125,12 +135,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
@@ -143,45 +155,54 @@ 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.arraycopy(otherdb, 0, newsrc, dbSources.length, 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
@@ -208,9 +229,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
@@ -253,8 +274,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
@@ -303,10 +329,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
@@ -325,7 +351,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
@@ -352,14 +380,12 @@ 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
                 addSeqId(sequence, uprefs[j].getAccessionId());\r
-                queries\r
-                        .addElement(uprefs[j].getAccessionId()\r
-                                .toUpperCase());\r
+                queries.addElement(uprefs[j].getAccessionId().toUpperCase());\r
               }\r
             }\r
             else\r
@@ -371,25 +397,42 @@ 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,\r
+                                    picrClient.getMappedDatabaseNames(),\r
+                                    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\r
+                          .println("Validated ID against PICR... (for what its worth):"\r
+                                  + token);\r
+                  addSeqId(sequence, token);\r
+                  queries.addElement(token.toUpperCase());\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
-                } else {\r
-                  System.out.println("Not querying source with token="+token+"\n");\r
-                  //addSeqId(sequence, token);\r
-                  //queries.addElement(token.toUpperCase());\r
                 }\r
               }\r
             }\r
@@ -401,11 +444,10 @@ public class DBRefFetcher implements Runnable
     } // all databases have been queries.\r
     if (sbuffer.length() > 0)\r
     {\r
-      output\r
-              .setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"\r
-                      + "altered, most likely the start/end residue will have been updated.\n"\r
-                      + "Save your alignment to maintain the updated id.\n\n"\r
-                      + sbuffer.toString());\r
+      output.setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"\r
+              + "altered, most likely the start/end residue will have been updated.\n"\r
+              + "Save your alignment to maintain the updated id.\n\n"\r
+              + sbuffer.toString());\r
       Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);\r
       // The above is the dataset, we must now find out the index\r
       // of the viewed sequence\r
@@ -428,13 +470,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 = 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
@@ -448,9 +492,16 @@ public class DBRefFetcher implements Runnable
       // taking into account all accessionIds and names in the file\r
       Vector sequenceMatches = new Vector();\r
       // look for corresponding accession ids\r
-      DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(entry\r
-              .getDBRef(), new String[]\r
-      { dbSource });\r
+      DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(\r
+              entry.getDBRef(), new String[]\r
+              { dbSource });\r
+      if (entryRefs == null)\r
+      {\r
+        System.err\r
+                .println("Dud dbSource string ? no entryrefs selected for "\r
+                        + dbSource + " on " + entry.getName());\r
+        continue;\r
+      }\r
       for (int j = 0; j < entryRefs.length; j++)\r
       {\r
         String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();\r
@@ -527,11 +578,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
@@ -551,6 +602,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
@@ -562,20 +614,24 @@ 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
+          if (updateRefFrame)\r
           {\r
-            SequenceFeature[] sf = sequence.getSequenceFeatures();\r
-            int start = sequence.getStart();\r
-            int end = sequence.getEnd();\r
-            int startShift = 1 - absStart - start; // how much the features are\r
-            // to be shifted by\r
-            for (int sfi = 0; sfi < sf.length; sfi++)\r
+            if (sequence.getSequenceFeatures() != null)\r
             {\r
-              if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)\r
+              SequenceFeature[] sf = sequence.getSequenceFeatures();\r
+              int start = sequence.getStart();\r
+              int end = sequence.getEnd();\r
+              int startShift = 1 - absStart - start; // how much the features\r
+                                                     // are\r
+              // to be shifted by\r
+              for (int sfi = 0; sfi < sf.length; sfi++)\r
               {\r
-                // shift feature along by absstart\r
-                sf[sfi].setBegin(sf[sfi].getBegin() + startShift);\r
-                sf[sfi].setEnd(sf[sfi].getEnd() + startShift);\r
+                if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)\r
+                {\r
+                  // shift feature along by absstart\r
+                  sf[sfi].setBegin(sf[sfi].getBegin() + startShift);\r
+                  sf[sfi].setEnd(sf[sfi].getEnd() + startShift);\r
+                }\r
               }\r
             }\r
           }\r
@@ -592,12 +648,74 @@ 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()\r
+                      .toUpperCase().indexOf(ngAlsq)\r
+                      + sequence.getStart());\r
+              if (oldstrt != alseqs[alsq].getStart())\r
+              {\r
+                alseqs[alsq].setEnd(ngAlsq.length()\r
+                        + alseqs[alsq].getStart() - 1);\r
+              }\r
+            }\r
+          }\r
+          // TODO: search for all other references to this dataset sequence, and\r
+          // update start/end\r
+          // TODO: update all AlCodonMappings which involve this alignment\r
+          // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas\r
+          // 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
+    {\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
+      {\r
+        if ((map = dbr[r].getMap()) != null)\r
+        {\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
+    {\r
+      sequencesArray = new SequenceI[nseq.size()];\r
+      nseq.toArray(sequencesArray);\r
+    }\r
+    return sequencesArray;\r
   }\r
 }\r