59ba8a3f21af35149bf8b9bbc3e3289f2ec2ca9b
[jalview.git] / src / jalview / analysis / CrossRef.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.analysis;
22
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.Mapping;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.util.DBRefUtils;
32 import jalview.util.MapList;
33 import jalview.ws.SequenceFetcherFactory;
34 import jalview.ws.seqfetcher.ASequenceFetcher;
35
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
39
40 /**
41  * Functions for cross-referencing sequence databases.
42  * 
43  * @author JimP
44  * 
45  */
46 public class CrossRef
47 {
48   /*
49    * the dataset of the alignment for which we are searching for 
50    * cross-references; in some cases we may resolve xrefs by 
51    * searching in the dataset
52    */
53   private AlignmentI dataset;
54
55   /*
56    * the sequences for which we are seeking cross-references
57    */
58   private SequenceI[] fromSeqs;
59
60   /**
61    * matcher built from dataset
62    */
63   SequenceIdMatcher matcher;
64
65   /**
66    * sequences found by cross-ref searches to fromSeqs
67    */
68   List<SequenceI> rseqs;
69
70   /**
71    * Constructor
72    * 
73    * @param seqs
74    *          the sequences for which we are seeking cross-references
75    * @param ds
76    *          the containing alignment dataset (may be searched to resolve
77    *          cross-references)
78    */
79   public CrossRef(SequenceI[] seqs, AlignmentI ds)
80   {
81     fromSeqs = seqs;
82     dataset = ds.getDataset() == null ? ds : ds.getDataset();
83   }
84
85   /**
86    * Returns a list of distinct database sources for which sequences have either
87    * <ul>
88    * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
89    * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
90    * reference from another sequence in the dataset which has a cross-reference
91    * to a direct DBRefEntry on the given sequence</li>
92    * </ul>
93    * 
94    * @param dna
95    *          - when true, cross-references *from* dna returned. When false,
96    *          cross-references *from* protein are returned
97    * @return
98    */
99   public List<String> findXrefSourcesForSequences(boolean dna)
100   {
101     List<String> sources = new ArrayList<String>();
102     for (SequenceI seq : fromSeqs)
103     {
104       if (seq != null)
105       {
106         findXrefSourcesForSequence(seq, dna, sources);
107       }
108     }
109     return sources;
110   }
111
112   /**
113    * Returns a list of distinct database sources for which a sequence has either
114    * <ul>
115    * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
116    * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
117    * reference from another sequence in the dataset which has a cross-reference
118    * to a direct DBRefEntry on the given sequence</li>
119    * </ul>
120    * 
121    * @param seq
122    *          the sequence whose dbrefs we are searching against
123    * @param fromDna
124    *          when true, context is DNA - so sources identifying protein
125    *          products will be returned.
126    * @param sources
127    *          a list of sources to add matches to
128    */
129   void findXrefSourcesForSequence(SequenceI seq, boolean fromDna,
130           List<String> sources)
131   {
132     /*
133      * first find seq's xrefs (dna-to-peptide or peptide-to-dna)
134      */
135     DBRefEntry[] rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
136     addXrefsToSources(rfs, sources);
137     if (dataset != null)
138     {
139       /*
140        * find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
141        */
142       DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
143       List<SequenceI> foundSeqs = new ArrayList<SequenceI>();
144
145       /*
146        * find sequences in the alignment which xref one of these DBRefs
147        * i.e. is xref-ed to a common sequence identifier
148        */
149       searchDatasetXrefs(fromDna, seq, lrfs, foundSeqs, null);
150
151       /*
152        * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
153        */
154       for (SequenceI rs : foundSeqs)
155       {
156         DBRefEntry[] xrs = DBRefUtils
157                 .selectDbRefs(!fromDna, rs.getDBRefs());
158         addXrefsToSources(xrs, sources);
159       }
160     }
161   }
162
163   /**
164    * Helper method that adds the source identifiers of some cross-references to
165    * a (non-redundant) list of database sources
166    * 
167    * @param xrefs
168    * @param sources
169    */
170   void addXrefsToSources(DBRefEntry[] xrefs, List<String> sources)
171   {
172     if (xrefs != null)
173     {
174       for (DBRefEntry ref : xrefs)
175       {
176         /*
177          * avoid duplication e.g. ENSEMBL and Ensembl
178          */
179         String source = DBRefUtils.getCanonicalName(ref.getSource());
180         if (!sources.contains(source))
181         {
182           sources.add(source);
183         }
184       }
185     }
186   }
187
188   /**
189    * Attempts to find cross-references from the sequences provided in the
190    * constructor to the given source database. Cross-references may be found
191    * <ul>
192    * <li>in dbrefs on the sequence which hold a mapping to a sequence
193    * <ul>
194    * <li>provided with a fetched sequence (e.g. ENA translation), or</li>
195    * <li>populated previously after getting cross-references</li>
196    * </ul>
197    * <li>as other sequences in the alignment which share a dbref identifier with
198    * the sequence</li>
199    * <li>by fetching from the remote database</li>
200    * </ul>
201    * The cross-referenced sequences, and mappings to them, are added to the
202    * alignment dataset.
203    * 
204    * @param source
205    * @return cross-referenced sequences (as dataset sequences)
206    */
207   public Alignment findXrefSequences(String source, boolean fromDna)
208   {
209
210     rseqs = new ArrayList<SequenceI>();
211     AlignedCodonFrame cf = new AlignedCodonFrame();
212     matcher = new SequenceIdMatcher(
213             dataset.getSequences());
214
215     for (SequenceI seq : fromSeqs)
216     {
217       SequenceI dss = seq;
218       while (dss.getDatasetSequence() != null)
219       {
220         dss = dss.getDatasetSequence();
221       }
222       boolean found = false;
223       DBRefEntry[] xrfs = DBRefUtils
224               .selectDbRefs(!fromDna, dss.getDBRefs());
225       // ENST & ENSP comes in to both Protein and nucleotide, so we need to
226       // filter them
227       // out later.
228       if ((xrfs == null || xrfs.length == 0) && dataset != null)
229       {
230         /*
231          * found no suitable dbrefs on sequence - look for sequences in the
232          * alignment which share a dbref with this one
233          */
234         DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna,
235                 seq.getDBRefs());
236
237         /*
238          * find sequences (except this one!), of complementary type,
239          *  which have a dbref to an accession id for this sequence,
240          *  and add them to the results
241          */
242         found = searchDatasetXrefs(fromDna, dss, lrfs, rseqs, cf);
243       }
244       if (xrfs == null && !found)
245       {
246         /*
247          * no dbref to source on this sequence or matched
248          * complementary sequence in the dataset 
249          */
250         continue;
251       }
252       List<DBRefEntry> sourceRefs = DBRefUtils.searchRefsForSource(xrfs,
253               source);
254       Iterator<DBRefEntry> refIterator = sourceRefs.iterator();
255       // At this point, if we are retrieving Ensembl, we still don't filter out
256       // ENST when looking for protein crossrefs.
257       while (refIterator.hasNext())
258       {
259         DBRefEntry xref = refIterator.next();
260         found = false;
261         // we're only interested in coding cross-references, not
262         // locus->transcript
263         if (xref.hasMap() && xref.getMap().getMap().isTripletMap())
264         {
265           SequenceI mappedTo = xref.getMap().getTo();
266           if (mappedTo != null)
267           {
268             /*
269              * dbref contains the sequence it maps to; add it to the
270              * results unless we have done so already (could happen if 
271              * fetching xrefs for sequences which have xrefs in common)
272              * for example: UNIPROT {P0CE19, P0CE20} -> EMBL {J03321, X06707}
273              */
274             found = true;
275             /*
276              * problem: matcher.findIdMatch() is lenient - returns a sequence
277              * with a dbref to the search arg e.g. ENST for ENSP - wrong
278              * but findInDataset() matches ENSP when looking for Uniprot...
279              */
280             SequenceI matchInDataset = findInDataset(xref);
281             if (matchInDataset != null && xref.getMap().getTo() != null
282                     && matchInDataset != xref.getMap().getTo())
283             {
284               System.err
285                       .println("Implementation problem (reopen JAL-2154): CrossRef.findInDataset seems to have recovered a different sequence than the one explicitly mapped for xref."
286                               + "Found:"
287                               + matchInDataset
288                               + "\nExpected:"
289                               + xref.getMap().getTo()
290                               + "\nFor xref:"
291                               + xref);
292             }
293             /*matcher.findIdMatch(mappedTo);*/
294             if (matchInDataset != null)
295             {
296               if (!rseqs.contains(matchInDataset))
297               {
298                 rseqs.add(matchInDataset);
299               }
300               // even if rseqs contained matchInDataset - check mappings between
301               // these seqs are added
302               // need to try harder to only add unique mappings
303               if (xref.getMap().getMap().isTripletMap()
304                       && dataset.getMapping(seq, matchInDataset) == null
305                       && cf.getMappingBetween(seq, matchInDataset) == null)
306               {
307                 // materialise a mapping for highlighting between these
308                 // sequences
309                 if (fromDna)
310                 {
311                   cf.addMap(dss, matchInDataset, xref.getMap().getMap(),
312                           xref.getMap().getMappedFromId());
313                 }
314                 else
315                 {
316                   cf.addMap(matchInDataset, dss, xref.getMap().getMap()
317                           .getInverse(), xref.getMap().getMappedFromId());
318                 }
319               }
320
321               refIterator.remove();
322               continue;
323             }
324             // TODO: need to determine if this should be a deriveSequence
325             SequenceI rsq = new Sequence(mappedTo);
326             rseqs.add(rsq);
327             if (xref.getMap().getMap().isTripletMap())
328             {
329               // get sense of map correct for adding to product alignment.
330               if (fromDna)
331               {
332                 // map is from dna seq to a protein product
333                 cf.addMap(dss, rsq, xref.getMap().getMap(), xref.getMap()
334                         .getMappedFromId());
335               }
336               else
337               {
338                 // map should be from protein seq to its coding dna
339                 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse(),
340                         xref.getMap().getMappedFromId());
341               }
342             }
343           }
344         }
345
346         if (!found)
347         {
348           SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
349                   + xref.getAccessionId());
350           // if there was a match, check it's at least the right type of
351           // molecule!
352           if (matchedSeq != null && matchedSeq.isProtein() == fromDna)
353           {
354             if (constructMapping(seq, matchedSeq, xref, cf, fromDna))
355             {
356               found = true;
357             }
358           }
359         }
360
361         if (!found)
362         {
363           // do a bit more work - search for sequences with references matching
364           // xrefs on this sequence.
365           found = searchDataset(fromDna, dss, xref, rseqs, cf, false);
366         }
367         if (found)
368         {
369           refIterator.remove();
370         }
371       }
372
373       /*
374        * fetch from source database any dbrefs we haven't resolved up to here
375        */
376       if (!sourceRefs.isEmpty())
377       {
378         retrieveCrossRef(sourceRefs, seq, xrfs, fromDna, cf);
379       }
380     }
381
382     Alignment ral = null;
383     if (rseqs.size() > 0)
384     {
385       ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
386       if (!cf.isEmpty())
387       {
388         dataset.addCodonFrame(cf);
389       }
390     }
391     return ral;
392   }
393
394   private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
395           DBRefEntry[] xrfs, boolean fromDna, AlignedCodonFrame cf)
396   {
397     ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
398     SequenceI[] retrieved = null;
399     SequenceI dss = seq.getDatasetSequence() == null ? seq : seq
400             .getDatasetSequence();
401     // first filter in case we are retrieving crossrefs that have already been
402     // retrieved. this happens for cases where a database record doesn't yield
403     // protein products for CDS
404     removeAlreadyRetrievedSeqs(sourceRefs, fromDna);
405     if (sourceRefs.size() == 0)
406     {
407       // no more work to do! We already had all requested sequence records in
408       // the dataset.
409       return;
410     }
411     try
412     {
413       retrieved = sftch.getSequences(sourceRefs, !fromDna);
414     } catch (Exception e)
415     {
416       System.err
417               .println("Problem whilst retrieving cross references for Sequence : "
418                       + seq.getName());
419       e.printStackTrace();
420     }
421
422     if (retrieved != null)
423     {
424       boolean addedXref = false;
425       List<SequenceI> newDsSeqs = new ArrayList<SequenceI>(), doNotAdd = new ArrayList<SequenceI>();
426
427       for (SequenceI retrievedSequence : retrieved)
428       {
429         // dataset gets contaminated ccwith non-ds sequences. why ??!
430         // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
431         SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
432                 : retrievedSequence.getDatasetSequence();
433         addedXref |= importCrossRefSeq(cf, newDsSeqs, doNotAdd, dss,
434                 retrievedDss);
435       }
436       if (!addedXref)
437       {
438         // try again, after looking for matching IDs
439         // shouldn't need to do this unless the dbref mechanism has broken.
440         updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
441         for (SequenceI retrievedSequence : retrieved)
442         {
443           // dataset gets contaminated ccwith non-ds sequences. why ??!
444           // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
445           SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
446                   : retrievedSequence.getDatasetSequence();
447           addedXref |= importCrossRefSeq(cf, newDsSeqs, doNotAdd, dss,
448                   retrievedDss);
449         }
450       }
451       for (SequenceI newToSeq : newDsSeqs)
452       {
453         if (!doNotAdd.contains(newToSeq)
454                 && dataset.findIndex(newToSeq) == -1)
455         {
456           dataset.addSequence(newToSeq);
457           matcher.add(newToSeq);
458         }
459       }
460     }
461   }
462
463   /**
464    * Search dataset for sequences with a primary reference contained in
465    * sourceRefs.
466    * 
467    * @param sourceRefs
468    *          - list of references to filter.
469    * @param fromDna
470    *          - type of sequence to search for matching primary reference.
471    */
472   private void removeAlreadyRetrievedSeqs(List<DBRefEntry> sourceRefs,
473           boolean fromDna)
474   {
475     DBRefEntry[] dbrSourceSet = sourceRefs.toArray(new DBRefEntry[0]);
476     for (SequenceI sq : dataset.getSequences())
477     {
478       boolean dupeFound = false;
479       // !fromDna means we are looking only for nucleotide sequences, not
480       // protein
481       if (sq.isProtein() == fromDna)
482       {
483         for (DBRefEntry dbr : sq.getPrimaryDBRefs())
484         {
485           for (DBRefEntry found : DBRefUtils.searchRefs(dbrSourceSet, dbr))
486           {
487             sourceRefs.remove(found);
488             dupeFound = true;
489           }
490         }
491       }
492       if (dupeFound)
493       {
494         // rebuild the search array from the filtered sourceRefs list
495         dbrSourceSet = sourceRefs.toArray(new DBRefEntry[0]);
496       }
497     }
498   }
499
500   /**
501    * process sequence retrieved via a dbref on source sequence to resolve and
502    * transfer data
503    * 
504    * @param cf
505    * @param sourceSequence
506    * @param retrievedSequence
507    * @return true if retrieveSequence was imported
508    */
509   private boolean importCrossRefSeq(AlignedCodonFrame cf,
510           List<SequenceI> newDsSeqs, List<SequenceI> doNotAdd,
511           SequenceI sourceSequence, SequenceI retrievedSequence)
512   {
513     /**
514      * set when retrievedSequence has been verified as a crossreference for
515      * sourceSequence
516      */
517     boolean imported = false;
518     DBRefEntry[] dbr = retrievedSequence.getDBRefs();
519     if (dbr != null)
520     {
521       for (DBRefEntry dbref : dbr)
522       {
523         SequenceI matched = findInDataset(dbref);
524         if (matched == sourceSequence)
525         {
526           // verified retrieved and source sequence cross-reference each other
527           imported = true;
528         }
529         // find any entry where we should put in the sequence being
530         // cross-referenced into the map
531         Mapping map = dbref.getMap();
532         if (map != null)
533         {
534           if (map.getTo() != null && map.getMap() != null)
535           {
536             if (map.getTo() == sourceSequence)
537             {
538               // already called to import once, and most likely this sequence
539               // already imported !
540               continue;
541             }
542             if (matched == null)
543             {
544               /*
545                * sequence is new to dataset, so save a reference so it can be added. 
546                */
547               newDsSeqs.add(map.getTo());
548               continue;
549             }
550
551             /*
552              * there was a matching sequence in dataset, so now, check to see if we can update the map.getTo() sequence to the existing one.
553              */
554
555             try
556             {
557               // compare ms with dss and replace with dss in mapping
558               // if map is congruent
559               SequenceI ms = map.getTo();
560               // TODO findInDataset requires exact sequence match but
561               // 'congruent' test is only for the mapped part
562               // maybe not a problem in practice since only ENA provide a
563               // mapping and it is to the full protein translation of CDS
564               // matcher.findIdMatch(map.getTo());
565               // TODO addendum: if matched is shorter than getTo, this will fail
566               // - when it should really succeed.
567               int sf = map.getMap().getToLowest();
568               int st = map.getMap().getToHighest();
569               SequenceI mappedrg = ms.getSubSequence(sf, st);
570               if (mappedrg.getLength() > 0
571                       && ms.getSequenceAsString().equals(
572                               matched.getSequenceAsString()))
573               {
574                 /*
575                  * sequences were a match, 
576                  */
577                 String msg = "Mapping updated from " + ms.getName()
578                         + " to retrieved crossreference "
579                         + matched.getName();
580                 System.out.println(msg);
581
582                 DBRefEntry[] toRefs = map.getTo().getDBRefs();
583                 if (toRefs != null)
584                 {
585                   /*
586                    * transfer database refs
587                    */
588                   for (DBRefEntry ref : toRefs)
589                   {
590                     if (dbref.getSrcAccString().equals(
591                             ref.getSrcAccString()))
592                     {
593                       continue; // avoid overwriting the ref on source sequence
594                     }
595                     matched.addDBRef(ref); // add or update mapping
596                   }
597                 }
598                 doNotAdd.add(map.getTo());
599                 map.setTo(matched);
600
601                 /*
602                  * give the reverse reference the inverse mapping 
603                  * (if it doesn't have one already)
604                  */
605                 setReverseMapping(matched, dbref, cf);
606
607                 /*
608                  * copy sequence features as well, avoiding
609                  * duplication (e.g. same variation from two 
610                  * transcripts)
611                  */
612                 SequenceFeature[] sfs = ms.getSequenceFeatures();
613                 if (sfs != null)
614                 {
615                   for (SequenceFeature feat : sfs)
616                   {
617                     /*
618                      * make a flyweight feature object which ignores Parent
619                      * attribute in equality test; this avoids creating many
620                      * otherwise duplicate exon features on genomic sequence
621                      */
622                     SequenceFeature newFeature = new SequenceFeature(
623                             feat)
624                     {
625                       @Override
626                       public boolean equals(Object o)
627                       {
628                         return super.equals(o, true);
629                       }
630                     };
631                     matched.addSequenceFeature(newFeature);
632                   }
633                 }
634
635               }
636               cf.addMap(retrievedSequence, map.getTo(), map.getMap());
637             } catch (Exception e)
638             {
639               System.err
640                       .println("Exception when consolidating Mapped sequence set...");
641               e.printStackTrace(System.err);
642             }
643           }
644         }
645       }
646     }
647     if (imported)
648     {
649       retrievedSequence.updatePDBIds();
650       rseqs.add(retrievedSequence);
651       if (dataset.findIndex(retrievedSequence) == -1)
652       {
653         dataset.addSequence(retrievedSequence);
654         matcher.add(retrievedSequence);
655       }
656     }
657     return imported;
658   }
659   /**
660    * Sets the inverse sequence mapping in the corresponding dbref of the mapped
661    * to sequence (if any). This is used after fetching a cross-referenced
662    * sequence, if the fetched sequence has a mapping to the original sequence,
663    * to set the mapping in the original sequence's dbref.
664    * 
665    * @param mapFrom
666    *          the sequence mapped from
667    * @param dbref
668    * @param mappings
669    */
670   void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
671           AlignedCodonFrame mappings)
672   {
673     SequenceI mapTo = dbref.getMap().getTo();
674     if (mapTo == null)
675     {
676       return;
677     }
678     DBRefEntry[] dbrefs = mapTo.getDBRefs();
679     if (dbrefs == null)
680     {
681       return;
682     }
683     for (DBRefEntry toRef : dbrefs)
684     {
685       if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
686       {
687         /*
688          * found the reverse dbref; update its mapping if null
689          */
690         if (toRef.getMap().getMap() == null)
691         {
692           MapList inverse = dbref.getMap().getMap().getInverse();
693           toRef.getMap().setMap(inverse);
694           mappings.addMap(mapTo, mapFrom, inverse);
695         }
696       }
697     }
698   }
699
700   /**
701    * Returns null or the first sequence in the dataset which is identical to
702    * xref.mapTo, and has a) a primary dbref matching xref, or if none found, the
703    * first one with an ID source|xrefacc
704    * 
705    * @param xref
706    *          with map and mapped-to sequence
707    * @return
708    */
709   SequenceI findInDataset(DBRefEntry xref)
710   {
711     if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
712     {
713       return null;
714     }
715     SequenceI mapsTo = xref.getMap().getTo();
716     String name = xref.getAccessionId();
717     String name2 = xref.getSource() + "|" + name;
718     SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
719             .getDatasetSequence();
720     // first check ds if ds is directly referenced
721     if (dataset.findIndex(dss) > -1)
722     {
723       return dss;
724     }
725     DBRefEntry template = new DBRefEntry(xref.getSource(), null,
726             xref.getAccessionId());
727     /**
728      * remember the first ID match - in case we don't find a match to template
729      */
730     SequenceI firstIdMatch = null;
731     for (SequenceI seq : dataset.getSequences())
732     {
733       // first check primary refs.
734       List<DBRefEntry> match = DBRefUtils.searchRefs(seq.getPrimaryDBRefs()
735               .toArray(new DBRefEntry[0]), template);
736       if (match != null && match.size() == 1 && sameSequence(seq, dss))
737       {
738         return seq;
739       }
740       /*
741        * clumsy alternative to using SequenceIdMatcher which currently
742        * returns sequences with a dbref to the matched accession id 
743        * which we don't want
744        */
745       if (firstIdMatch == null
746               && (name.equals(seq.getName()) || seq.getName().startsWith(
747                       name2)))
748       {
749         if (sameSequence(seq, dss))
750         {
751           firstIdMatch = seq;
752         }
753       }
754     }
755     return firstIdMatch;
756   }
757
758   /**
759    * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
760    * case), else false. This method compares the lengths, then each character in
761    * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
762    * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
763    * 
764    * @param seq1
765    * @param seq2
766    * @return
767    */
768   // TODO move to Sequence / SequenceI
769   static boolean sameSequence(SequenceI seq1, SequenceI seq2)
770   {
771     if (seq1 == seq2)
772     {
773       return true;
774     }
775     if (seq1 == null || seq2 == null)
776     {
777       return false;
778     }
779     char[] c1 = seq1.getSequence();
780     char[] c2 = seq2.getSequence();
781     if (c1.length != c2.length)
782     {
783       return false;
784     }
785     for (int i = 0; i < c1.length; i++)
786     {
787       int diff = c1[i] - c2[i];
788       /*
789        * same char or differ in case only ('a'-'A' == 32)
790        */
791       if (diff != 0 && diff != 32 && diff != -32)
792       {
793         return false;
794       }
795     }
796     return true;
797   }
798
799   /**
800    * Updates any empty mappings in the cross-references with one to a compatible
801    * retrieved sequence if found, and adds any new mappings to the
802    * AlignedCodonFrame
803    * 
804    * @param mapFrom
805    * @param xrefs
806    * @param retrieved
807    * @param acf
808    */
809   void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
810           SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
811   {
812     SequenceIdMatcher idMatcher = new SequenceIdMatcher(retrieved);
813     for (DBRefEntry xref : xrefs)
814     {
815       if (!xref.hasMap())
816       {
817         String targetSeqName = xref.getSource() + "|"
818                 + xref.getAccessionId();
819         SequenceI[] matches = idMatcher.findAllIdMatches(targetSeqName);
820         if (matches == null)
821         {
822           return;
823         }
824         for (SequenceI seq : matches)
825         {
826           constructMapping(mapFrom, seq, xref, acf, fromDna);
827         }
828       }
829     }
830   }
831
832   /**
833    * Tries to make a mapping between sequences. If successful, adds the mapping
834    * to the dbref and the mappings collection and answers true, otherwise
835    * answers false. The following methods of making are mapping are tried in
836    * turn:
837    * <ul>
838    * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
839    * example, the case after fetching EMBL cross-references for a Uniprot
840    * sequence</li>
841    * <li>else check if the dna translates exactly to the protein (give or take
842    * start and stop codons></li>
843    * <li>else try to map based on CDS features on the dna sequence</li>
844    * </ul>
845    * 
846    * @param mapFrom
847    * @param mapTo
848    * @param xref
849    * @param mappings
850    * @return
851    */
852   boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
853           DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
854   {
855     MapList mapping = null;
856     SequenceI dsmapFrom = mapFrom.getDatasetSequence() == null ? mapFrom
857             : mapFrom.getDatasetSequence();
858     SequenceI dsmapTo = mapTo.getDatasetSequence() == null ? mapTo
859             : mapTo.getDatasetSequence();
860     /*
861      * look for a reverse mapping, if found make its inverse. 
862      * Note - we do this on dataset sequences only.
863      */
864     if (dsmapTo.getDBRefs() != null)
865     {
866       for (DBRefEntry dbref : dsmapTo.getDBRefs())
867       {
868         String name = dbref.getSource() + "|" + dbref.getAccessionId();
869         if (dbref.hasMap() && dsmapFrom.getName().startsWith(name))
870         {
871           /*
872            * looks like we've found a map from 'mapTo' to 'mapFrom'
873            * - invert it to make the mapping the other way 
874            */
875           MapList reverse = dbref.getMap().getMap().getInverse();
876           xref.setMap(new Mapping(dsmapTo, reverse));
877           mappings.addMap(mapFrom, dsmapTo, reverse);
878           return true;
879         }
880       }
881     }
882
883     if (fromDna)
884     {
885       mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
886     }
887     else
888     {
889       mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
890       if (mapping != null)
891       {
892         mapping = mapping.getInverse();
893       }
894     }
895     if (mapping == null)
896     {
897       return false;
898     }
899     xref.setMap(new Mapping(mapTo, mapping));
900
901     /*
902      * and add a reverse DbRef with the inverse mapping
903      */
904     if (mapFrom.getDatasetSequence() != null && false)
905     // && mapFrom.getDatasetSequence().getSourceDBRef() != null)
906     {
907       // possible need to search primary references... except, why doesn't xref
908       // == getSourceDBRef ??
909       // DBRefEntry dbref = new DBRefEntry(mapFrom.getDatasetSequence()
910       // .getSourceDBRef());
911       // dbref.setMap(new Mapping(mapFrom.getDatasetSequence(), mapping
912       // .getInverse()));
913       // mapTo.addDBRef(dbref);
914     }
915
916     if (fromDna)
917     {
918       AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
919       mappings.addMap(mapFrom, mapTo, mapping);
920     }
921     else
922     {
923       mappings.addMap(mapTo, mapFrom, mapping.getInverse());
924     }
925
926     return true;
927   }
928
929   /**
930    * find references to lrfs in the cross-reference set of each sequence in
931    * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
932    * based on source and accession string only - Map and Version are nulled.
933    * 
934    * @param fromDna
935    *          - true if context was searching from Dna sequences, false if
936    *          context was searching from Protein sequences
937    * @param sequenceI
938    * @param lrfs
939    * @param foundSeqs
940    * @return true if matches were found.
941    */
942   private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
943           DBRefEntry[] lrfs, List<SequenceI> foundSeqs, AlignedCodonFrame cf)
944   {
945     boolean found = false;
946     if (lrfs == null)
947     {
948       return false;
949     }
950     for (int i = 0; i < lrfs.length; i++)
951     {
952       DBRefEntry xref = new DBRefEntry(lrfs[i]);
953       // add in wildcards
954       xref.setVersion(null);
955       xref.setMap(null);
956       found |= searchDataset(fromDna, sequenceI, xref, foundSeqs, cf, false);
957     }
958     return found;
959   }
960
961   /**
962    * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
963    * associated sequence to rseqs
964    * 
965    * @param fromDna
966    *          true if context was searching for refs *from* dna sequence, false
967    *          if context was searching for refs *from* protein sequence
968    * @param fromSeq
969    *          a sequence to ignore (start point of search)
970    * @param xrf
971    *          a cross-reference to try to match
972    * @param foundSeqs
973    *          result list to add to
974    * @param mappings
975    *          a set of sequence mappings to add to
976    * @param direct
977    *          - indicates the type of relationship between returned sequences,
978    *          xrf, and sequenceI that is required.
979    *          <ul>
980    *          <li>direct implies xrf is a primary reference for sequenceI AND
981    *          the sequences to be located (eg a uniprot ID for a protein
982    *          sequence, and a uniprot ref on a transcript sequence).</li>
983    *          <li>indirect means xrf is a cross reference with respect to
984    *          sequenceI or all the returned sequences (eg a genomic reference
985    *          associated with a locus and one or more transcripts)</li>
986    *          </ul>
987    * @return true if relationship found and sequence added.
988    */
989   boolean searchDataset(boolean fromDna, SequenceI fromSeq, DBRefEntry xrf,
990           List<SequenceI> foundSeqs, AlignedCodonFrame mappings,
991           boolean direct)
992   {
993     boolean found = false;
994     if (dataset == null)
995     {
996       return false;
997     }
998     if (dataset.getSequences() == null)
999     {
1000       System.err.println("Empty dataset sequence set - NO VECTOR");
1001       return false;
1002     }
1003     List<SequenceI> ds;
1004     synchronized (ds = dataset.getSequences())
1005     {
1006       for (SequenceI nxt : ds)
1007       {
1008         if (nxt != null)
1009         {
1010           if (nxt.getDatasetSequence() != null)
1011           {
1012             System.err
1013                     .println("Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
1014                             + nxt.getDisplayId(true)
1015                             + " has ds reference "
1016                             + nxt.getDatasetSequence().getDisplayId(true)
1017                             + ")");
1018           }
1019           if (nxt == fromSeq || nxt == fromSeq.getDatasetSequence())
1020           {
1021             continue;
1022           }
1023           /*
1024            * only look at same molecule type if 'direct', or
1025            * complementary type if !direct
1026            */
1027           {
1028             boolean isDna = !nxt.isProtein();
1029             if (direct ? (isDna != fromDna) : (isDna == fromDna))
1030             {
1031               // skip this sequence because it is wrong molecule type
1032               continue;
1033             }
1034           }
1035
1036           // look for direct or indirect references in common
1037           DBRefEntry[] poss = nxt.getDBRefs();
1038           List<DBRefEntry> cands = null;
1039
1040           // todo: indirect specifies we select either direct references to nxt
1041           // that match xrf which is indirect to sequenceI, or indirect
1042           // references to nxt that match xrf which is direct to sequenceI
1043           cands = DBRefUtils.searchRefs(poss, xrf);
1044           // else
1045           // {
1046           // poss = DBRefUtils.selectDbRefs(nxt.isProtein()!fromDna, poss);
1047           // cands = DBRefUtils.searchRefs(poss, xrf);
1048           // }
1049           if (!cands.isEmpty())
1050           {
1051             if (foundSeqs.contains(nxt))
1052             {
1053               continue;
1054             }
1055             found = true;
1056             foundSeqs.add(nxt);
1057             if (mappings != null && !direct)
1058             {
1059               /*
1060                * if the matched sequence has mapped dbrefs to
1061                * protein product / cdna, add equivalent mappings to
1062                * our source sequence
1063                */
1064               for (DBRefEntry candidate : cands)
1065               {
1066                 Mapping mapping = candidate.getMap();
1067                 if (mapping != null)
1068                 {
1069                   MapList map = mapping.getMap();
1070                   if (mapping.getTo() != null
1071                           && map.getFromRatio() != map.getToRatio())
1072                   {
1073                     /*
1074                      * add a mapping, as from dna to peptide sequence
1075                      */
1076                     if (map.getFromRatio() == 3)
1077                     {
1078                       mappings.addMap(nxt, fromSeq, map);
1079                     }
1080                     else
1081                     {
1082                       mappings.addMap(nxt, fromSeq, map.getInverse());
1083                     }
1084                   }
1085                 }
1086               }
1087             }
1088           }
1089         }
1090       }
1091     }
1092     return found;
1093   }
1094 }