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