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