JAL-2210 CrossRef.findInDataset should search for presence of SequenceI in dataset...
[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     // first filter in case we are retrieving crossrefs that have already been
394     // retrieved. this happens for cases where a database record doesn't yield
395     // protein products for CDS
396     DBRefEntry[] dbrSourceSet = sourceRefs.toArray(new DBRefEntry[0]);
397     for (SequenceI sq : dataset.getSequences())
398     {
399       boolean dupeFound = false;
400       // !fromDna means we are looking only for nucleotide sequences, not
401       // protein
402       if (sq.isProtein() == fromDna)
403       {
404         for (DBRefEntry dbr : sq.getPrimaryDBRefs())
405         {
406           for (DBRefEntry found : DBRefUtils.searchRefs(dbrSourceSet, dbr))
407           {
408             sourceRefs.remove(found);
409             dupeFound = true;
410           }
411         }
412       }
413       if (dupeFound)
414       {
415         dbrSourceSet = sourceRefs.toArray(new DBRefEntry[0]);
416       }
417     }
418     if (sourceRefs.size() == 0)
419     {
420       // no more work to do! We already had all requested sequence records in
421       // the dataset.
422       return;
423     }
424     try
425     {
426       retrieved = sftch.getSequences(sourceRefs, !fromDna);
427     } catch (Exception e)
428     {
429       System.err
430               .println("Problem whilst retrieving cross references for Sequence : "
431                       + seq.getName());
432       e.printStackTrace();
433     }
434
435     if (retrieved != null)
436     {
437       updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
438       for (SequenceI retrievedSequence : retrieved)
439       {
440         // dataset gets contaminated ccwith non-ds sequences. why ??!
441         // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
442         SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
443                 : retrievedSequence.getDatasetSequence();
444         DBRefEntry[] dbr = retrievedSequence.getDBRefs();
445         if (dbr != null)
446         {
447           for (DBRefEntry dbref : dbr)
448           {
449             // find any entry where we should put in the sequence being
450             // cross-referenced into the map
451             Mapping map = dbref.getMap();
452             if (map != null)
453             {
454               if (map.getTo() != null && map.getMap() != null)
455               {
456                 // TODO findInDataset requires exact sequence match but
457                 // 'congruent' test is only for the mapped part
458                 // maybe not a problem in practice since only ENA provide a
459                 // mapping and it is to the full protein translation of CDS
460                 SequenceI matched = findInDataset(dbref);
461                 // matcher.findIdMatch(map.getTo());
462                 if (matched != null)
463                 {
464                   /*
465                    * already got an xref to this sequence; update this
466                    * map to point to the same sequence, and add
467                    * any new dbrefs to it
468                    */
469                   DBRefEntry[] toRefs = map.getTo().getDBRefs();
470                   if (toRefs != null)
471                   {
472                     for (DBRefEntry ref : toRefs)
473                     {
474                       matched.addDBRef(ref); // add or update mapping
475                     }
476                   }
477                   map.setTo(matched);
478                 }
479                 else
480                 {
481                   if (dataset.findIndex(map.getTo()) == -1)
482                   {
483                     dataset.addSequence(map.getTo());
484                     matcher.add(map.getTo());
485                   }
486                 }
487                 try
488                 {
489                   // compare ms with dss and replace with dss in mapping
490                   // if map is congruent
491                   SequenceI ms = map.getTo();
492                   int sf = map.getMap().getToLowest();
493                   int st = map.getMap().getToHighest();
494                   SequenceI mappedrg = ms.getSubSequence(sf, st);
495                   // SequenceI loc = dss.getSubSequence(sf, st);
496                   if (mappedrg.getLength() > 0
497                           && ms.getSequenceAsString().equals(
498                                   dss.getSequenceAsString()))
499                   // && mappedrg.getSequenceAsString().equals(
500                   // loc.getSequenceAsString()))
501                   {
502                     String msg = "Mapping updated from " + ms.getName()
503                             + " to retrieved crossreference "
504                             + dss.getName();
505                     System.out.println(msg);
506                     map.setTo(dss);
507
508                     /*
509                      * give the reverse reference the inverse mapping 
510                      * (if it doesn't have one already)
511                      */
512                     setReverseMapping(dss, dbref, cf);
513
514                     /*
515                      * copy sequence features as well, avoiding
516                      * duplication (e.g. same variation from two 
517                      * transcripts)
518                      */
519                     SequenceFeature[] sfs = ms.getSequenceFeatures();
520                     if (sfs != null)
521                     {
522                       for (SequenceFeature feat : sfs)
523                       {
524                         /*
525                          * make a flyweight feature object which ignores Parent
526                          * attribute in equality test; this avoids creating many
527                          * otherwise duplicate exon features on genomic sequence
528                          */
529                         SequenceFeature newFeature = new SequenceFeature(
530                                 feat)
531                         {
532                           @Override
533                           public boolean equals(Object o)
534                           {
535                             return super.equals(o, true);
536                           }
537                         };
538                         dss.addSequenceFeature(newFeature);
539                       }
540                     }
541                   }
542                   cf.addMap(retrievedDss, map.getTo(), map.getMap());
543                 } catch (Exception e)
544                 {
545                   System.err
546                           .println("Exception when consolidating Mapped sequence set...");
547                   e.printStackTrace(System.err);
548                 }
549               }
550             }
551           }
552         }
553         retrievedSequence.updatePDBIds();
554         rseqs.add(retrievedDss);
555         if (dataset.findIndex(retrievedDss) == -1)
556         {
557           dataset.addSequence(retrievedDss);
558           matcher.add(retrievedDss);
559         }
560       }
561     }
562   }
563   /**
564    * Sets the inverse sequence mapping in the corresponding dbref of the mapped
565    * to sequence (if any). This is used after fetching a cross-referenced
566    * sequence, if the fetched sequence has a mapping to the original sequence,
567    * to set the mapping in the original sequence's dbref.
568    * 
569    * @param mapFrom
570    *          the sequence mapped from
571    * @param dbref
572    * @param mappings
573    */
574   void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
575           AlignedCodonFrame mappings)
576   {
577     SequenceI mapTo = dbref.getMap().getTo();
578     if (mapTo == null)
579     {
580       return;
581     }
582     DBRefEntry[] dbrefs = mapTo.getDBRefs();
583     if (dbrefs == null)
584     {
585       return;
586     }
587     for (DBRefEntry toRef : dbrefs)
588     {
589       if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
590       {
591         /*
592          * found the reverse dbref; update its mapping if null
593          */
594         if (toRef.getMap().getMap() == null)
595         {
596           MapList inverse = dbref.getMap().getMap().getInverse();
597           toRef.getMap().setMap(inverse);
598           mappings.addMap(mapTo, mapFrom, inverse);
599         }
600       }
601     }
602   }
603
604   /**
605    * Returns the first identical sequence in the dataset if any, else null
606    * 
607    * @param xref
608    * @return
609    */
610   SequenceI findInDataset(DBRefEntry xref)
611   {
612     if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
613     {
614       return null;
615     }
616     SequenceI mapsTo = xref.getMap().getTo();
617     String name = xref.getAccessionId();
618     String name2 = xref.getSource() + "|" + name;
619     SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
620             .getDatasetSequence();
621     // first check ds if ds is directly referenced
622     if (dataset.findIndex(dss) > -1)
623     {
624       return dss;
625     }
626     ;
627     for (SequenceI seq : dataset.getSequences())
628     {
629       /*
630        * clumsy alternative to using SequenceIdMatcher which currently
631        * returns sequences with a dbref to the matched accession id 
632        * which we don't want
633        */
634       if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
635       {
636         if (sameSequence(seq, dss))
637         {
638           return seq;
639         }
640       }
641     }
642     return null;
643   }
644
645   /**
646    * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
647    * case), else false. This method compares the lengths, then each character in
648    * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
649    * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
650    * 
651    * @param seq1
652    * @param seq2
653    * @return
654    */
655   // TODO move to Sequence / SequenceI
656   static boolean sameSequence(SequenceI seq1, SequenceI seq2)
657   {
658     if (seq1 == seq2)
659     {
660       return true;
661     }
662     if (seq1 == null || seq2 == null)
663     {
664       return false;
665     }
666     char[] c1 = seq1.getSequence();
667     char[] c2 = seq2.getSequence();
668     if (c1.length != c2.length)
669     {
670       return false;
671     }
672     for (int i = 0; i < c1.length; i++)
673     {
674       int diff = c1[i] - c2[i];
675       /*
676        * same char or differ in case only ('a'-'A' == 32)
677        */
678       if (diff != 0 && diff != 32 && diff != -32)
679       {
680         return false;
681       }
682     }
683     return true;
684   }
685
686   /**
687    * Updates any empty mappings in the cross-references with one to a compatible
688    * retrieved sequence if found, and adds any new mappings to the
689    * AlignedCodonFrame
690    * 
691    * @param mapFrom
692    * @param xrefs
693    * @param retrieved
694    * @param acf
695    */
696   void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
697           SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
698   {
699     SequenceIdMatcher idMatcher = new SequenceIdMatcher(retrieved);
700     for (DBRefEntry xref : xrefs)
701     {
702       if (!xref.hasMap())
703       {
704         String targetSeqName = xref.getSource() + "|"
705                 + xref.getAccessionId();
706         SequenceI[] matches = idMatcher.findAllIdMatches(targetSeqName);
707         if (matches == null)
708         {
709           return;
710         }
711         for (SequenceI seq : matches)
712         {
713           constructMapping(mapFrom, seq, xref, acf, fromDna);
714         }
715       }
716     }
717   }
718
719   /**
720    * Tries to make a mapping between sequences. If successful, adds the mapping
721    * to the dbref and the mappings collection and answers true, otherwise
722    * answers false. The following methods of making are mapping are tried in
723    * turn:
724    * <ul>
725    * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
726    * example, the case after fetching EMBL cross-references for a Uniprot
727    * sequence</li>
728    * <li>else check if the dna translates exactly to the protein (give or take
729    * start and stop codons></li>
730    * <li>else try to map based on CDS features on the dna sequence</li>
731    * </ul>
732    * 
733    * @param mapFrom
734    * @param mapTo
735    * @param xref
736    * @param mappings
737    * @return
738    */
739   boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
740           DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
741   {
742     MapList mapping = null;
743     SequenceI dsmapFrom = mapFrom.getDatasetSequence() == null ? mapFrom
744             : mapFrom.getDatasetSequence();
745     SequenceI dsmapTo = mapTo.getDatasetSequence() == null ? mapTo
746             : mapTo.getDatasetSequence();
747     /*
748      * look for a reverse mapping, if found make its inverse. 
749      * Note - we do this on dataset sequences only.
750      */
751     if (dsmapTo.getDBRefs() != null)
752     {
753       for (DBRefEntry dbref : dsmapTo.getDBRefs())
754       {
755         String name = dbref.getSource() + "|" + dbref.getAccessionId();
756         if (dbref.hasMap() && dsmapFrom.getName().startsWith(name))
757         {
758           /*
759            * looks like we've found a map from 'mapTo' to 'mapFrom'
760            * - invert it to make the mapping the other way 
761            */
762           MapList reverse = dbref.getMap().getMap().getInverse();
763           xref.setMap(new Mapping(dsmapTo, reverse));
764           mappings.addMap(mapFrom, dsmapTo, reverse);
765           return true;
766         }
767       }
768     }
769
770     if (fromDna)
771     {
772       mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
773     }
774     else
775     {
776       mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
777       if (mapping != null)
778       {
779         mapping = mapping.getInverse();
780       }
781     }
782     if (mapping == null)
783     {
784       return false;
785     }
786     xref.setMap(new Mapping(mapTo, mapping));
787
788     /*
789      * and add a reverse DbRef with the inverse mapping
790      */
791     if (mapFrom.getDatasetSequence() != null && false)
792     // && mapFrom.getDatasetSequence().getSourceDBRef() != null)
793     {
794       // possible need to search primary references... except, why doesn't xref
795       // == getSourceDBRef ??
796       // DBRefEntry dbref = new DBRefEntry(mapFrom.getDatasetSequence()
797       // .getSourceDBRef());
798       // dbref.setMap(new Mapping(mapFrom.getDatasetSequence(), mapping
799       // .getInverse()));
800       // mapTo.addDBRef(dbref);
801     }
802
803     if (fromDna)
804     {
805       AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
806       mappings.addMap(mapFrom, mapTo, mapping);
807     }
808     else
809     {
810       mappings.addMap(mapTo, mapFrom, mapping.getInverse());
811     }
812
813     return true;
814   }
815
816   /**
817    * find references to lrfs in the cross-reference set of each sequence in
818    * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
819    * based on source and accession string only - Map and Version are nulled.
820    * 
821    * @param fromDna
822    *          - true if context was searching from Dna sequences, false if
823    *          context was searching from Protein sequences
824    * @param sequenceI
825    * @param lrfs
826    * @param foundSeqs
827    * @return true if matches were found.
828    */
829   private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
830           DBRefEntry[] lrfs, List<SequenceI> foundSeqs, AlignedCodonFrame cf)
831   {
832     boolean found = false;
833     if (lrfs == null)
834     {
835       return false;
836     }
837     for (int i = 0; i < lrfs.length; i++)
838     {
839       DBRefEntry xref = new DBRefEntry(lrfs[i]);
840       // add in wildcards
841       xref.setVersion(null);
842       xref.setMap(null);
843       found |= searchDataset(fromDna, sequenceI, xref, foundSeqs, cf, false);
844     }
845     return found;
846   }
847
848   /**
849    * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
850    * associated sequence to rseqs
851    * 
852    * @param fromDna
853    *          true if context was searching for refs *from* dna sequence, false
854    *          if context was searching for refs *from* protein sequence
855    * @param fromSeq
856    *          a sequence to ignore (start point of search)
857    * @param xrf
858    *          a cross-reference to try to match
859    * @param foundSeqs
860    *          result list to add to
861    * @param mappings
862    *          a set of sequence mappings to add to
863    * @param direct
864    *          - indicates the type of relationship between returned sequences,
865    *          xrf, and sequenceI that is required.
866    *          <ul>
867    *          <li>direct implies xrf is a primary reference for sequenceI AND
868    *          the sequences to be located (eg a uniprot ID for a protein
869    *          sequence, and a uniprot ref on a transcript sequence).</li>
870    *          <li>indirect means xrf is a cross reference with respect to
871    *          sequenceI or all the returned sequences (eg a genomic reference
872    *          associated with a locus and one or more transcripts)</li>
873    *          </ul>
874    * @return true if relationship found and sequence added.
875    */
876   boolean searchDataset(boolean fromDna, SequenceI fromSeq, DBRefEntry xrf,
877           List<SequenceI> foundSeqs, AlignedCodonFrame mappings,
878           boolean direct)
879   {
880     boolean found = false;
881     if (dataset == null)
882     {
883       return false;
884     }
885     if (dataset.getSequences() == null)
886     {
887       System.err.println("Empty dataset sequence set - NO VECTOR");
888       return false;
889     }
890     List<SequenceI> ds;
891     synchronized (ds = dataset.getSequences())
892     {
893       for (SequenceI nxt : ds)
894       {
895         if (nxt != null)
896         {
897           if (nxt.getDatasetSequence() != null)
898           {
899             System.err
900                     .println("Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
901                             + nxt.getDisplayId(true)
902                             + " has ds reference "
903                             + nxt.getDatasetSequence().getDisplayId(true)
904                             + ")");
905           }
906           if (nxt == fromSeq || nxt == fromSeq.getDatasetSequence())
907           {
908             continue;
909           }
910           /*
911            * only look at same molecule type if 'direct', or
912            * complementary type if !direct
913            */
914           {
915             boolean isDna = !nxt.isProtein();
916             if (direct ? (isDna != fromDna) : (isDna == fromDna))
917             {
918               // skip this sequence because it is wrong molecule type
919               continue;
920             }
921           }
922
923           // look for direct or indirect references in common
924           DBRefEntry[] poss = nxt.getDBRefs();
925           List<DBRefEntry> cands = null;
926
927           // todo: indirect specifies we select either direct references to nxt
928           // that match xrf which is indirect to sequenceI, or indirect
929           // references to nxt that match xrf which is direct to sequenceI
930           cands = DBRefUtils.searchRefs(poss, xrf);
931           // else
932           // {
933           // poss = DBRefUtils.selectDbRefs(nxt.isProtein()!fromDna, poss);
934           // cands = DBRefUtils.searchRefs(poss, xrf);
935           // }
936           if (!cands.isEmpty())
937           {
938             if (foundSeqs.contains(nxt))
939             {
940               continue;
941             }
942             found = true;
943             foundSeqs.add(nxt);
944             if (mappings != null && !direct)
945             {
946               /*
947                * if the matched sequence has mapped dbrefs to
948                * protein product / cdna, add equivalent mappings to
949                * our source sequence
950                */
951               for (DBRefEntry candidate : cands)
952               {
953                 Mapping mapping = candidate.getMap();
954                 if (mapping != null)
955                 {
956                   MapList map = mapping.getMap();
957                   if (mapping.getTo() != null
958                           && map.getFromRatio() != map.getToRatio())
959                   {
960                     /*
961                      * add a mapping, as from dna to peptide sequence
962                      */
963                     if (map.getFromRatio() == 3)
964                     {
965                       mappings.addMap(nxt, fromSeq, map);
966                     }
967                     else
968                     {
969                       mappings.addMap(nxt, fromSeq, map.getInverse());
970                     }
971                   }
972                 }
973               }
974             }
975           }
976         }
977       }
978     }
979     return found;
980   }
981 }