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.datamodel.xdb.embl;
23 import jalview.analysis.SequenceIdMatcher;
24 import jalview.bin.Cache;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.FeatureProperties;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.util.DBRefUtils;
33 import jalview.util.DnaUtils;
34 import jalview.util.MapList;
35 import jalview.util.MappingUtils;
36 import jalview.util.StringUtils;
38 import java.text.ParseException;
39 import java.util.Arrays;
40 import java.util.Hashtable;
41 import java.util.List;
43 import java.util.Map.Entry;
44 import java.util.Vector;
45 import java.util.regex.Pattern;
48 * Data model for one entry returned from an EMBL query, as marshalled by a
52 * http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=ena_sequence&id=J03321
55 * @see embl_mapping.xml
57 public class EmblEntry
59 private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
65 String sequenceVersion;
73 String sequenceLength;
75 String taxonomicDivision;
79 String firstPublicDate;
81 String firstPublicRelease;
83 String lastUpdatedDate;
85 String lastUpdatedRelease;
87 Vector<String> keywords;
89 Vector<DBRefEntry> dbRefs;
91 Vector<EmblFeature> features;
93 EmblSequence sequence;
96 * @return the accession
98 public String getAccession()
105 * the accession to set
107 public void setAccession(String accession)
109 this.accession = accession;
115 public Vector<DBRefEntry> getDbRefs()
124 public void setDbRefs(Vector<DBRefEntry> dbRefs)
126 this.dbRefs = dbRefs;
130 * @return the features
132 public Vector<EmblFeature> getFeatures()
139 * the features to set
141 public void setFeatures(Vector<EmblFeature> features)
143 this.features = features;
147 * @return the keywords
149 public Vector<String> getKeywords()
156 * the keywords to set
158 public void setKeywords(Vector<String> keywords)
160 this.keywords = keywords;
164 * @return the sequence
166 public EmblSequence getSequence()
173 * the sequence to set
175 public void setSequence(EmblSequence sequence)
177 this.sequence = sequence;
181 * Recover annotated sequences from EMBL file
185 * a list of protein products found so far (to add to)
186 * @return dna dataset sequence with DBRefs and features
188 public SequenceI getSequence(String sourceDb, List<SequenceI> peptides)
190 SequenceI dna = new Sequence(sourceDb + "|" + accession,
191 sequence.getSequence());
192 dna.setDescription(description);
193 DBRefEntry retrievedref = new DBRefEntry(sourceDb,
194 getSequenceVersion(), accession);
195 dna.addDBRef(retrievedref);
196 // add map to indicate the sequence is a valid coordinate frame for the
198 retrievedref.setMap(new Mapping(null, new int[] { 1, dna.getLength() },
199 new int[] { 1, dna.getLength() }, 1, 1));
200 // TODO: transform EMBL Database refs to canonical form
203 for (DBRefEntry dbref : dbRefs)
205 dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
212 for (EmblFeature feature : features)
214 if (feature.dbRefs != null)
216 for (DBRefEntry dbref : feature.dbRefs)
219 * convert UniProtKB/Swiss-Prot to UNIPROT
221 dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
225 if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
227 parseCodingFeature(feature, sourceDb, dna, peptides);
230 } catch (Exception e)
232 System.err.println("EMBL Record Features parsing error!");
234 .println("Please report the following to help@jalview.org :");
235 System.err.println("EMBL Record " + accession);
236 System.err.println("Resulted in exception: " + e.getMessage());
237 e.printStackTrace(System.err);
244 * Extracts coding region and product from a CDS feature and properly decorate
245 * it with annotations.
250 * source database for the EMBLXML
252 * parent dna sequence for this record
254 * list of protein product sequences for Embl entry
256 void parseCodingFeature(EmblFeature feature, String sourceDb,
257 SequenceI dna, List<SequenceI> peptides)
259 boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
261 int[] exon = getCdsRanges(feature);
266 Map<String, String> vals = new Hashtable<String, String>();
267 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
270 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
271 * (phase is required for CDS features in GFF3 format)
276 * parse qualifiers, saving protein translation, protein id,
277 * codon start position, product (name), and 'other values'
279 if (feature.getQualifiers() != null)
281 for (Qualifier q : feature.getQualifiers())
283 String qname = q.getName();
284 if (qname.equals("translation"))
286 // remove all spaces (precompiled String.replaceAll(" ", ""))
287 prseq = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
289 else if (qname.equals("protein_id"))
291 prid = q.getValues()[0];
293 else if (qname.equals("codon_start"))
297 codonStart = Integer.parseInt(q.getValues()[0]);
298 } catch (NumberFormatException e)
300 System.err.println("Invalid codon_start in XML for "
301 + accession + ": " + e.getMessage());
304 else if (qname.equals("product"))
306 // sometimes name is returned e.g. for V00488
307 prname = q.getValues()[0];
311 // throw anything else into the additional properties hash
312 String[] qvals = q.getValues();
315 String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
317 vals.put(qname, commaSeparated);
323 DBRefEntry protEMBLCDS = null;
324 exon = MappingUtils.removeStartPositions(codonStart - 1, exon);
325 boolean noProteinDbref = true;
327 SequenceI product = null;
329 if (prseq != null && prname != null && prid != null)
332 * look for product in peptides list, if not found, add it
334 product = matcher.findIdMatch(prid);
337 product = new Sequence(prid, prseq, 1, prseq.length());
338 product.setDescription(((prname.length() == 0) ? "Protein Product from "
341 peptides.add(product);
342 matcher.add(product);
345 // we have everything - create the mapping and perhaps the protein
347 if (exon == null || exon.length == 0)
350 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
351 + sourceDb + ":" + getAccession() + ")");
352 if (prseq.length() * 3 == (1 - codonStart + dna.getSequence().length))
355 .println("Not allowing for additional stop codon at end of cDNA fragment... !");
356 // this might occur for CDS sequences where no features are
358 exon = new int[] { dna.getStart() + (codonStart - 1),
360 map = new Mapping(product, exon, new int[] { 1, prseq.length() },
363 if ((prseq.length() + 1) * 3 == (1 - codonStart + dna.getSequence().length))
366 .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
367 exon = new int[] { dna.getStart() + (codonStart - 1),
369 map = new Mapping(product, exon, new int[] { 1, prseq.length() },
375 // Trim the exon mapping if necessary - the given product may only be a
376 // fragment of a larger protein. (EMBL:AY043181 is an example)
380 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
382 // if given a dataset reference, search dataset for parent EMBL
383 // sequence if it exists and set its map
384 // make a new feature annotating the coding contig
388 // final product length truncation check
389 // TODO should from range include stop codon even if not in protein
390 // in order to include stop codon in CDS sequence (as done for
392 int[] cdsRanges = adjustForProteinLength(prseq.length(), exon);
393 map = new Mapping(product, cdsRanges, new int[] { 1,
394 prseq.length() }, 3, 1);
395 // reconstruct the EMBLCDS entry
396 // TODO: this is only necessary when there codon annotation is
397 // complete (I think JBPNote)
398 DBRefEntry pcdnaref = new DBRefEntry();
399 pcdnaref.setAccessionId(prid);
400 pcdnaref.setSource(DBRefSource.EMBLCDS);
401 pcdnaref.setVersion(getSequenceVersion()); // same as parent EMBL
403 MapList mp = new MapList(new int[] { 1, prseq.length() },
404 new int[] { 1 + (codonStart - 1),
405 (codonStart - 1) + 3 * prseq.length() }, 1, 3);
406 pcdnaref.setMap(new Mapping(mp));
409 product.addDBRef(pcdnaref);
410 protEMBLCDS = new DBRefEntry(pcdnaref);
411 protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
412 product.addDBRef(protEMBLCDS);
416 // add cds feature to dna seq - this may include the stop codon
417 for (int xint = 0; exon != null && xint < exon.length; xint += 2)
419 SequenceFeature sf = makeCdsFeature(exon, xint, prname, prid, vals,
421 sf.setType(feature.getName()); // "CDS"
422 sf.setEnaLocation(feature.getLocation());
423 sf.setFeatureGroup(sourceDb);
424 dna.addSequenceFeature(sf);
429 * add mappings for Uniprot xrefs
431 if (feature.dbRefs != null)
433 boolean mappingUsed = false;
434 for (DBRefEntry ref : feature.dbRefs)
436 if (ref.getSource().equals(DBRefSource.UNIPROT))
438 String proteinSeqName = DBRefSource.UNIPROT + "|"
439 + ref.getAccessionId();
440 if (map != null && map.getTo() != null)
445 * two or more Uniprot xrefs for the same CDS -
446 * each needs a distinct Mapping (as to a different sequence)
448 map = new Mapping(map);
453 * try to locate the protein mapped to (possibly by a
454 * previous CDS feature)
456 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
457 if (proteinSeq == null)
459 proteinSeq = new Sequence(proteinSeqName,
460 product.getSequenceAsString());
461 matcher.add(proteinSeq);
462 peptides.add(proteinSeq);
464 map.setTo(proteinSeq);
465 map.getTo().addDBRef(
466 new DBRefEntry(ref.getSource(), ref.getVersion(), ref
470 noProteinDbref = false;
474 DBRefEntry pref = new DBRefEntry(ref.getSource(),
475 ref.getVersion(), ref.getAccessionId());
476 pref.setMap(null); // reference is direct
477 product.addDBRef(pref);
478 // Add converse mapping reference
481 Mapping pmap = new Mapping(dna, map.getMap().getInverse());
482 pref = new DBRefEntry(sourceDb, getSequenceVersion(),
483 this.getAccession());
485 if (map.getTo() != null)
487 map.getTo().addDBRef(pref);
492 if (noProteinDbref && product != null)
494 // add protein coding reference to dna sequence so xref matches
495 if (protEMBLCDS == null)
497 protEMBLCDS = new DBRefEntry();
498 protEMBLCDS.setAccessionId(prid);
499 protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
500 protEMBLCDS.setVersion(getSequenceVersion());
502 .setMap(new Mapping(product, map.getMap().getInverse()));
504 product.addDBRef(protEMBLCDS);
506 // Add converse mapping reference
509 Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
511 DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
513 if (map.getTo() != null)
523 * Helper method to construct a SequenceFeature for one cds range
526 * array of cds [start, end, ...] positions
527 * @param exonStartIndex
528 * offset into the exons array
530 * @param proteinAccessionId
532 * map of 'miscellaneous values' for feature
534 * codon start position for CDS (1/2/3, normally 1)
537 protected SequenceFeature makeCdsFeature(int[] exons, int exonStartIndex,
538 String proteinName, String proteinAccessionId,
539 Map<String, String> vals, int codonStart)
541 int exonNumber = exonStartIndex / 2 + 1;
542 SequenceFeature sf = new SequenceFeature();
543 sf.setBegin(Math.min(exons[exonStartIndex], exons[exonStartIndex + 1]));
544 sf.setEnd(Math.max(exons[exonStartIndex], exons[exonStartIndex + 1]));
545 sf.setDescription(String.format("Exon %d for protein '%s' EMBLCDS:%s",
546 exonNumber, proteinName, proteinAccessionId));
547 sf.setPhase(String.valueOf(codonStart - 1));
548 sf.setStrand(exons[exonStartIndex] <= exons[exonStartIndex + 1] ? "+"
550 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
551 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
554 StringBuilder sb = new StringBuilder();
555 boolean first = true;
556 for (Entry<String, String> val : vals.entrySet())
562 sb.append(val.getKey()).append("=").append(val.getValue());
564 sf.setValue(val.getKey(), val.getValue());
566 sf.setAttributes(sb.toString());
572 * Returns the CDS positions as a single array of [start, end, start, end...]
573 * positions. If on the reverse strand, these will be in descending order.
578 protected int[] getCdsRanges(EmblFeature feature)
580 if (feature.location == null)
587 List<int[]> ranges = DnaUtils.parseLocation(feature.location);
588 return listToArray(ranges);
589 } catch (ParseException e)
591 Cache.log.warn(String.format(
592 "Not parsing inexact CDS location %s in ENA %s",
593 feature.location, this.accession));
599 * Converts a list of [start, end] ranges to a single array of [start, end,
605 int[] listToArray(List<int[]> ranges)
607 int[] result = new int[ranges.size() * 2];
609 for (int[] range : ranges)
611 result[i++] = range[0];
612 result[i++] = range[1];
618 * truncate the last exon interval to the prlength'th codon
624 static int[] adjustForProteinLength(int prlength, int[] exon)
626 if (prlength <= 0 || exon == null)
630 int desiredCdsLength = prlength * 3;
631 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
634 * assuming here exon might include stop codon in addition to protein codons
636 if (desiredCdsLength == exonLength
637 || desiredCdsLength == exonLength - 3)
645 origxon = new int[exon.length];
646 System.arraycopy(exon, 0, origxon, 0, exon.length);
648 for (int x = 0; x < exon.length; x += 2)
650 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
651 if (desiredCdsLength <= cdspos)
653 // advanced beyond last codon.
655 if (desiredCdsLength != cdspos)
658 // .println("Truncating final exon interval on region by "
659 // + (cdspos - cdslength));
663 * shrink the final exon - reduce end position if forward
664 * strand, increase it if reverse
666 if (exon[x + 1] >= exon[x])
668 endxon = exon[x + 1] - cdspos + desiredCdsLength;
672 endxon = exon[x + 1] + cdspos - desiredCdsLength;
680 // and trim the exon interval set if necessary
681 int[] nxon = new int[sxpos + 2];
682 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
683 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
690 public String getSequenceVersion()
692 return sequenceVersion;
695 public void setSequenceVersion(String sequenceVersion)
697 this.sequenceVersion = sequenceVersion;
700 public String getSequenceLength()
702 return sequenceLength;
705 public void setSequenceLength(String sequenceLength)
707 this.sequenceLength = sequenceLength;
710 public String getEntryVersion()
715 public void setEntryVersion(String entryVersion)
717 this.entryVersion = entryVersion;
720 public String getMoleculeType()
725 public void setMoleculeType(String moleculeType)
727 this.moleculeType = moleculeType;
730 public String getTopology()
735 public void setTopology(String topology)
737 this.topology = topology;
740 public String getTaxonomicDivision()
742 return taxonomicDivision;
745 public void setTaxonomicDivision(String taxonomicDivision)
747 this.taxonomicDivision = taxonomicDivision;
750 public String getDescription()
755 public void setDescription(String description)
757 this.description = description;
760 public String getFirstPublicDate()
762 return firstPublicDate;
765 public void setFirstPublicDate(String firstPublicDate)
767 this.firstPublicDate = firstPublicDate;
770 public String getFirstPublicRelease()
772 return firstPublicRelease;
775 public void setFirstPublicRelease(String firstPublicRelease)
777 this.firstPublicRelease = firstPublicRelease;
780 public String getLastUpdatedDate()
782 return lastUpdatedDate;
785 public void setLastUpdatedDate(String lastUpdatedDate)
787 this.lastUpdatedDate = lastUpdatedDate;
790 public String getLastUpdatedRelease()
792 return lastUpdatedRelease;
795 public void setLastUpdatedRelease(String lastUpdatedRelease)
797 this.lastUpdatedRelease = lastUpdatedRelease;
800 public String getDataClass()
805 public void setDataClass(String dataClass)
807 this.dataClass = dataClass;