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