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