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