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