2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.analysis;
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.Comparison;
32 import jalview.util.DBRefUtils;
33 import jalview.util.MapList;
34 import jalview.ws.SequenceFetcherFactory;
35 import jalview.ws.seqfetcher.ASequenceFetcher;
37 import java.util.ArrayList;
38 import java.util.Iterator;
39 import java.util.List;
42 * Functions for cross-referencing sequence databases.
50 * the dataset of the alignment for which we are searching for
51 * cross-references; in some cases we may resolve xrefs by
52 * searching in the dataset
54 private AlignmentI dataset;
57 * true if we are searching for cross-references from nucleotide,
58 * i.e. for protein sequences, false if the reverse
60 private boolean fromDna;
63 * the sequences for which we are seeking cross-references
65 private SequenceI[] fromSeqs;
71 * the sequences for which we are seeking cross-references
73 * the containing alignment dataset (may be searched to resolve
76 public CrossRef(SequenceI[] seqs, AlignmentI ds)
79 fromDna = ds.isNucleotide();
80 dataset = ds.getDataset() == null ? ds : ds.getDataset();
84 * Returns a list of distinct database sources for which sequences have either
86 * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
87 * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
88 * reference from another sequence in the dataset which has a cross-reference
89 * to a direct DBRefEntry on the given sequence</li>
93 public List<String> findXrefSourcesForSequences()
95 List<String> sources = new ArrayList<String>();
96 for (SequenceI seq : fromSeqs)
100 findXrefSourcesForSequence(seq, sources);
107 * Returns a list of distinct database sources for which a sequence has either
109 * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
110 * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
111 * reference from another sequence in the dataset which has a cross-reference
112 * to a direct DBRefEntry on the given sequence</li>
116 * the sequence whose dbrefs we are searching against
118 * a list of sources to add matches to
120 void findXrefSourcesForSequence(SequenceI seq, List<String> sources)
123 * first find seq's xrefs (dna-to-peptide or peptide-to-dna)
125 DBRefEntry[] rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
126 addXrefsToSources(rfs, sources);
130 * find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
132 DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
133 List<SequenceI> rseqs = new ArrayList<SequenceI>();
136 * find sequences in the alignment which xref one of these DBRefs
137 * i.e. is xref-ed to a common sequence identifier
139 searchDatasetXrefs(seq, lrfs, rseqs, null);
142 * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
144 for (SequenceI rs : rseqs)
146 DBRefEntry[] xrs = DBRefUtils
147 .selectDbRefs(!fromDna, rs.getDBRefs());
148 addXrefsToSources(xrs, sources);
154 * Helper method that adds the source identifiers of some cross-references to
155 * a (non-redundant) list of database sources
160 void addXrefsToSources(DBRefEntry[] xrefs, List<String> sources)
164 for (DBRefEntry ref : xrefs)
166 String source = ref.getSource();
167 if (!sources.contains(source))
178 * sequences whose xrefs are being retrieved
180 * true if sequences are nucleotide
183 * alignment to search for cross-referenced sequences (and possibly
185 * @return products (as dataset sequences)
187 public Alignment findXrefSequences(String source)
189 List<SequenceI> rseqs = new ArrayList<SequenceI>();
190 AlignedCodonFrame cf = new AlignedCodonFrame();
191 SequenceIdMatcher matcher = new SequenceIdMatcher(
192 dataset.getSequences());
194 for (SequenceI seq : fromSeqs)
197 while (dss.getDatasetSequence() != null)
199 dss = dss.getDatasetSequence();
201 boolean found = false;
202 DBRefEntry[] xrfs = DBRefUtils
203 .selectDbRefs(!fromDna, dss.getDBRefs());
204 if ((xrfs == null || xrfs.length == 0) && dataset != null)
207 * found no suitable dbrefs on sequence - look for sequences in the
208 * alignment which share a dbref with this one
210 DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna,
214 * find sequences (except this one!), of complementary type,
215 * which have a dbref to an accession id for this sequence,
216 * and add them to the results
218 found = searchDatasetXrefs(dss, lrfs, rseqs, cf);
220 if (xrfs == null && !found)
223 * no dbref to source on this sequence or matched
224 * complementary sequence in the dataset
228 List<DBRefEntry> sourceRefs = DBRefUtils.searchRefsForSource(xrfs,
230 Iterator<DBRefEntry> refIterator = sourceRefs.iterator();
231 while (refIterator.hasNext())
233 DBRefEntry xref = refIterator.next();
237 SequenceI mappedTo = xref.getMap().getTo();
238 if (mappedTo != null)
241 * dbref contains the sequence it maps to; add it to the
242 * results unless we have done so already (could happen if
243 * fetching xrefs for sequences which have xrefs in common)
244 * for example: UNIPROT {P0CE19, P0CE20} -> EMBL {J03321, X06707}
247 SequenceI matchInDataset = findInDataset(mappedTo);// matcher.findIdMatch(mappedTo);
248 if (matchInDataset != null)
250 if (!rseqs.contains(matchInDataset))
252 rseqs.add(matchInDataset);
256 SequenceI rsq = new Sequence(mappedTo);
258 if (xref.getMap().getMap().getFromRatio() != xref.getMap()
259 .getMap().getToRatio())
261 // get sense of map correct for adding to product alignment.
264 // map is from dna seq to a protein product
265 cf.addMap(dss, rsq, xref.getMap().getMap());
269 // map should be from protein seq to its coding dna
270 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse());
278 SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
279 + xref.getAccessionId());
280 if (matchedSeq != null)
282 if (constructMapping(seq, matchedSeq, xref, cf))
291 // do a bit more work - search for sequences with references matching
292 // xrefs on this sequence.
293 found = searchDataset(dss, xref, rseqs, cf, false);
297 refIterator.remove();
302 * fetch from source database any dbrefs we haven't resolved up to here
304 if (!sourceRefs.isEmpty())
306 ASequenceFetcher sftch = SequenceFetcherFactory
307 .getSequenceFetcher();
308 SequenceI[] retrieved = null;
311 retrieved = sftch.getSequences(sourceRefs, !fromDna);
312 } catch (Exception e)
315 .println("Problem whilst retrieving cross references for Sequence : "
320 if (retrieved != null)
322 updateDbrefMappings(seq, xrfs, retrieved, cf);
323 for (SequenceI retrievedSequence : retrieved)
325 SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
326 : retrievedSequence.getDatasetSequence();
327 DBRefEntry[] dbr = retrievedSequence.getDBRefs();
330 for (DBRefEntry dbref : dbr)
332 // find any entry where we should put in the sequence being
333 // cross-referenced into the map
334 Mapping map = dbref.getMap();
337 if (map.getTo() != null && map.getMap() != null)
339 // TODO findInDataset requires exact sequence match but
340 // 'congruent' test only for the mapped part
341 SequenceI matched = findInDataset(map.getTo());// matcher.findIdMatch(map.getTo());
345 * already got an xref to this sequence; update this
346 * map to point to the same sequence, and add
347 * any new dbrefs to it
349 DBRefEntry[] toRefs = map.getTo().getDBRefs();
352 for (DBRefEntry ref : toRefs)
354 matched.addDBRef(ref); // add or update mapping
361 matcher.add(map.getTo());
365 // compare ms with dss and replace with dss in mapping
366 // if map is congruent
367 SequenceI ms = map.getTo();
368 int sf = map.getMap().getToLowest();
369 int st = map.getMap().getToHighest();
370 SequenceI mappedrg = ms.getSubSequence(sf, st);
371 // SequenceI loc = dss.getSubSequence(sf, st);
372 if (mappedrg.getLength() > 0
373 && ms.getSequenceAsString().equals(
374 dss.getSequenceAsString()))
375 // && mappedrg.getSequenceAsString().equals(
376 // loc.getSequenceAsString()))
378 String msg = "Mapping updated from " + ms.getName()
379 + " to retrieved crossreference "
381 System.out.println(msg);
382 // method to update all refs of existing To on
383 // retrieved sequence with dss and merge any props
385 // TODO don't we have to change the mapped to ranges
386 // if not to the whole sequence?
389 * copy sequence features as well, avoiding
390 * duplication (e.g. same variation from 2
393 SequenceFeature[] sfs = ms.getSequenceFeatures();
396 for (SequenceFeature feat : sfs)
399 * make a flyweight feature object which ignores Parent
400 * attribute in equality test, to avoid creating many
401 * otherwise duplicate exon features on genomic sequence
403 SequenceFeature newFeature = new SequenceFeature(
407 public boolean equals(Object o)
409 return super.equals(o, true);
412 dss.addSequenceFeature(newFeature);
416 cf.addMap(retrievedDss, map.getTo(), map.getMap());
417 } catch (Exception e)
420 .println("Exception when consolidating Mapped sequence set...");
421 e.printStackTrace(System.err);
427 retrievedSequence.updatePDBIds();
428 rseqs.add(retrievedSequence);
429 dataset.addSequence(retrievedDss);
430 matcher.add(retrievedSequence);
436 Alignment ral = null;
437 if (rseqs.size() > 0)
439 ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
440 if (cf != null && !cf.isEmpty())
442 ral.addCodonFrame(cf);
449 * Returns the first identical sequence in the dataset if any, else null
454 SequenceI findInDataset(SequenceI mappedTo)
456 if (mappedTo == null)
460 SequenceI dss = mappedTo.getDatasetSequence() == null ? mappedTo
461 : mappedTo.getDatasetSequence();
462 for (SequenceI seq : dataset.getSequences())
464 if (sameSequence(seq, dss))
473 * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
474 * case), else false. This method compares the lengths, then each character in
475 * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
476 * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
482 // TODO move to Sequence / SequenceI
483 static boolean sameSequence(SequenceI seq1, SequenceI seq2)
489 if (seq1 == null || seq2 == null)
493 char[] c1 = seq1.getSequence();
494 char[] c2 = seq2.getSequence();
495 if (c1.length != c2.length)
499 for (int i = 0; i < c1.length; i++)
501 int diff = c1[i] - c2[i];
503 * same char or differ in case only ('a'-'A' == 32)
505 if (diff != 0 && diff != 32 && diff != -32)
514 * Updates any empty mappings in the cross-references with one to a compatible
515 * retrieved sequence if found, and adds any new mappings to the
523 void updateDbrefMappings(SequenceI mapFrom,
524 DBRefEntry[] xrefs, SequenceI[] retrieved, AlignedCodonFrame acf)
526 SequenceIdMatcher matcher = new SequenceIdMatcher(retrieved);
527 for (DBRefEntry xref : xrefs)
531 String targetSeqName = xref.getSource() + "|"
532 + xref.getAccessionId();
533 SequenceI[] matches = matcher.findAllIdMatches(targetSeqName);
538 for (SequenceI seq : matches)
540 constructMapping(mapFrom, seq, xref, acf);
547 * Tries to make a mapping from dna to protein. If successful, adds the
548 * mapping to the dbref and the mappings collection and answers true,
549 * otherwise answers false.
557 boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
558 DBRefEntry xref, AlignedCodonFrame mappings)
560 MapList mapping = null;
563 mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
567 mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
570 mapping = mapping.getInverse();
577 xref.setMap(new Mapping(mapTo, mapping));
580 AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
581 mappings.addMap(mapFrom, mapTo, mapping);
585 mappings.addMap(mapTo, mapFrom, mapping.getInverse());
592 * find references to lrfs in the cross-reference set of each sequence in
593 * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
594 * based on source and accession string only - Map and Version are nulled.
599 * @return true if matches were found.
601 private boolean searchDatasetXrefs(SequenceI sequenceI,
602 DBRefEntry[] lrfs, List<SequenceI> rseqs, AlignedCodonFrame cf)
604 boolean found = false;
609 for (int i = 0; i < lrfs.length; i++)
611 DBRefEntry xref = new DBRefEntry(lrfs[i]);
613 xref.setVersion(null);
615 found |= searchDataset(sequenceI, xref, rseqs, cf, false);
621 * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
622 * associated sequence to rseqs
625 * a sequence to ignore (start point of search)
627 * a cross-reference to try to match
629 * result list to add to
631 * a set of sequence mappings to add to
633 * - search all references or only subset
634 * @return true if relationship found and sequence added.
636 boolean searchDataset(SequenceI sequenceI, DBRefEntry xrf,
637 List<SequenceI> rseqs, AlignedCodonFrame cf, boolean direct)
639 boolean found = false;
644 if (dataset.getSequences() == null)
646 System.err.println("Empty dataset sequence set - NO VECTOR");
650 synchronized (ds = dataset.getSequences())
652 for (SequenceI nxt : ds)
656 if (nxt.getDatasetSequence() != null)
659 .println("Implementation warning: getProducts passed a dataset alignment without dataset sequences in it!");
661 if (nxt == sequenceI || nxt == sequenceI.getDatasetSequence())
666 * only look at same molecule type if 'direct', or
667 * complementary type if !direct
670 boolean isDna = Comparison
671 .isNucleotide(new SequenceI[] { nxt });
672 if (direct ? (isDna != fromDna) : (isDna == fromDna))
674 // skip this sequence because it is wrong molecule type
679 // look for direct or indirect references in common
680 DBRefEntry[] poss = nxt.getDBRefs();
681 List<DBRefEntry> cands = null;
683 * TODO does this make any sense?
684 * if 'direct', search the dbrefs for xrf
685 * else, filter the dbrefs by type and then search for xrf
686 * - the result is the same isn't it?
690 cands = DBRefUtils.searchRefs(poss, xrf);
694 poss = DBRefUtils.selectDbRefs(!fromDna, poss);
695 cands = DBRefUtils.searchRefs(poss, xrf);
697 if (!cands.isEmpty())
699 if (!rseqs.contains(nxt))
705 // don't search if we aren't given a codon map object
706 for (DBRefEntry candidate : cands)
708 Mapping mapping = candidate.getMap();
711 MapList map = mapping.getMap();
712 if (mapping.getTo() != null
713 && map.getFromRatio() != map.getToRatio())
715 // get sense of map correct for adding to product
719 // map is from dna seq to a protein product
720 cf.addMap(sequenceI, nxt, map);
724 // map should be from protein seq to its coding dna
725 cf.addMap(nxt, sequenceI, map.getInverse());
731 // TODO: add mapping between sequences if necessary