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