Merge branch 'develop' into JAL-1705_trialMerge
[jalview.git] / src / jalview / ws / DBRefFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.CutAndPasteTransfer;
32 import jalview.gui.Desktop;
33 import jalview.gui.FeatureSettings;
34 import jalview.gui.IProgressIndicator;
35 import jalview.gui.OOMWarning;
36 import jalview.util.MessageManager;
37 import jalview.ws.dbsources.das.api.jalviewSourceI;
38 import jalview.ws.seqfetcher.DbSourceProxy;
39
40 import java.util.ArrayList;
41 import java.util.Enumeration;
42 import java.util.Hashtable;
43 import java.util.List;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
46
47 import uk.ac.ebi.picr.model.UPEntry;
48
49 /**
50  * Implements a runnable for validating a sequence against external databases
51  * and then propagating references and features onto the sequence(s)
52  * 
53  * @author $author$
54  * @version $Revision$
55  */
56 public class DBRefFetcher implements Runnable
57 {
58   SequenceI[] dataset;
59
60   IProgressIndicator progressWindow;
61
62   CutAndPasteTransfer output = new CutAndPasteTransfer();
63
64   StringBuffer sbuffer = new StringBuffer();
65
66   boolean running = false;
67
68   /**
69    * picr client instance
70    */
71   uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
72
73   // /This will be a collection of Vectors of sequenceI refs.
74   // The key will be the seq name or accession id of the seq
75   Hashtable seqRefs;
76
77   DbSourceProxy[] dbSources;
78
79   SequenceFetcher sfetcher;
80
81   private SequenceI[] alseqs;
82
83   /**
84    * when true - retrieved sequences will be trimmed to cover longest derived
85    * alignment sequence
86    */
87   private boolean trimDsSeqs = true;
88
89   public DBRefFetcher()
90   {
91   }
92
93   /**
94    * Creates a new DBRefFetcher object and fetches from the currently selected
95    * set of databases, if this is null then it fetches based on feature settings
96    * 
97    * @param seqs
98    *          fetch references for these SequenceI array
99    * @param progressIndicatorFrame
100    *          the frame for progress bar monitoring
101    * @param sources
102    *          array of DbSourceProxy to query references form
103    * @param featureSettings
104    *          FeatureSettings to get alternative DbSourceProxy from
105    * @param isNucleotide
106    *          indicates if the array of SequenceI are Nucleotides or not
107    */
108   public DBRefFetcher(SequenceI[] seqs,
109           IProgressIndicator progressIndicatorFrame,
110           DbSourceProxy[] sources, FeatureSettings featureSettings, boolean isNucleotide)
111   {
112     this.progressWindow = progressIndicatorFrame;
113     alseqs = new SequenceI[seqs.length];
114     SequenceI[] ds = new SequenceI[seqs.length];
115     for (int i = 0; i < seqs.length; i++)
116     {
117       alseqs[i] = seqs[i];
118       if (seqs[i].getDatasetSequence() != null)
119       {
120         ds[i] = seqs[i].getDatasetSequence();
121       }
122       else
123       {
124         ds[i] = seqs[i];
125       }
126     }
127     this.dataset = ds;
128     // TODO Jalview 2.5 lots of this code should be in the gui package!
129     sfetcher = jalview.gui.SequenceFetcher
130             .getSequenceFetcherSingleton(progressIndicatorFrame);
131     // set default behaviour for transferring excess sequence data to the
132     // dataset
133     trimDsSeqs = Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true);
134     if (sources == null)
135     {
136       // af.featureSettings_actionPerformed(null);
137       String[] defdb = null, otherdb = sfetcher
138               .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
139       List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
140       Vector dasselsrc = (featureSettings != null) ? featureSettings
141               .getSelectedSources() : new jalview.gui.DasSourceBrowser()
142               .getSelectedSources();
143       Enumeration<jalviewSourceI> en = dasselsrc.elements();
144       while (en.hasMoreElements())
145       {
146         jalviewSourceI src = en.nextElement();
147         List<DbSourceProxy> sp = src.getSequenceSourceProxies();
148         if (sp != null)
149         {
150           selsources.addAll(sp);
151           if (sp.size() > 1)
152           {
153             Cache.log.debug("Added many Db Sources for :" + src.getTitle());
154           }
155         }
156       }
157       // select appropriate databases based on alignFrame context.
158       if (isNucleotide)
159       {
160         defdb = DBRefSource.DNACODINGDBS;
161       }
162       else
163       {
164         defdb = DBRefSource.PROTEINDBS;
165       }
166       List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
167       for (String ddb : defdb)
168       {
169         List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
170         if (srcesfordb != null)
171         {
172           srces.addAll(srcesfordb);
173         }
174       }
175
176       // append the selected sequence sources to the default dbs
177       srces.addAll(selsources);
178       dbSources = srces.toArray(new DbSourceProxy[0]);
179     }
180     else
181     {
182       // we assume the caller knows what they're doing and ensured that all the
183       // db source names are valid
184       dbSources = sources;
185     }
186   }
187
188   /**
189    * retrieve all the das sequence sources and add them to the list of db
190    * sources to retrieve from
191    */
192   public void appendAllDasSources()
193   {
194     if (dbSources == null)
195     {
196       dbSources = new DbSourceProxy[0];
197     }
198     // append additional sources
199     DbSourceProxy[] otherdb = sfetcher
200             .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
201     if (otherdb != null && otherdb.length > 0)
202     {
203       DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
204               + otherdb.length];
205       System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
206       System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
207       dbSources = newsrc;
208     }
209   }
210
211   /**
212    * start the fetcher thread
213    * 
214    * @param waitTillFinished
215    *          true to block until the fetcher has finished
216    */
217   public void fetchDBRefs(boolean waitTillFinished)
218   {
219     Thread thread = new Thread(this);
220     thread.start();
221     running = true;
222
223     if (waitTillFinished)
224     {
225       while (running)
226       {
227         try
228         {
229           Thread.sleep(500);
230         } catch (Exception ex)
231         {
232         }
233       }
234     }
235   }
236
237   /**
238    * The sequence will be added to a vector of sequences belonging to key which
239    * could be either seq name or dbref id
240    * 
241    * @param seq
242    *          SequenceI
243    * @param key
244    *          String
245    */
246   void addSeqId(SequenceI seq, String key)
247   {
248     key = key.toUpperCase();
249
250     Vector seqs;
251     if (seqRefs.containsKey(key))
252     {
253       seqs = (Vector) seqRefs.get(key);
254
255       if (seqs != null && !seqs.contains(seq))
256       {
257         seqs.addElement(seq);
258       }
259       else if (seqs == null)
260       {
261         seqs = new Vector();
262         seqs.addElement(seq);
263       }
264
265     }
266     else
267     {
268       seqs = new Vector();
269       seqs.addElement(seq);
270     }
271
272     seqRefs.put(key, seqs);
273   }
274
275   /**
276    * DOCUMENT ME!
277    */
278   @Override
279   public void run()
280   {
281     if (dbSources == null)
282     {
283       throw new Error(
284               MessageManager
285                       .getString("error.implementation_error_must_init_dbsources"));
286     }
287     running = true;
288     long startTime = System.currentTimeMillis();
289     if (progressWindow != null)
290     {
291       progressWindow.setProgressBar(
292               MessageManager.getString("status.fetching_db_refs"),
293             startTime);
294     }
295     try
296     {
297       if (Cache.getDefault("DBREFFETCH_USEPICR", false))
298       {
299         picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
300                 .getAccessionMapperPort();
301       }
302     } catch (Exception e)
303     {
304       System.err.println("Couldn't locate PICR service instance.\n");
305       e.printStackTrace();
306     }
307     int db = 0;
308     Vector sdataset = new Vector();
309     for (int s = 0; s < dataset.length; s++)
310     {
311       sdataset.addElement(dataset[s]);
312     }
313     while (sdataset.size() > 0 && db < dbSources.length)
314     {
315       int maxqlen = 1; // default number of queries made to at one time
316       System.err.println("Verifying against " + dbSources[db].getDbName());
317       boolean dn = false;
318
319       // iterate through db for each remaining un-verified sequence
320       SequenceI[] currSeqs = new SequenceI[sdataset.size()];
321       sdataset.copyInto(currSeqs);// seqs that are to be validated against
322       // dbSources[db]
323       Vector queries = new Vector(); // generated queries curSeq
324       seqRefs = new Hashtable();
325
326       int seqIndex = 0;
327
328       jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
329       {
330         // for moment, we dumbly iterate over all retrieval sources for a
331         // particular database
332         // TODO: introduce multithread multisource queries and logic to remove a
333         // query from other sources if any source for a database returns a
334         // record
335         maxqlen = dbsource.getMaximumQueryCount();
336
337         while (queries.size() > 0 || seqIndex < currSeqs.length)
338         {
339           if (queries.size() > 0)
340           {
341             // Still queries to make for current seqIndex
342             StringBuffer queryString = new StringBuffer("");
343             int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
344                     .size() : maxqlen;
345
346             while (queries.size() > 0 && numq < nqSize)
347             {
348               String query = (String) queries.elementAt(0);
349               if (dbsource.isValidReference(query))
350               {
351                 queryString.append((numq == 0) ? "" : dbsource
352                         .getAccessionSeparator());
353                 queryString.append(query);
354                 numq++;
355               }
356               // remove the extracted query string
357               queries.removeElementAt(0);
358             }
359             // make the queries and process the response
360             AlignmentI retrieved = null;
361             try
362             {
363               if (jalview.bin.Cache.log.isDebugEnabled())
364               {
365                 jalview.bin.Cache.log.debug("Querying "
366                         + dbsource.getDbName() + " with : '"
367                         + queryString.toString() + "'");
368               }
369               retrieved = dbsource.getSequenceRecords(queryString
370                       .toString());
371             } catch (Exception ex)
372             {
373               ex.printStackTrace();
374             } catch (OutOfMemoryError err)
375             {
376               new OOMWarning("retrieving database references ("
377                       + queryString.toString() + ")", err);
378             }
379             if (retrieved != null)
380             {
381               transferReferences(sdataset, dbsource.getDbSource(),
382                       retrieved, trimDsSeqs);
383             }
384           }
385           else
386           {
387             // make some more strings for use as queries
388             for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
389             {
390               SequenceI sequence = dataset[seqIndex];
391               DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
392                       sequence.getDBRefs(),
393                       new String[] { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
394               // });
395               // check for existing dbrefs to use
396               if (uprefs != null && uprefs.length > 0)
397               {
398                 for (int j = 0; j < uprefs.length; j++)
399                 {
400                   addSeqId(sequence, uprefs[j].getAccessionId());
401                   queries.addElement(uprefs[j].getAccessionId()
402                           .toUpperCase());
403                 }
404               }
405               else
406               {
407                 // generate queries from sequence ID string
408                 StringTokenizer st = new StringTokenizer(
409                         sequence.getName(), "|");
410                 while (st.hasMoreTokens())
411                 {
412                   String token = st.nextToken();
413                   UPEntry[] presp = null;
414                   if (picrClient != null)
415                   {
416                     // resolve the string against PICR to recover valid IDs
417                     try
418                     {
419                       presp = picrClient.getUPIForAccession(token, null,
420                               picrClient.getMappedDatabaseNames(), null,
421                               true);
422                     } catch (Exception e)
423                     {
424                       System.err.println("Exception with Picr for '"
425                               + token + "'\n");
426                       e.printStackTrace();
427                     }
428                   }
429                   if (presp != null && presp.length > 0)
430                   {
431                     for (int id = 0; id < presp.length; id++)
432                     {
433                       // construct sequences from response if sequences are
434                       // present, and do a transferReferences
435                       // otherwise transfer non sequence x-references directly.
436                     }
437                     System.out
438                             .println("Validated ID against PICR... (for what its worth):"
439                                     + token);
440                     addSeqId(sequence, token);
441                     queries.addElement(token.toUpperCase());
442                   }
443                   else
444                   {
445                     // if ()
446                     // System.out.println("Not querying source with token="+token+"\n");
447                     addSeqId(sequence, token);
448                     queries.addElement(token.toUpperCase());
449                   }
450                 }
451               }
452             }
453           }
454         }
455       }
456       // advance to next database
457       db++;
458     } // all databases have been queries.
459     if (sbuffer.length() > 0)
460     {
461       output.setText(MessageManager
462               .getString("label.your_sequences_have_been_verified")
463               + sbuffer.toString());
464       Desktop.addInternalFrame(output,
465               MessageManager.getString("label.sequence_names_updated"),
466               600, 300);
467       // The above is the dataset, we must now find out the index
468       // of the viewed sequence
469
470     }
471     if (progressWindow != null)
472     {
473       progressWindow.setProgressBar(
474               MessageManager.getString("label.dbref_search_completed"),
475               startTime);
476       // promptBeforeBlast();
477
478     }
479
480     running = false;
481
482   }
483
484   /**
485    * Verify local sequences in seqRefs against the retrieved sequence database
486    * records.
487    * 
488    * @param trimDatasetSeqs
489    * 
490    */
491   void transferReferences(Vector sdataset, String dbSource,
492           AlignmentI retrievedAl, boolean trimDatasetSeqs) // File
493   // file)
494   {
495     System.out.println("trimming ? " + trimDatasetSeqs);
496     if (retrievedAl == null || retrievedAl.getHeight() == 0)
497     {
498       return;
499     }
500     SequenceI[] retrieved = recoverDbSequences(retrievedAl
501             .getSequencesArray());
502     SequenceI sequence = null;
503     boolean transferred = false;
504     StringBuffer messages = new StringBuffer();
505
506     // Vector entries = new Uniprot().getUniprotEntries(file);
507
508     int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
509     // UniprotEntry entry;
510     for (i = 0; i < iSize; i++)
511     {
512       SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
513
514       // Work out which sequences this sequence matches,
515       // taking into account all accessionIds and names in the file
516       Vector sequenceMatches = new Vector();
517       // look for corresponding accession ids
518       DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
519               entry.getDBRefs(), new String[] { dbSource });
520       if (entryRefs == null)
521       {
522         System.err
523                 .println("Dud dbSource string ? no entryrefs selected for "
524                         + dbSource + " on " + entry.getName());
525         continue;
526       }
527       for (int j = 0; j < entryRefs.length; j++)
528       {
529         String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
530         // match up on accessionId
531         if (seqRefs.containsKey(accessionId.toUpperCase()))
532         {
533           Vector seqs = (Vector) seqRefs.get(accessionId);
534           for (int jj = 0; jj < seqs.size(); jj++)
535           {
536             sequence = (SequenceI) seqs.elementAt(jj);
537             if (!sequenceMatches.contains(sequence))
538             {
539               sequenceMatches.addElement(sequence);
540             }
541           }
542         }
543       }
544       if (sequenceMatches.size() == 0)
545       {
546         // failed to match directly on accessionId==query so just compare all
547         // sequences to entry
548         Enumeration e = seqRefs.keys();
549         while (e.hasMoreElements())
550         {
551           Vector sqs = (Vector) seqRefs.get(e.nextElement());
552           if (sqs != null && sqs.size() > 0)
553           {
554             Enumeration sqe = sqs.elements();
555             while (sqe.hasMoreElements())
556             {
557               sequenceMatches.addElement(sqe.nextElement());
558             }
559           }
560         }
561       }
562       // look for corresponding names
563       // this is uniprot specific ?
564       // could be useful to extend this so we try to find any 'significant'
565       // information in common between two sequence objects.
566       /*
567        * DBRefEntry[] entryRefs =
568        * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
569        * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
570        * name = entry.getName().elementAt(j).toString(); if
571        * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
572        * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
573        * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
574        * sequenceMatches.addElement(sequence); } } } }
575        */
576       // sequenceMatches now contains the set of all sequences associated with
577       // the returned db record
578       String entrySeq = entry.getSequenceAsString().toUpperCase();
579       for (int m = 0; m < sequenceMatches.size(); m++)
580       {
581         sequence = (SequenceI) sequenceMatches.elementAt(m);
582         // only update start and end positions and shift features if there are
583         // no existing references
584         // TODO: test for legacy where uniprot or EMBL refs exist but no
585         // mappings are made (but content matches retrieved set)
586         boolean updateRefFrame = sequence.getDBRefs() == null
587                 || sequence.getDBRefs().length == 0;
588         // TODO:
589         // verify sequence against the entry sequence
590
591         String nonGapped = AlignSeq.extractGaps("-. ",
592                 sequence.getSequenceAsString()).toUpperCase();
593
594         int absStart = entrySeq.indexOf(nonGapped);
595         Mapping mp;
596
597         final int sequenceStart = sequence.getStart();
598         if (absStart == -1)
599         {
600           // Is local sequence contained in dataset sequence?
601           absStart = nonGapped.indexOf(entrySeq);
602           if (absStart == -1)
603           { // verification failed.
604             messages.append(sequence.getName()
605                     + " SEQUENCE NOT %100 MATCH \n");
606             continue;
607           }
608           transferred = true;
609           sbuffer.append(sequence.getName() + " HAS " + absStart
610                   + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
611           //
612           // + " - ANY SEQUENCE FEATURES"
613           // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
614           // absStart = 0;
615           // create valid mapping between matching region of local sequence and
616           // the mapped sequence
617           mp = new Mapping(null, new int[] { sequenceStart + absStart,
618               sequenceStart + absStart + entrySeq.length() - 1 }, new int[]
619           { entry.getStart(), entry.getStart() + entrySeq.length() - 1 },
620                   1, 1);
621           updateRefFrame = false; // mapping is based on current start/end so
622           // don't modify start and end
623         }
624         else
625         {
626           transferred = true;
627           // update start and end of local sequence to place it in entry's
628           // reference frame.
629           // apply identity map map from whole of local sequence to matching
630           // region of database
631           // sequence
632           mp = null; // Mapping.getIdentityMap();
633           // new Mapping(null,
634           // new int[] { absStart+sequence.getStart(),
635           // absStart+sequence.getStart()+entrySeq.length()-1},
636           // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
637           // relocate local features for updated start
638           if (updateRefFrame)
639           {
640             if (sequence.getSequenceFeatures() != null)
641             {
642               SequenceFeature[] sf = sequence.getSequenceFeatures();
643               int start = sequenceStart;
644               int end = sequence.getEnd();
645               int startShift = 1 - absStart - start; // how much the features
646                                                      // are
647               // to be shifted by
648               for (int sfi = 0; sfi < sf.length; sfi++)
649               {
650                 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
651                 {
652                   // shift feature along by absstart
653                   sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
654                   sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
655                 }
656               }
657             }
658           }
659         }
660
661         System.out.println("Adding dbrefs to " + sequence.getName()
662                 + " from " + dbSource + " sequence : " + entry.getName());
663         sequence.transferAnnotation(entry, mp);
664         // unknownSequences.remove(sequence);
665         absStart += entry.getStart();
666         int absEnd = absStart + nonGapped.length() - 1;
667         if (!trimDatasetSeqs)
668         {
669           // insert full length sequence from record
670           sequence.setSequence(entry.getSequenceAsString());
671           sequence.setStart(entry.getStart());
672         }
673         if (updateRefFrame)
674         {
675           // finally, update local sequence reference frame if we're allowed
676           if (trimDatasetSeqs)
677           {
678             // just fix start/end
679             sequence.setStart(absStart);
680             sequence.setEnd(absEnd);
681           }
682           // search for alignment sequences to update coordinate frame for
683           for (int alsq = 0; alsq < alseqs.length; alsq++)
684           {
685             if (alseqs[alsq].getDatasetSequence() == sequence)
686             {
687               String ngAlsq = AlignSeq.extractGaps("-. ",
688                       alseqs[alsq].getSequenceAsString()).toUpperCase();
689               int oldstrt = alseqs[alsq].getStart();
690               alseqs[alsq].setStart(sequence.getSequenceAsString()
691                       .toUpperCase().indexOf(ngAlsq)
692                       + sequence.getStart());
693               if (oldstrt != alseqs[alsq].getStart())
694               {
695                 alseqs[alsq].setEnd(ngAlsq.length()
696                         + alseqs[alsq].getStart() - 1);
697               }
698             }
699           }
700           // TODO: search for all other references to this dataset sequence, and
701           // update start/end
702           // TODO: update all AlCodonMappings which involve this alignment
703           // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
704           // demo)
705         }
706         // and remove it from the rest
707         // TODO: decide if we should remove annotated sequence from set
708         sdataset.remove(sequence);
709         // TODO: should we make a note of sequences that have received new DB
710         // ids, so we can query all enabled DAS servers for them ?
711       }
712     }
713     if (!transferred)
714     {
715       // report the ID/sequence mismatches
716       sbuffer.append(messages);
717     }
718   }
719
720   /**
721    * loop thru and collect additional sequences in Map.
722    * 
723    * @param sequencesArray
724    * @return
725    */
726   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
727   {
728     Vector nseq = new Vector();
729     for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
730     {
731       nseq.addElement(sequencesArray[i]);
732       DBRefEntry dbr[] = sequencesArray[i].getDBRefs();
733       jalview.datamodel.Mapping map = null;
734       for (int r = 0; (dbr != null) && r < dbr.length; r++)
735       {
736         if ((map = dbr[r].getMap()) != null)
737         {
738           if (map.getTo() != null && !nseq.contains(map.getTo()))
739           {
740             nseq.addElement(map.getTo());
741           }
742         }
743       }
744     }
745     if (nseq.size() > 0)
746     {
747       sequencesArray = new SequenceI[nseq.size()];
748       nseq.toArray(sequencesArray);
749     }
750     return sequencesArray;
751   }
752 }