JAL-3210 Improvements to eclipse detection. New src tree and SwingJS updated from...
[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.SequenceI;
30 import jalview.gui.CutAndPasteTransfer;
31 import jalview.gui.Desktop;
32 import jalview.gui.FeatureSettings;
33 import jalview.gui.IProgressIndicator;
34 import jalview.gui.OOMWarning;
35 import jalview.gui.Preferences;
36 import jalview.util.DBRefUtils;
37 import jalview.util.MessageManager;
38 import jalview.ws.seqfetcher.DbSourceProxy;
39
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Enumeration;
43 import java.util.Hashtable;
44 import java.util.List;
45 import java.util.StringTokenizer;
46 import java.util.Vector;
47
48 import uk.ac.ebi.picr.model.UPEntry;
49 import uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator;
50
51 /**
52  * Implements a runnable for validating a sequence against external databases
53  * and then propagating references and features onto the sequence(s)
54  * 
55  * @author $author$
56  * @version $Revision$
57  */
58 public class DBRefFetcher implements Runnable
59 {
60   private static final String NEWLINE = System.lineSeparator();
61
62   public static final String TRIM_RETRIEVED_SEQUENCES = "TRIM_FETCHED_DATASET_SEQS";
63
64   public interface FetchFinishedListenerI
65   {
66     void finished();
67   }
68
69   SequenceI[] dataset;
70
71   IProgressIndicator progressWindow;
72
73   CutAndPasteTransfer output = new CutAndPasteTransfer();
74
75   boolean running = false;
76
77   /**
78    * picr client instance
79    */
80   uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
81
82   // This will be a collection of Vectors of sequenceI refs.
83   // The key will be the seq name or accession id of the seq
84   Hashtable<String, Vector<SequenceI>> seqRefs;
85
86   DbSourceProxy[] dbSources;
87
88   SequenceFetcher sfetcher;
89
90   private List<FetchFinishedListenerI> listeners;
91
92   private SequenceI[] alseqs;
93
94   /*
95    * when true - retrieved sequences will be trimmed to cover longest derived
96    * alignment sequence
97    */
98   private boolean trimDsSeqs = true;
99
100   /**
101    * Creates a new DBRefFetcher object and fetches from the currently selected
102    * set of databases, if this is null then it fetches based on feature settings
103    * 
104    * @param seqs
105    *          fetch references for these SequenceI array
106    * @param progressIndicatorFrame
107    *          the frame for progress bar monitoring
108    * @param sources
109    *          array of DbSourceProxy to query references form
110    * @param featureSettings
111    *          FeatureSettings to get alternative DbSourceProxy from
112    * @param isNucleotide
113    *          indicates if the array of SequenceI are Nucleotides or not
114    */
115   public DBRefFetcher(SequenceI[] seqs,
116           IProgressIndicator progressIndicatorFrame,
117           DbSourceProxy[] sources, FeatureSettings featureSettings,
118           boolean isNucleotide)
119   {
120     listeners = new ArrayList<>();
121     this.progressWindow = progressIndicatorFrame;
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       {
129         ds[i] = seqs[i].getDatasetSequence();
130       }
131       else
132       {
133         ds[i] = seqs[i];
134       }
135     }
136     this.dataset = ds;
137     // TODO Jalview 2.5 lots of this code should be in the gui package!
138     sfetcher = SequenceFetcher.getInstance();
139     // set default behaviour for transferring excess sequence data to the
140     // dataset
141     trimDsSeqs = Cache.getDefault(TRIM_RETRIEVED_SEQUENCES, true);
142     if (sources == null)
143     {
144       setDatabaseSources(featureSettings, isNucleotide);
145     }
146     else
147     {
148       // we assume the caller knows what they're doing and ensured that all the
149       // db source names are valid
150       dbSources = sources;
151     }
152   }
153
154   /**
155    * Helper method to configure the list of database sources to query
156    * 
157    * @param featureSettings
158    * @param forNucleotide
159    */
160   void setDatabaseSources(FeatureSettings featureSettings,
161           boolean forNucleotide)
162   {
163     // af.featureSettings_actionPerformed(null);
164     String[] defdb = null;
165     List<DbSourceProxy> selsources = new ArrayList<>();
166     // select appropriate databases based on alignFrame context.
167     if (forNucleotide)
168     {
169       defdb = DBRefSource.DNACODINGDBS;
170     }
171     else
172     {
173       defdb = DBRefSource.PROTEINDBS;
174     }
175     List<DbSourceProxy> srces = new ArrayList<>();
176     for (String ddb : defdb)
177     {
178       List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
179       if (srcesfordb != null)
180       {
181         for (DbSourceProxy src : srcesfordb)
182         {
183           if (!srces.contains(src))
184           {
185             srces.addAll(srcesfordb);
186           }
187         }
188       }
189     }
190     // append the PDB data source, since it is 'special', catering for both
191     // nucleotide and protein
192     // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
193
194     srces.addAll(selsources);
195     dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
196   }
197
198   /**
199    * Constructor with only sequences provided
200    * 
201    * @param sequences
202    */
203   public DBRefFetcher(SequenceI[] sequences)
204   {
205     this(sequences, null, null, null, false);
206   }
207
208   /**
209    * Add a listener to be notified when sequence fetching is complete
210    * 
211    * @param l
212    */
213   public void addListener(FetchFinishedListenerI l)
214   {
215     listeners.add(l);
216   }
217
218   /**
219    * start the fetcher thread
220    * 
221    * @param waitTillFinished
222    *          true to block until the fetcher has finished
223    */
224   public void fetchDBRefs(boolean waitTillFinished)
225   {
226     // TODO can we not simply write
227     // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
228
229     Thread thread = new Thread(this);
230     thread.start();
231     running = true;
232
233     if (waitTillFinished)
234     {
235       while (running)
236       {
237         try
238         {
239           Thread.sleep(500);
240         } catch (Exception ex)
241         {
242         }
243       }
244     }
245   }
246
247   /**
248    * The sequence will be added to a vector of sequences belonging to key which
249    * could be either seq name or dbref id
250    * 
251    * @param seq
252    *          SequenceI
253    * @param key
254    *          String
255    */
256   void addSeqId(SequenceI seq, String key)
257   {
258     key = key.toUpperCase();
259
260     Vector<SequenceI> seqs;
261     if (seqRefs.containsKey(key))
262     {
263       seqs = seqRefs.get(key);
264
265       if (seqs != null && !seqs.contains(seq))
266       {
267         seqs.addElement(seq);
268       }
269       else if (seqs == null)
270       {
271         seqs = new Vector<>();
272         seqs.addElement(seq);
273       }
274
275     }
276     else
277     {
278       seqs = new Vector<>();
279       seqs.addElement(seq);
280     }
281
282     seqRefs.put(key, seqs);
283   }
284
285   /**
286    * DOCUMENT ME!
287    */
288   @Override
289   public void run()
290   {
291     if (dbSources == null)
292     {
293       throw new Error(MessageManager
294               .getString("error.implementation_error_must_init_dbsources"));
295     }
296     running = true;
297     long startTime = System.currentTimeMillis();
298     if (progressWindow != null)
299     {
300       progressWindow.setProgressBar(
301               MessageManager.getString("status.fetching_db_refs"),
302               startTime);
303     }
304     try
305     {
306       if (Cache.getDefault(Preferences.DBREFFETCH_USEPICR, false))
307       {
308         picrClient = new AccessionMapperServiceLocator()
309                 .getAccessionMapperPort();
310       }
311     } catch (Exception e)
312     {
313       System.err.println("Couldn't locate PICR service instance.\n");
314       e.printStackTrace();
315     }
316
317     Vector<SequenceI> sdataset = new Vector<>(
318             Arrays.asList(dataset));
319     List<String> warningMessages = new ArrayList<>();
320
321     int db = 0;
322     while (sdataset.size() > 0 && db < dbSources.length)
323     {
324       int maxqlen = 1; // default number of queries made at one time
325       System.out.println("Verifying against " + dbSources[db].getDbName());
326
327       // iterate through db for each remaining un-verified sequence
328       SequenceI[] currSeqs = new SequenceI[sdataset.size()];
329       sdataset.copyInto(currSeqs);// seqs that are to be validated against
330       // dbSources[db]
331       Vector<String> queries = new Vector<>(); // generated queries curSeq
332       seqRefs = new Hashtable<>();
333
334       int seqIndex = 0;
335
336       DbSourceProxy dbsource = dbSources[db];
337       // for moment, we dumbly iterate over all retrieval sources for a
338       // particular database
339       // TODO: introduce multithread multisource queries and logic to remove a
340       // query from other sources if any source for a database returns a
341       // record
342       maxqlen = dbsource.getMaximumQueryCount();
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;
351           int nqSize = (maxqlen > queries.size()) ? queries.size()
352                   : maxqlen;
353
354           while (queries.size() > 0 && numq < nqSize)
355           {
356             String query = queries.elementAt(0);
357             if (dbsource.isValidReference(query))
358             {
359               queryString.append(
360                       (numq == 0) ? "" : dbsource.getAccessionSeparator());
361               queryString.append(query);
362               numq++;
363             }
364             // remove the extracted query string
365             queries.removeElementAt(0);
366           }
367           // make the queries and process the response
368           AlignmentI retrieved = null;
369           try
370           {
371             if (Cache.log.isDebugEnabled())
372             {
373               Cache.log.debug("Querying " + dbsource.getDbName()
374                       + " with : '" + queryString.toString() + "'");
375             }
376             retrieved = dbsource.getSequenceRecords(queryString.toString());
377           } catch (Exception ex)
378           {
379             ex.printStackTrace();
380           } catch (OutOfMemoryError err)
381           {
382             new OOMWarning("retrieving database references ("
383                     + queryString.toString() + ")", err);
384           }
385           if (retrieved != null)
386           {
387             transferReferences(sdataset, dbsource.getDbSource(), retrieved,
388                     trimDsSeqs, warningMessages);
389           }
390         }
391         else
392         {
393           // make some more strings for use as queries
394           for (int i = 0; (seqIndex < dataset.length)
395                   && (i < 50); seqIndex++, i++)
396           {
397             SequenceI sequence = dataset[seqIndex];
398             List<DBRefEntry> uprefs = DBRefUtils
399                     .selectRefs(sequence.getDBRefs(), new String[]
400                     { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
401             // });
402             // check for existing dbrefs to use
403             if (uprefs != null && uprefs.size() > 0)
404             {
405               for (int j = 0, n = uprefs.size(); j < n; j++)
406               {
407                 DBRefEntry upref = uprefs.get(j);
408                 addSeqId(sequence, upref.getAccessionId());
409                 queries.addElement(
410                         upref.getAccessionId().toUpperCase());
411               }
412             }
413             else
414             {
415               // generate queries from sequence ID string
416               StringTokenizer st = new StringTokenizer(sequence.getName(),
417                       "|");
418               while (st.hasMoreTokens())
419               {
420                 String token = st.nextToken();
421                 UPEntry[] presp = null;
422                 if (picrClient != null)
423                 {
424                   // resolve the string against PICR to recover valid IDs
425                   try
426                   {
427                     presp = picrClient.getUPIForAccession(token, null,
428                             picrClient.getMappedDatabaseNames(), null,
429                             true);
430                   } catch (Exception e)
431                   {
432                     System.err.println(
433                             "Exception with Picr for '" + token + "'\n");
434                     e.printStackTrace();
435                   }
436                 }
437                 if (presp != null && presp.length > 0)
438                 {
439                   for (int id = 0; id < presp.length; id++)
440                   {
441                     // construct sequences from response if sequences are
442                     // present, and do a transferReferences
443                     // otherwise transfer non sequence x-references directly.
444                   }
445                   System.out.println(
446                           "Validated ID against PICR... (for what its worth):"
447                                   + token);
448                   addSeqId(sequence, token);
449                   queries.addElement(token.toUpperCase());
450                 }
451                 else
452                 {
453                   // if ()
454                   // System.out.println("Not querying source with
455                   // token="+token+"\n");
456                   addSeqId(sequence, token);
457                   queries.addElement(token.toUpperCase());
458                 }
459               }
460             }
461           }
462         }
463       }
464       // advance to next database
465       db++;
466     } // all databases have been queried
467     if (!warningMessages.isEmpty())
468     {
469       StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
470       sb.append(MessageManager
471               .getString("label.your_sequences_have_been_verified"));
472       for (String msg : warningMessages)
473       {
474         sb.append(msg).append(NEWLINE);
475       }
476       output.setText(sb.toString());
477
478       Desktop.addInternalFrame(output,
479               MessageManager.getString("label.sequences_updated"), 600,
480               300);
481       // The above is the dataset, we must now find out the index
482       // of the viewed sequence
483
484     }
485     if (progressWindow != null)
486     {
487       progressWindow.setProgressBar(
488               MessageManager.getString("label.dbref_search_completed"),
489               startTime);
490     }
491
492     for (FetchFinishedListenerI listener : listeners)
493     {
494       listener.finished();
495     }
496     running = false;
497   }
498
499   /**
500    * Verify local sequences in seqRefs against the retrieved sequence database
501    * records. Returns true if any sequence was modified as a result (start/end
502    * changed and/or sequence enlarged), else false.
503    * 
504    * @param sdataset
505    *          dataset sequences we are retrieving for
506    * @param dbSource
507    *          database source we are retrieving from
508    * @param retrievedAl
509    *          retrieved sequences as alignment
510    * @param trimDatasetSeqs
511    *          if true, sequences will not be enlarged to match longer retrieved
512    *          sequences, only their start/end adjusted
513    * @param warningMessages
514    *          a list of messages to add to
515    */
516   boolean transferReferences(Vector<SequenceI> sdataset, String dbSource,
517           AlignmentI retrievedAl, boolean trimDatasetSeqs,
518           List<String> warningMessages)
519   {
520     // System.out.println("trimming ? " + trimDatasetSeqs);
521     if (retrievedAl == null || retrievedAl.getHeight() == 0)
522     {
523       return false;
524     }
525
526     boolean modified = false;
527     SequenceI[] retrieved = recoverDbSequences(
528             retrievedAl.getSequencesArray());
529     SequenceI sequence = null;
530
531     for (SequenceI retrievedSeq : retrieved)
532     {
533       // Work out which sequences this sequence matches,
534       // taking into account all accessionIds and names in the file
535       Vector<SequenceI> sequenceMatches = new Vector<>();
536       // look for corresponding accession ids
537       List<DBRefEntry> entryRefs = DBRefUtils
538               .selectRefs(retrievedSeq.getDBRefs(), new String[]
539               { dbSource });
540       if (entryRefs == null)
541       {
542         System.err
543                 .println("Dud dbSource string ? no entryrefs selected for "
544                         + dbSource + " on " + retrievedSeq.getName());
545         continue;
546       }
547       for (int j = 0, n = entryRefs.size(); j < n; j++)
548       {
549         DBRefEntry ref = entryRefs.get(j);
550         String accessionId = ref.getAccessionId();
551         // match up on accessionId
552         if (seqRefs.containsKey(accessionId.toUpperCase()))
553         {
554           Vector<SequenceI> seqs = seqRefs.get(accessionId);
555           for (int jj = 0; jj < seqs.size(); jj++)
556           {
557             sequence = seqs.elementAt(jj);
558             if (!sequenceMatches.contains(sequence))
559             {
560               sequenceMatches.addElement(sequence);
561             }
562           }
563         }
564       }
565       if (sequenceMatches.isEmpty())
566       {
567         // failed to match directly on accessionId==query so just compare all
568         // sequences to entry
569         Enumeration<String> e = seqRefs.keys();
570         while (e.hasMoreElements())
571         {
572           Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
573           if (sqs != null && sqs.size() > 0)
574           {
575             Enumeration<SequenceI> sqe = sqs.elements();
576             while (sqe.hasMoreElements())
577             {
578               sequenceMatches.addElement(sqe.nextElement());
579             }
580           }
581         }
582       }
583       // look for corresponding names
584       // this is uniprot specific ?
585       // could be useful to extend this so we try to find any 'significant'
586       // information in common between two sequence objects.
587       /*
588        * List<DBRefEntry> entryRefs =
589        * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
590        * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
591        * name = entry.getName().elementAt(j).toString(); if
592        * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
593        * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
594        * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
595        * sequenceMatches.addElement(sequence); } } } }
596        */
597       // sequenceMatches now contains the set of all sequences associated with
598       // the returned db record
599       final String retrievedSeqString = retrievedSeq.getSequenceAsString();
600       String entrySeq = retrievedSeqString.toUpperCase();
601       for (int m = 0; m < sequenceMatches.size(); m++)
602       {
603         sequence = sequenceMatches.elementAt(m);
604         // only update start and end positions and shift features if there are
605         // no existing references
606         // TODO: test for legacy where uniprot or EMBL refs exist but no
607         // mappings are made (but content matches retrieved set)
608         boolean updateRefFrame = sequence.getDBRefs() == null
609                 || sequence.getDBRefs().size() == 0;
610         // TODO:
611         // verify sequence against the entry sequence
612
613         Mapping mp;
614         final int sequenceStart = sequence.getStart();
615
616         boolean remoteEnclosesLocal = false;
617         String nonGapped = AlignSeq
618                 .extractGaps("-. ", sequence.getSequenceAsString())
619                 .toUpperCase();
620         int absStart = entrySeq.indexOf(nonGapped);
621         if (absStart == -1)
622         {
623           // couldn't find local sequence in sequence from database, so check if
624           // the database sequence is a subsequence of local sequence
625           absStart = nonGapped.indexOf(entrySeq);
626           if (absStart == -1)
627           {
628             // verification failed. couldn't find any relationship between
629             // entrySeq and local sequence
630             // messages suppressed as many-to-many matches are confusing
631             // String msg = sequence.getName()
632             // + " Sequence not 100% match with "
633             // + retrievedSeq.getName();
634             // addWarningMessage(warningMessages, msg);
635             continue;
636           }
637           /*
638            * retrieved sequence is a proper subsequence of local sequence
639            */
640           String msg = sequence.getName() + " has " + absStart
641                   + " prefixed residues compared to "
642                   + retrievedSeq.getName();
643           addWarningMessage(warningMessages, msg);
644
645           /*
646            * So create a mapping to the external entry from the matching region of 
647            * the local sequence, and leave local start/end untouched. 
648            */
649           mp = new Mapping(null,
650                   new int[]
651                   { sequenceStart + absStart,
652                       sequenceStart + absStart + entrySeq.length() - 1 },
653                   new int[]
654                   { retrievedSeq.getStart(),
655                       retrievedSeq.getStart() + entrySeq.length() - 1 },
656                   1, 1);
657           updateRefFrame = false;
658         }
659         else
660         {
661           /*
662            * local sequence is a subsequence of (or matches) retrieved sequence
663            */
664           remoteEnclosesLocal = true;
665           mp = null;
666
667           if (updateRefFrame)
668           {
669             /*
670              * relocate existing sequence features by offset
671              */
672             int startShift = absStart - sequenceStart + 1;
673             if (startShift != 0)
674             {
675               modified |= sequence.getFeatures().shiftFeatures(1,
676                       startShift);
677             }
678           }
679         }
680
681         System.out.println("Adding dbrefs to " + sequence.getName()
682                 + " from " + dbSource + " sequence : "
683                 + retrievedSeq.getName());
684         sequence.transferAnnotation(retrievedSeq, mp);
685
686         absStart += retrievedSeq.getStart();
687         int absEnd = absStart + nonGapped.length() - 1;
688         if (!trimDatasetSeqs)
689         {
690           /*
691            * update start position and/or expand to longer retrieved sequence
692            */
693           if (!retrievedSeqString.equals(sequence.getSequenceAsString())
694                   && remoteEnclosesLocal)
695           {
696             sequence.setSequence(retrievedSeqString);
697             modified = true;
698             addWarningMessage(warningMessages,
699                     "Sequence for " + sequence.getName() + " expanded from "
700                             + retrievedSeq.getName());
701           }
702           if (sequence.getStart() != retrievedSeq.getStart())
703           {
704             sequence.setStart(retrievedSeq.getStart());
705             modified = true;
706             if (absStart != sequenceStart)
707             {
708               addWarningMessage(warningMessages,
709                       "Start/end position for " + sequence.getName()
710                               + " updated from " + retrievedSeq.getName());
711             }
712           }
713         }
714         if (updateRefFrame)
715         {
716           // finally, update local sequence reference frame if we're allowed
717           if (trimDatasetSeqs)
718           {
719             // just fix start/end
720             if (sequence.getStart() != absStart
721                     || sequence.getEnd() != absEnd)
722             {
723               sequence.setStart(absStart);
724               sequence.setEnd(absEnd);
725               modified = true;
726               addWarningMessage(warningMessages,
727                       "Start/end for " + sequence.getName()
728                               + " updated from " + retrievedSeq.getName());
729             }
730           }
731           // search for alignment sequences to update coordinate frame for
732           for (int alsq = 0; alsq < alseqs.length; alsq++)
733           {
734             if (alseqs[alsq].getDatasetSequence() == sequence)
735             {
736               String ngAlsq = AlignSeq
737                       .extractGaps("-. ",
738                               alseqs[alsq].getSequenceAsString())
739                       .toUpperCase();
740               int oldstrt = alseqs[alsq].getStart();
741               alseqs[alsq].setStart(sequence.getSequenceAsString()
742                       .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
743               if (oldstrt != alseqs[alsq].getStart())
744               {
745                 alseqs[alsq].setEnd(
746                         ngAlsq.length() + alseqs[alsq].getStart() - 1);
747                 modified = true;
748               }
749             }
750           }
751           // TODO: search for all other references to this dataset sequence, and
752           // update start/end
753           // TODO: update all AlCodonMappings which involve this alignment
754           // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
755           // demo)
756         }
757         // and remove it from the rest
758         // TODO: decide if we should remove annotated sequence from set
759         sdataset.remove(sequence);
760       }
761     }
762     return modified;
763   }
764
765   /**
766    * Adds the message to the list unless it already contains it
767    * 
768    * @param messageList
769    * @param msg
770    */
771   void addWarningMessage(List<String> messageList, String msg)
772   {
773     if (!messageList.contains(msg))
774     {
775       messageList.add(msg);
776     }
777   }
778
779   /**
780    * loop thru and collect additional sequences in Map.
781    * 
782    * @param sequencesArray
783    * @return
784    */
785   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
786   {
787         int n;
788         if (sequencesArray == null || (n = sequencesArray.length) == 0)
789   {
790     return sequencesArray;
791   }
792     ArrayList<SequenceI> nseq = new ArrayList<>();
793     for (int i = 0;i < n; i++)
794     {
795       nseq.add(sequencesArray[i]);
796       List<DBRefEntry> dbr = sequencesArray[i].getDBRefs();
797       Mapping map = null;
798       if (dbr != null)
799       {
800         for (int r = 0, rn = dbr.size(); r < rn; r++)
801         {
802           if ((map = dbr.get(r).getMap()) != null)
803           {
804             if (map.getTo() != null && !nseq.contains(map.getTo()))
805             {
806               nseq.add(map.getTo());
807             }
808           }  
809         }
810       }
811     }
812     // BH 2019.01.25 question here if this is the right logic. Return the original if nothing found?
813     if (nseq.size() > 0)
814     {
815       return nseq.toArray(new SequenceI[nseq.size()]);
816     }
817     return sequencesArray;
818   }
819 }