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