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