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