JAL-2154 todo
[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             /*matcher.findIdMatch(mappedTo);*/
275             if (matchInDataset != null)
276             {
277               if (!rseqs.contains(matchInDataset))
278               {
279                 rseqs.add(matchInDataset);
280               }
281               refIterator.remove();
282               continue;
283             }
284             // TODO: need to determine if this should be a deriveSequence
285             SequenceI rsq = new Sequence(mappedTo);
286             rseqs.add(rsq);
287             if (xref.getMap().getMap().isTripletMap())
288             {
289               // get sense of map correct for adding to product alignment.
290               if (fromDna)
291               {
292                 // map is from dna seq to a protein product
293                 cf.addMap(dss, rsq, xref.getMap().getMap(), xref.getMap()
294                         .getMappedFromId());
295               }
296               else
297               {
298                 // map should be from protein seq to its coding dna
299                 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse(),
300                         xref.getMap().getMappedFromId());
301               }
302             }
303           }
304         }
305
306         if (!found)
307         {
308           SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
309                   + xref.getAccessionId());
310           if (matchedSeq != null)
311           {
312             if (constructMapping(seq, matchedSeq, xref, cf, fromDna))
313             {
314               found = true;
315             }
316           }
317         }
318
319         if (!found)
320         {
321           // do a bit more work - search for sequences with references matching
322           // xrefs on this sequence.
323           found = searchDataset(fromDna, dss, xref, rseqs, cf, false);
324         }
325         if (found)
326         {
327           refIterator.remove();
328         }
329       }
330
331       /*
332        * fetch from source database any dbrefs we haven't resolved up to here
333        */
334       if (!sourceRefs.isEmpty())
335       {
336         retrieveCrossRef(sourceRefs, seq, xrfs, fromDna, cf);
337       }
338     }
339
340     Alignment ral = null;
341     if (rseqs.size() > 0)
342     {
343       ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
344       if (!cf.isEmpty())
345       {
346         dataset.addCodonFrame(cf);
347       }
348     }
349     return ral;
350   }
351
352   private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
353           DBRefEntry[] xrfs, boolean fromDna, AlignedCodonFrame cf)
354   {
355     ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
356     SequenceI[] retrieved = null;
357     SequenceI dss = seq.getDatasetSequence() == null ? seq : seq
358             .getDatasetSequence();
359     try
360     {
361       retrieved = sftch.getSequences(sourceRefs, !fromDna);
362     } catch (Exception e)
363     {
364       System.err
365               .println("Problem whilst retrieving cross references for Sequence : "
366                       + seq.getName());
367       e.printStackTrace();
368     }
369
370     if (retrieved != null)
371     {
372       updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
373       for (SequenceI retrievedSequence : retrieved)
374       {
375         // dataset gets contaminated ccwith non-ds sequences. why ??!
376         // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
377         SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
378                 : retrievedSequence.getDatasetSequence();
379         DBRefEntry[] dbr = retrievedSequence.getDBRefs();
380         if (dbr != null)
381         {
382           for (DBRefEntry dbref : dbr)
383           {
384             // find any entry where we should put in the sequence being
385             // cross-referenced into the map
386             Mapping map = dbref.getMap();
387             if (map != null)
388             {
389               if (map.getTo() != null && map.getMap() != null)
390               {
391                 // TODO findInDataset requires exact sequence match but
392                 // 'congruent' test is only for the mapped part
393                 // maybe not a problem in practice since only ENA provide a
394                 // mapping and it is to the full protein translation of CDS
395                 SequenceI matched = findInDataset(dbref);
396                 // matcher.findIdMatch(map.getTo());
397                 if (matched != null)
398                 {
399                   /*
400                    * already got an xref to this sequence; update this
401                    * map to point to the same sequence, and add
402                    * any new dbrefs to it
403                    */
404                   DBRefEntry[] toRefs = map.getTo().getDBRefs();
405                   if (toRefs != null)
406                   {
407                     for (DBRefEntry ref : toRefs)
408                     {
409                       matched.addDBRef(ref); // add or update mapping
410                     }
411                   }
412                   map.setTo(matched);
413                 }
414                 else
415                 {
416                   matcher.add(map.getTo());
417                 }
418                 try
419                 {
420                   // compare ms with dss and replace with dss in mapping
421                   // if map is congruent
422                   SequenceI ms = map.getTo();
423                   int sf = map.getMap().getToLowest();
424                   int st = map.getMap().getToHighest();
425                   SequenceI mappedrg = ms.getSubSequence(sf, st);
426                   // SequenceI loc = dss.getSubSequence(sf, st);
427                   if (mappedrg.getLength() > 0
428                           && ms.getSequenceAsString().equals(
429                                   dss.getSequenceAsString()))
430                   // && mappedrg.getSequenceAsString().equals(
431                   // loc.getSequenceAsString()))
432                   {
433                     String msg = "Mapping updated from " + ms.getName()
434                             + " to retrieved crossreference "
435                             + dss.getName();
436                     System.out.println(msg);
437                     map.setTo(dss);
438
439                     /*
440                      * give the reverse reference the inverse mapping 
441                      * (if it doesn't have one already)
442                      */
443                     setReverseMapping(dss, dbref, cf);
444
445                     /*
446                      * copy sequence features as well, avoiding
447                      * duplication (e.g. same variation from two 
448                      * transcripts)
449                      */
450                     SequenceFeature[] sfs = ms.getSequenceFeatures();
451                     if (sfs != null)
452                     {
453                       for (SequenceFeature feat : sfs)
454                       {
455                         /*
456                          * make a flyweight feature object which ignores Parent
457                          * attribute in equality test; this avoids creating many
458                          * otherwise duplicate exon features on genomic sequence
459                          */
460                         SequenceFeature newFeature = new SequenceFeature(
461                                 feat)
462                         {
463                           @Override
464                           public boolean equals(Object o)
465                           {
466                             return super.equals(o, true);
467                           }
468                         };
469                         dss.addSequenceFeature(newFeature);
470                       }
471                     }
472                   }
473                   cf.addMap(retrievedDss, map.getTo(), map.getMap());
474                 } catch (Exception e)
475                 {
476                   System.err
477                           .println("Exception when consolidating Mapped sequence set...");
478                   e.printStackTrace(System.err);
479                 }
480               }
481             }
482           }
483         }
484         retrievedSequence.updatePDBIds();
485         rseqs.add(retrievedDss);
486         dataset.addSequence(retrievedDss);
487         matcher.add(retrievedDss);
488       }
489     }
490   }
491   /**
492    * Sets the inverse sequence mapping in the corresponding dbref of the mapped
493    * to sequence (if any). This is used after fetching a cross-referenced
494    * sequence, if the fetched sequence has a mapping to the original sequence,
495    * to set the mapping in the original sequence's dbref.
496    * 
497    * @param mapFrom
498    *          the sequence mapped from
499    * @param dbref
500    * @param mappings
501    */
502   void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
503           AlignedCodonFrame mappings)
504   {
505     SequenceI mapTo = dbref.getMap().getTo();
506     if (mapTo == null)
507     {
508       return;
509     }
510     DBRefEntry[] dbrefs = mapTo.getDBRefs();
511     if (dbrefs == null)
512     {
513       return;
514     }
515     for (DBRefEntry toRef : dbrefs)
516     {
517       if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
518       {
519         /*
520          * found the reverse dbref; update its mapping if null
521          */
522         if (toRef.getMap().getMap() == null)
523         {
524           MapList inverse = dbref.getMap().getMap().getInverse();
525           toRef.getMap().setMap(inverse);
526           mappings.addMap(mapTo, mapFrom, inverse);
527         }
528       }
529     }
530   }
531
532   /**
533    * Returns the first identical sequence in the dataset if any, else null
534    * 
535    * @param xref
536    * @return
537    */
538   SequenceI findInDataset(DBRefEntry xref)
539   {
540     if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
541     {
542       return null;
543     }
544     SequenceI mapsTo = xref.getMap().getTo();
545     String name = xref.getAccessionId();
546     String name2 = xref.getSource() + "|" + name;
547     SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
548             .getDatasetSequence();
549     for (SequenceI seq : dataset.getSequences())
550     {
551       /*
552        * clumsy alternative to using SequenceIdMatcher which currently
553        * returns sequences with a dbref to the matched accession id 
554        * which we don't want
555        */
556       if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
557       {
558         if (sameSequence(seq, dss))
559         {
560           return seq;
561         }
562       }
563     }
564     return null;
565   }
566
567   /**
568    * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
569    * case), else false. This method compares the lengths, then each character in
570    * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
571    * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
572    * 
573    * @param seq1
574    * @param seq2
575    * @return
576    */
577   // TODO move to Sequence / SequenceI
578   static boolean sameSequence(SequenceI seq1, SequenceI seq2)
579   {
580     if (seq1 == seq2)
581     {
582       return true;
583     }
584     if (seq1 == null || seq2 == null)
585     {
586       return false;
587     }
588     char[] c1 = seq1.getSequence();
589     char[] c2 = seq2.getSequence();
590     if (c1.length != c2.length)
591     {
592       return false;
593     }
594     for (int i = 0; i < c1.length; i++)
595     {
596       int diff = c1[i] - c2[i];
597       /*
598        * same char or differ in case only ('a'-'A' == 32)
599        */
600       if (diff != 0 && diff != 32 && diff != -32)
601       {
602         return false;
603       }
604     }
605     return true;
606   }
607
608   /**
609    * Updates any empty mappings in the cross-references with one to a compatible
610    * retrieved sequence if found, and adds any new mappings to the
611    * AlignedCodonFrame
612    * 
613    * @param mapFrom
614    * @param xrefs
615    * @param retrieved
616    * @param acf
617    */
618   void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
619           SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
620   {
621     SequenceIdMatcher idMatcher = new SequenceIdMatcher(retrieved);
622     for (DBRefEntry xref : xrefs)
623     {
624       if (!xref.hasMap())
625       {
626         String targetSeqName = xref.getSource() + "|"
627                 + xref.getAccessionId();
628         SequenceI[] matches = idMatcher.findAllIdMatches(targetSeqName);
629         if (matches == null)
630         {
631           return;
632         }
633         for (SequenceI seq : matches)
634         {
635           constructMapping(mapFrom, seq, xref, acf, fromDna);
636         }
637       }
638     }
639   }
640
641   /**
642    * Tries to make a mapping between sequences. If successful, adds the mapping
643    * to the dbref and the mappings collection and answers true, otherwise
644    * answers false. The following methods of making are mapping are tried in
645    * turn:
646    * <ul>
647    * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
648    * example, the case after fetching EMBL cross-references for a Uniprot
649    * sequence</li>
650    * <li>else check if the dna translates exactly to the protein (give or take
651    * start and stop codons></li>
652    * <li>else try to map based on CDS features on the dna sequence</li>
653    * </ul>
654    * 
655    * @param mapFrom
656    * @param mapTo
657    * @param xref
658    * @param mappings
659    * @return
660    */
661   boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
662           DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
663   {
664     MapList mapping = null;
665
666     /*
667      * look for a reverse mapping, if found make its inverse
668      */
669     if (mapTo.getDBRefs() != null)
670     {
671       for (DBRefEntry dbref : mapTo.getDBRefs())
672       {
673         String name = dbref.getSource() + "|" + dbref.getAccessionId();
674         if (dbref.hasMap() && mapFrom.getName().startsWith(name))
675         {
676           /*
677            * looks like we've found a map from 'mapTo' to 'mapFrom'
678            * - invert it to make the mapping the other way 
679            */
680           MapList reverse = dbref.getMap().getMap().getInverse();
681           xref.setMap(new Mapping(mapTo, reverse));
682           mappings.addMap(mapFrom, mapTo, reverse);
683           return true;
684         }
685       }
686     }
687
688     if (fromDna)
689     {
690       mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
691     }
692     else
693     {
694       mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
695       if (mapping != null)
696       {
697         mapping = mapping.getInverse();
698       }
699     }
700     if (mapping == null)
701     {
702       return false;
703     }
704     xref.setMap(new Mapping(mapTo, mapping));
705
706     /*
707      * and add a reverse DbRef with the inverse mapping
708      */
709     if (mapFrom.getDatasetSequence() != null
710             && mapFrom.getDatasetSequence().getSourceDBRef() != null)
711     {
712       DBRefEntry dbref = new DBRefEntry(mapFrom.getDatasetSequence()
713               .getSourceDBRef());
714       dbref.setMap(new Mapping(mapFrom.getDatasetSequence(), mapping
715               .getInverse()));
716       mapTo.addDBRef(dbref);
717     }
718
719     if (fromDna)
720     {
721       AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
722       mappings.addMap(mapFrom, mapTo, mapping);
723     }
724     else
725     {
726       mappings.addMap(mapTo, mapFrom, mapping.getInverse());
727     }
728
729     return true;
730   }
731
732   /**
733    * find references to lrfs in the cross-reference set of each sequence in
734    * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
735    * based on source and accession string only - Map and Version are nulled.
736    * 
737    * @param fromDna
738    *          - true if context was searching from Dna sequences, false if
739    *          context was searching from Protein sequences
740    * @param sequenceI
741    * @param lrfs
742    * @param foundSeqs
743    * @return true if matches were found.
744    */
745   private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
746           DBRefEntry[] lrfs, List<SequenceI> foundSeqs, AlignedCodonFrame cf)
747   {
748     boolean found = false;
749     if (lrfs == null)
750     {
751       return false;
752     }
753     for (int i = 0; i < lrfs.length; i++)
754     {
755       DBRefEntry xref = new DBRefEntry(lrfs[i]);
756       // add in wildcards
757       xref.setVersion(null);
758       xref.setMap(null);
759       found |= searchDataset(fromDna, sequenceI, xref, foundSeqs, cf, false);
760     }
761     return found;
762   }
763
764   /**
765    * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
766    * associated sequence to rseqs
767    * 
768    * @param fromDna
769    *          true if context was searching for refs *from* dna sequence, false
770    *          if context was searching for refs *from* protein sequence
771    * @param fromSeq
772    *          a sequence to ignore (start point of search)
773    * @param xrf
774    *          a cross-reference to try to match
775    * @param foundSeqs
776    *          result list to add to
777    * @param mappings
778    *          a set of sequence mappings to add to
779    * @param direct
780    *          - indicates the type of relationship between returned sequences,
781    *          xrf, and sequenceI that is required.
782    *          <ul>
783    *          <li>direct implies xrf is a primary reference for sequenceI AND
784    *          the sequences to be located (eg a uniprot ID for a protein
785    *          sequence, and a uniprot ref on a transcript sequence).</li>
786    *          <li>indirect means xrf is a cross reference with respect to
787    *          sequenceI or all the returned sequences (eg a genomic reference
788    *          associated with a locus and one or more transcripts)</li>
789    *          </ul>
790    * @return true if relationship found and sequence added.
791    */
792   boolean searchDataset(boolean fromDna, SequenceI fromSeq,
793           DBRefEntry xrf, List<SequenceI> foundSeqs, AlignedCodonFrame mappings,
794           boolean direct)
795   {
796     boolean found = false;
797     if (dataset == null)
798     {
799       return false;
800     }
801     if (dataset.getSequences() == null)
802     {
803       System.err.println("Empty dataset sequence set - NO VECTOR");
804       return false;
805     }
806     List<SequenceI> ds;
807     synchronized (ds = dataset.getSequences())
808     {
809       for (SequenceI nxt : ds)
810       {
811         if (nxt != null)
812         {
813           if (nxt.getDatasetSequence() != null)
814           {
815             System.err
816                     .println("Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
817                             + nxt.getDisplayId(true)
818                             + " has ds reference "
819                             + nxt.getDatasetSequence().getDisplayId(true)
820                             + ")");
821           }
822           if (nxt == fromSeq || nxt == fromSeq.getDatasetSequence())
823           {
824             continue;
825           }
826           /*
827            * only look at same molecule type if 'direct', or
828            * complementary type if !direct
829            */
830           {
831             boolean isDna = !nxt.isProtein();
832             if (direct ? (isDna != fromDna) : (isDna == fromDna))
833             {
834               // skip this sequence because it is wrong molecule type
835               continue;
836             }
837           }
838
839           // look for direct or indirect references in common
840           DBRefEntry[] poss = nxt.getDBRefs();
841           List<DBRefEntry> cands = null;
842
843           // todo: indirect specifies we select either direct references to nxt
844           // that match xrf which is indirect to sequenceI, or indirect
845           // references to nxt that match xrf which is direct to sequenceI
846           cands = DBRefUtils.searchRefs(poss, xrf);
847           // else
848           // {
849           // poss = DBRefUtils.selectDbRefs(nxt.isProtein()!fromDna, poss);
850           // cands = DBRefUtils.searchRefs(poss, xrf);
851           // }
852           if (!cands.isEmpty())
853           {
854             if (!foundSeqs.contains(nxt))
855             {
856               found = true;
857               foundSeqs.add(nxt);
858               if (mappings != null && !direct)
859               {
860                 /*
861                  * if the matched sequence has mapped dbrefs to
862                  * protein product / cdna, add equivalent mappings to
863                  * our source sequence
864                  */
865                 for (DBRefEntry candidate : cands)
866                 {
867                   Mapping mapping = candidate.getMap();
868                   if (mapping != null)
869                   {
870                     MapList map = mapping.getMap();
871                     if (mapping.getTo() != null
872                             && map.getFromRatio() != map.getToRatio())
873                     {
874                       /*
875                        * add a mapping, as from dna to peptide sequence
876                        */
877                       if (map.getFromRatio() == 3)
878                       {
879                         mappings.addMap(nxt, fromSeq, map);
880                       }
881                       else
882                       {
883                         mappings.addMap(nxt, fromSeq, map.getInverse());
884                       }
885                     }
886                   }
887                 }
888               }
889             }
890           }
891         }
892       }
893     }
894     return found;
895   }
896 }