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