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