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