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