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