Variants and files API¶
For examples, see file loading, sample queries, and transforms.
Reference genomes¶
varcode.Genome(ensembl_release: Any = None, *, fasta: Optional[Any] = None, verify: bool = True)
¶
Pyensembl Genome + optional chromosome FASTA.
Two source layers under one object:
self.fasta— optional chromosome FASTA. When attached, :meth:sequencereads from it directly; :meth:reference_baseand :meth:reference_rangeprefer it before falling back to transcript cDNA.- Wrapped pyensembl
Genome— transcript annotations + cDNA. Always present; provides the fallback for exonic positions when no FASTA is attached.
The two methods have intentionally different fall-through semantics:
- :meth:
sequence— chromosome FASTA only. Returns""when no FASTA is attached. Mirrors the proposedpyensembl.Genome.sequence()shape from openvax/pyensembl#337 so the eventual upstream migration is mechanical. - :meth:
reference_base/ :meth:reference_range— tiered. FASTA first when attached; otherwise transcript cDNA. Use these when you want "whatever varcode can tell you" about a position.
| PARAMETER | DESCRIPTION |
|---|---|
ensembl_release
|
Release identifier — passes through :func:
TYPE:
|
fasta
|
Optional chromosome FASTA:
varcode does not take ownership of the FASTA object — when the
caller passes a pre-opened
TYPE:
|
verify
|
When True (default) and
TYPE:
|
Examples:
>>> import varcode
>>> g = varcode.Genome(81, fasta="/path/to/GRCh38.fa")
>>> vc = varcode.load_vcf("tumor.vcf", genome=g)
>>> g.sequence("7", 117_480_000, 117_480_050)
'AC...'
Notes
Returned sequence is always uppercase. Soft-masked (lowercase) repeat annotations from the FASTA are dropped — varcode treats all bases uniformly. Callers that need the soft-masking signal should read the FASTA directly.
Equality and hashing fall back to object identity — two
Genome instances wrapping the same pyensembl release compare
unequal. This is intentional: a wrapper with an attached FASTA
and one without are different objects in any sense that matters
for varcode features, even if they share the same reference_name.
Source code in varcode/genome.py
__getattr__(name)
¶
Delegate everything else to the wrapped pyensembl Genome.
Called only when normal attribute lookup fails, so explicit
attributes (_ensembl, fasta, _missing_reference_warned)
still win. Underscore-prefixed names are not delegated — this
prevents infinite recursion when Python's copy / pickle
machinery probes for __deepcopy__ / __reduce__ /
__getstate__ etc., and keeps the wrapper's private state
from accidentally pulling private state from the wrapped
object.
Source code in varcode/genome.py
__dir__()
¶
Include attributes of the wrapped pyensembl Genome so
dir(genome) and IDE auto-completion surface the full
delegated API, not just the wrapper's own attributes.
Source code in varcode/genome.py
sequence(contig: str, start: int, end: int) -> str
¶
Chromosome FASTA sequence on the + strand.
1-based inclusive coordinates. Returns "" when no FASTA is
attached or the contig / range isn't covered.
FASTA-only — does not fall back to transcript cDNA. Use
:meth:reference_base / :meth:reference_range for the
tiered lookup. The split is deliberate: this method mirrors
the proposed pyensembl.Genome.sequence() API so callers
who want raw chromosome bases (and the upstream migration
path) can use it unambiguously.
Source code in varcode/genome.py
reference_base(contig: str, position: int) -> str
¶
Tiered + strand base lookup (FASTA → transcript cDNA → "").
Convenience method delegating to
:func:varcode.genome_sequence.reference_base.
Source code in varcode/genome.py
reference_range(contig: str, start: int, end: int) -> str
¶
Tiered + strand range lookup. All-or-nothing — returns
"" if any position in the range is uncovered by the chosen
source.
Source code in varcode/genome.py
Variants¶
varcode.Variant(contig, start, ref, alt, genome=None, ensembl=None, allow_extended_nucleotides=False, normalize_contig_names=True, convert_ucsc_contig_names=None)
¶
Bases: Serializable
Construct a Variant object.
| PARAMETER | DESCRIPTION |
|---|---|
contig
|
Chromosome that this variant is on
TYPE:
|
start
|
1-based position on the chromosome of first reference nucleotide
TYPE:
|
ref
|
Reference nucleotide(s)
TYPE:
|
alt
|
Alternate nucleotide(s)
TYPE:
|
genome
|
Name of reference genome, Ensembl release number, or object derived from pyensembl.Genome. Default to latest available release of GRCh38
TYPE:
|
ensembl
|
Previous name used instead of 'genome', the two arguments should be mutually exclusive.
TYPE:
|
allow_extended_nucleotides
|
Extended nucleotides include 'Y' for pyrimidies or 'N' for any base
TYPE:
|
normalize_contig_names
|
By default the contig name will be normalized by converting integers to strings (e.g. 1 -> "1"), and converting any letters after "chr" to uppercase (e.g. "chrx" -> "chrX"). If you don't want this behavior then pass normalize_contig_name=False.
TYPE:
|
convert_ucsc_contig_names
|
Setting this argument to True causes UCSC chromosome names to be coverted, such as "chr1" to "1". If the default value (None) is used then it defaults to whether or not a UCSC genome was pass in for the 'genome' argument.
TYPE:
|
Source code in varcode/variant.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
ensembl
property
¶
Deprecated alias for Variant.genome
| RETURNS | DESCRIPTION |
|---|---|
Genome
|
|
trimmed_ref
property
¶
Eventually the field Variant.ref will store the reference nucleotides as given in a VCF or MAF and trimming of any shared prefix/suffix between ref and alt will be done via the properties trimmed_ref and trimmed_alt.
trimmed_alt
property
¶
Eventually the field Variant.ref will store the reference nucleotides as given in a VCF or MAF and trimming of any shared prefix/suffix between ref and alt will be done via the properties trimmed_ref and trimmed_alt.
trimmed_base1_start
property
¶
Currently the field Variant.start carries the base-1 starting position adjusted by trimming any shared prefix between Variant.ref and Variant.alt. Eventually this trimming should be done more explicitly via trimmed_* properties.
trimmed_base1_end
property
¶
Currently the field Variant.end carries the base-1 "last" position of this variant, adjusted by trimming any shared suffix between Variant.ref and Variant.alt. Eventually this trimming should be done more explicitly via trimmed_* properties.
short_description
property
¶
HGVS nomenclature for genomic variants More info: http://www.hgvs.org/mutnomen/
coding_transcripts
property
¶
Protein coding transcripts
genes
property
¶
Return Gene object for all genes which overlap this variant.
gene_ids
property
¶
Return IDs of all genes which overlap this variant. Calling
this method is significantly cheaper than calling Variant.genes(),
which has to issue many more queries to construct each Gene object.
gene_names
property
¶
Return names of all genes which overlap this variant. Calling
this method is significantly cheaper than calling Variant.genes(),
which has to issue many more queries to construct each Gene object.
coding_genes
property
¶
Protein coding transcripts
is_insertion
property
¶
Does this variant represent the insertion of nucleotides into the reference genome?
is_deletion
property
¶
Does this variant represent the deletion of nucleotides from the reference genome?
is_indel
property
¶
Is this variant either an insertion or deletion?
is_snv
property
¶
Is the variant a single nucleotide variant
is_transition
property
¶
Is this variant and pyrimidine to pyrimidine change or purine to purine change
is_transversion
property
¶
Is this variant a pyrimidine to purine change or vice versa
__lt__(other)
¶
Variants are ordered by locus.
to_dict()
¶
We want the original values (un-normalized) field values while serializing since normalization will happen in init.
Source code in varcode/variant.py
effects(raise_on_error=True, annotator=None, phase_resolver=None, rna_resolver=None, germline=None)
¶
Predict the variant's effects on overlapping transcripts.
Splice-disrupting effects are always wrapped in a
:class:varcode.splice_outcomes.SpliceOutcomeSet carrying the
candidate mechanisms (normal splicing, exon skipping, intron
retention, cryptic splice). Mechanism candidates are computed
lazily, so the wrap is cheap. See openvax/varcode#262, #391.
| PARAMETER | DESCRIPTION |
|---|---|
raise_on_error
|
If True, raise on annotation errors; if False, capture per-transcript errors as Failure effects. Failed initial gene/transcript lookups return an empty EffectCollection and log the error.
TYPE:
|
annotator
|
Per-call annotator override.
TYPE:
|
phase_resolver
|
Optional phase-evidence source (typically a
:class:
TYPE:
|
rna_resolver
|
Optional RNA-observed-outcome source. When provided, any
:class:
TYPE:
|
germline
|
Optional patient-germline context. When non-empty, every
per-transcript effect is computed against the patient's
germline-applied transcript instead of the reference.
Codons / splice signals where germline overlaps the
somatic and phase is unknown produce a
:class:
TYPE:
|
Source code in varcode/variant.py
effect_on_transcript(transcript, annotator=None, germline=None, phase_resolver=None)
¶
Annotate one transcript using the same selection as :meth:effects.
Source code in varcode/variant.py
clone_without_ucsc_data()
¶
Clone this variant but discarding the original format of its genome and contig: useful if we want to mix hg19 and GRCh37 variants.
| RETURNS | DESCRIPTION |
|---|---|
Variant
|
|
Source code in varcode/variant.py
varcode.VariantCollection(variants, distinct=True, sort_key=variant_ascending_position_sort_key, sources=None, source_to_metadata_dict={})
¶
Bases: Collection
Construct a VariantCollection from a list of Variant records.
| PARAMETER | DESCRIPTION |
|---|---|
variants
|
Variant objects contained in this VariantCollection
TYPE:
|
distinct
|
Don't keep repeated variants
TYPE:
|
sort_key
|
TYPE:
|
sources
|
Optional set of source names, may be larger than those for which we have metadata dictionaries.
TYPE:
|
source_to_metadata_dict
|
Dictionary mapping each source name (e.g. VCF path) to a dictionary from metadata attributes to values.
TYPE:
|
Source code in varcode/variant_collection.py
metadata
property
¶
The most common usage of a VariantCollection is loading a single VCF, in which case it's annoying to have to always specify that path when accessing metadata fields. This property is meant to both maintain backward compatibility with old versions of Varcode and make the common case easier.
samples
property
¶
Sorted list of sample names present in the collection's
sample_info metadata (empty if no VCFs with sample columns
were loaded).
to_dict()
¶
Since Collection.to_dict() returns a state dictionary with an 'elements' field we have to rename it to 'variants'.
Source code in varcode/variant_collection.py
clone_with_new_elements(new_elements)
¶
Create another VariantCollection of the same class and with same state (including metadata) but possibly different entries.
Warning: metadata is a dictionary keyed by variants. This method leaves that dictionary as-is, which may result in extraneous entries or missing entries.
Source code in varcode/variant_collection.py
effects(raise_on_error=True, annotator=None, phase_resolver=None, rna_resolver=None, germline=None, validate_reference=True)
¶
Splice-disrupting effects are always wrapped in a
:class:varcode.splice_outcomes.SpliceOutcomeSet carrying the
candidate mechanisms (always-on as of varcode 6.0). Mechanism
candidates are computed lazily — only the cheap
NormalSplicing candidate is built eagerly. See
openvax/varcode#262, #391.
| PARAMETER | DESCRIPTION |
|---|---|
raise_on_error
|
If exception is raised while determining effect of variant on a transcript, should it be raised? This default is True, meaning errors result in raised exceptions, otherwise they are only logged.
TYPE:
|
annotator
|
Per-call annotator override applied to every variant in
the collection. See :meth:
TYPE:
|
phase_resolver
|
Optional phase-evidence source (e.g. a
:class:
TYPE:
|
rna_resolver
|
Optional RNA-observed-outcome source. When provided, any
:class:
TYPE:
|
germline
|
Optional patient-germline context. When non-empty, every
per-transcript effect is computed against the patient's
germline-applied transcript instead of the reference.
See :meth:
TYPE:
|
validate_reference
|
Cross-check that the germline context's reference build
matches this collection's reference build before running
annotation. Hard error on mismatch. Set to False if
you've already lifted over and know the builds agree.
Ignored when
TYPE:
|
Source code in varcode/variant_collection.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
reference_names()
¶
All distinct reference names used by Variants in this collection.
| RETURNS | DESCRIPTION |
|---|---|
set of str
|
|
original_reference_names()
¶
Similar to reference_names but preserves UCSC references,
so that a variant collection derived from an hg19 VCF would
return {"hg19"} instead of {"GRCh37"}.
| RETURNS | DESCRIPTION |
|---|---|
set of str
|
|
Source code in varcode/variant_collection.py
groupby_gene_name()
¶
Group variants by the gene names they overlap, which may put each variant in multiple groups.
gene_counts()
¶
Returns number of elements overlapping each gene name. Expects the derived class (VariantCollection or EffectCollection) to have an implementation of groupby_gene_name.
Source code in varcode/variant_collection.py
filter_by_transcript_expression(transcript_expression_dict, min_expression_value=0.0)
¶
Filters variants down to those which have overlap a transcript whose expression value in the transcript_expression_dict argument is greater than min_expression_value.
| PARAMETER | DESCRIPTION |
|---|---|
transcript_expression_dict
|
Dictionary mapping Ensembl transcript IDs to expression estimates (either FPKM or TPM)
TYPE:
|
min_expression_value
|
Threshold above which we'll keep an effect in the result collection
TYPE:
|
Source code in varcode/variant_collection.py
filter_by_gene_expression(gene_expression_dict, min_expression_value=0.0)
¶
Filters variants down to those which have overlap a gene whose expression value in the transcript_expression_dict argument is greater than min_expression_value.
| PARAMETER | DESCRIPTION |
|---|---|
gene_expression_dict
|
Dictionary mapping Ensembl gene IDs to expression estimates (either FPKM or TPM)
TYPE:
|
min_expression_value
|
Threshold above which we'll keep an effect in the result collection
TYPE:
|
Source code in varcode/variant_collection.py
exactly_equal(other)
¶
Comparison between VariantCollection instances that takes into account the info field of Variant instances.
| RETURNS | DESCRIPTION |
|---|---|
True if the variants in this collection equal the variants in the other
|
|
collection. The Variant.info fields are included in the comparison.
|
|
Source code in varcode/variant_collection.py
union(*others, **kwargs)
¶
Returns the union of variants in a several VariantCollection objects.
Source code in varcode/variant_collection.py
intersection(*others, **kwargs)
¶
Returns the intersection of variants in several VariantCollection objects.
Source code in varcode/variant_collection.py
difference(*others, **kwargs)
¶
Returns variants present in this collection but not in any of the others.
Source code in varcode/variant_collection.py
to_dataframe()
¶
Build a DataFrame from this variant collection.
Source code in varcode/variant_collection.py
to_csv(path, include_header=True)
¶
Write this collection to CSV.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Output path.
TYPE:
|
include_header
|
If True (default), prepend
TYPE:
|
Source code in varcode/variant_collection.py
from_csv(path, genome=None, distinct=True, sort_key=variant_ascending_position_sort_key)
classmethod
¶
Rebuild a VariantCollection from a CSV previously written by
VariantCollection.to_csv().
The CSV round-trip is human-readable and easy to inspect. For
byte-for-byte round-trip or for faster loading of large
collections (≳10k variants), prefer from_json — CSV parsing
plus per-row Variant construction is significantly slower.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the CSV file. Lines starting with '#' are treated as
comments and parsed as
TYPE:
|
genome
|
Reference genome to associate with the loaded variants. If
TYPE:
|
distinct
|
Drop duplicate variants (same as the constructor).
TYPE:
|
sort_key
|
Sort key for the resulting collection.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
VariantCollection
|
|
Source code in varcode/variant_collection.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | |
has_sample_data()
¶
genotype(variant, sample)
¶
Return the Genotype for sample at variant.
| PARAMETER | DESCRIPTION |
|---|---|
variant
|
TYPE:
|
sample
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Genotype or None
|
|
| RAISES | DESCRIPTION |
|---|---|
SampleNotFoundError
|
If the variant's metadata exists but doesn't include the
requested sample. Subclass of |
Source code in varcode/variant_collection.py
zygosity(variant, sample)
¶
Zygosity of the given sample at the given variant.
Multi-allelic aware: at a site split into multiple Variants, each asks "does this sample carry this alt?".
Source code in varcode/variant_collection.py
for_sample(sample)
¶
Return a VariantCollection restricted to variants where
sample carries the alt (heterozygous or homozygous). Useful
for multi-sample VCFs where not every row is called in every
sample.
Source code in varcode/variant_collection.py
heterozygous_in(sample)
¶
Variants where sample is heterozygous for this variant's alt.
homozygous_alt_in(sample)
¶
Variants where sample is homozygous for this variant's alt.
varcode.StructuralVariant(contig: str, start: int, sv_type: str, end: Optional[int] = None, alt: Optional[str] = None, ref: str = 'N', mate_contig: Optional[str] = None, mate_start: Optional[int] = None, mate_orientation: Optional[str] = None, ci_start: Optional[Tuple[int, int]] = None, ci_end: Optional[Tuple[int, int]] = None, alt_assembly: Optional[str] = None, info: Optional[Mapping[str, Any]] = None, genome=None, ensembl=None, normalize_contig_names: bool = True, convert_ucsc_contig_names=None, affected_start: Optional[int] = None, affected_end: Optional[int] = None)
¶
Bases: Variant
A structural variant — deletion, duplication, inversion, insertion, CNV, or breakend — too large or too complex to represent as a simple ref/alt nucleotide pair.
Subclasses :class:Variant so isinstance(v, Variant) still
works; downstream code that handles variant kinds generically
(effect collections, serialization) sees a :class:Variant and
the shared contract still applies. The SV-specific fields
(:attr:sv_type, :attr:end, breakend mate fields) live here
and are consulted by SV-aware code.
The SV position model:
- :attr:
start— 1-based event/record position (matches VCF POS). For parsed symbolic spans this is the retained padding base. - :attr:
end— 1-based inclusive end. For a DEL/DUP/INV/CNV this is the SV endpoint on the same contig. For an INS it equals start (insertions are zero-width in reference coords). For a BND,end == startand the other breakpoint lives in :attr:mate_contig/ :attr:mate_start. - :attr:
affected_start/ :attr:affected_end— inclusive bases changed by a span event. These normally equalstart/end; parsed symbolic spans and paired breakend events use them to exclude retained VCF padding bases from exon and mutant-sequence annotation.
| PARAMETER | DESCRIPTION |
|---|---|
contig
|
Chromosome of the (first) breakpoint.
TYPE:
|
start
|
1-based start position.
TYPE:
|
sv_type
|
One of :data:
TYPE:
|
end
|
1-based inclusive end position. Defaults to
TYPE:
|
alt
|
Original ALT field from the VCF —
TYPE:
|
ref
|
Original REF base (usually one nucleotide, the anchor).
Defaults to
TYPE:
|
mate_contig
|
For BND: the mate breakpoint's chromosome. Normalized the same
way as
TYPE:
|
mate_start
|
For BND: the mate breakpoint's position.
TYPE:
|
mate_orientation
|
For BND: one of
TYPE:
|
ci_start
|
Confidence interval around
TYPE:
|
ci_end
|
Confidence interval around
TYPE:
|
alt_assembly
|
Caller-supplied assembled sequence of the rearranged allele. Hook for long-read / targeted-assembly pipelines. The SV annotator can prefer this over inferring from breakpoints.
TYPE:
|
info
|
Open-ended bag for extra VCF INFO fields the core class doesn't model (HOMLEN, SVMETHOD, MATEID, etc.). Kept as a Mapping so callers can pass whatever shape their caller produces.
TYPE:
|
genome
|
Same meaning as :class:
DEFAULT:
|
ensembl
|
Same meaning as :class:
DEFAULT:
|
normalize_contig_names
|
Same meaning as :class:
DEFAULT:
|
convert_ucsc_contig_names
|
Same meaning as :class:
DEFAULT:
|
affected_start
|
Inclusive affected-region coordinates. Defaults to
TYPE:
|
affected_end
|
Inclusive affected-region coordinates. Defaults to
TYPE:
|
Source code in varcode/structural_variant.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
symbolic_alt: str
property
¶
The original symbolic / breakend ALT string from the VCF.
junctions: Tuple[Tuple[Breakend, Breakend], ...]
property
¶
The novel adjacencies this variant creates, each a pair of
:class:Breakend ends.
One junction for a breakend record (its own position joined to its mate), and one for a deletion or tandem duplication. A symbolic inversion has two, since it joins both of its ends; an inversion built from one breakend pair has only the junction that pair observed. Empty for insertions, CNVs and single breakends, which have no second end to join.
Positions follow the VCF symbolic-allele convention that
start is the base before the event, so a deletion joins
start (keeping the left side) to end + 1 (keeping the
right side), and a tandem duplication joins end to
start + 1.
breakpoints: Tuple[Tuple[str, int], ...]
property
¶
Distinct (contig, position) breakpoints of this variant's
junctions, for consumers that read sequence around them
(cryptic-exon and splice-window scans). Falls back to the
variant's own start when it has no junction.
length: Optional[int]
property
¶
Length of the SV span in reference coordinates, when
well-defined. None for breakends (the span depends on
the mate, which may be on another contig).
to_dict()
¶
The constructor arguments, so serialization (JSON, pickle) round-trips every SV field rather than only the base locus.
Source code in varcode/structural_variant.py
varcode.parse_symbolic_alt(contig: str, start: int, ref: str, alt: str, info=None, genome=None, normalize_contig_names: bool = True, convert_ucsc_contig_names: Optional[bool] = None) -> Optional[StructuralVariant]
¶
Parse a single symbolic or breakend ALT into a
:class:StructuralVariant. Returns None if the ALT is not
symbolic (the caller keeps handling it as a simple variant).
info is an optional mapping (e.g. a pyvcf INFO dict) that
may carry END, SVTYPE, CIPOS, CIEND, MATEID,
etc. The parser reads those when present but doesn't require
them — the ALT shape alone is enough to distinguish symbolic
from breakend from inline.
normalize_contig_names and convert_ucsc_contig_names mean
the same as for :class:~varcode.Variant and apply to both
contig and a breakend's mate contig. The VCF loader forwards
its own settings.
Source code in varcode/sv_allele_parser.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
varcode.SV_TYPES = frozenset({'DEL', 'DUP', 'INV', 'INS', 'CNV', 'BND'})
module-attribute
¶
Genotypes¶
varcode.Genotype(raw_gt: str, alleles: Tuple[Optional[int], ...], phased: bool = False, phase_set: Optional[int] = None, allele_depths: Optional[Tuple[int, ...]] = None, total_depth: Optional[int] = None, genotype_quality: Optional[int] = None)
dataclass
¶
Bases: DataclassSerializable
One sample's genotype at one variant locus.
The alleles tuple encodes the observed alleles using VCF GT
semantics: 0 is the reference allele, 1 is the first ALT
listed on the VCF row, 2 is the second, and so on. None
indicates a no-call on that haplotype.
For varcode's variant-level API, note that Variant.alt is a
specific alt (a multi-allelic VCF row is split into one Variant
per alt). When querying zygosity relative to a Variant, use the
variant's alt_allele_index from the collection's metadata and
add 1 to get the GT-encoded index, then call
:meth:zygosity_for_alt or :meth:carries_alt.
is_called: bool
property
¶
True if at least one allele is non-None.
ploidy: int
property
¶
Number of alleles in the call (including missing).
from_sample_info(sample_info)
classmethod
¶
Build a Genotype from pyvcf's call.data._asdict() output.
Handles the keys varcode normally sees: GT, AD, DP,
GQ, PS. Missing keys default to None.
Source code in varcode/genotype.py
carries_alt(alt_index: int) -> bool
¶
True if this sample's genotype contains the given alt.
alt_index uses VCF GT encoding: 1 is the first alt on
the row, 2 is the second, etc. (i.e. one more than
alt_allele_index from the VariantCollection metadata).
Source code in varcode/genotype.py
copies_of_alt(alt_index: int) -> int
¶
zygosity_for_alt(alt_index: int) -> Zygosity
¶
Classify the sample's zygosity relative to one alt allele.
Multi-allelic aware: GT=1/2 queried for alt 1 returns
HETEROZYGOUS (one copy of this alt, one of a different
alt); queried for alt 3 it returns ABSENT.
Source code in varcode/genotype.py
depth_for_alt(alt_index: int) -> Optional[int]
¶
Per-allele read depth for a given alt, from the AD field.
AD is indexed with ref at position 0 and alt #1 at
position 1, etc., so alt_index should use GT encoding
(1 = first alt).
Source code in varcode/genotype.py
varcode.Zygosity
¶
Bases: Enum
Zygosity of a sample's genotype relative to a specific alt allele.
ABSENT is distinct from MISSING: ABSENT means the call
exists but doesn't include the alt in question (e.g. the sample
is ref-ref, or carries a different alt at a multi-allelic
site). MISSING means the call itself is ./. or the sample
wasn't called.
VariantCollection transforms¶
varcode.transforms.pair_breakends(vc)
¶
Merge MATEID-paired BND rows into a single combined
StructuralVariant per rearrangement event. (reduces)
For each pair of :class:~varcode.StructuralVariant rows where
row A's MATEID references row B's VCF ID (and vice versa),
emit one combined row carrying both endpoints. The combined
variant's source_variants attribute holds the two originals.
Non-BND variants, single-row TRA, and single-ended BNDs (no
MATEID) pass through unchanged with source_variants=().
Pairing rules:
- Primary key:
MATEIDfield on each variant'sinfodict against the VCF row ID stored in the collection's source metadata. - Alias:
PARID(used by older GRIDSS) is treated asMATEID. - Symmetric: row A's
MATEIDmust equal row B's ID and row B'sMATEIDmust equal row A's ID. Asymmetric references are warned and left unpaired. - If a
MATEIDpoints to an ID not present in this collection (filtered out, chunked load), a warning is emitted and the variant passes through unpaired. - If three or more rows share a
MATEIDgroup, the whole group is left unpaired with a warning (pairing is ambiguous). - Already-paired input (
source_variantsnon-empty) passes through unchanged — :func:pair_breakendsis idempotent.
Metadata merge for paired rows:
- Genotype: both halves must agree on the per-sample
GT. The combined variant inherits the shared genotype. Disagreement raises :class:ValueError. alt_assembly: if exactly one half carries an assembled sequence, the combined variant inherits it. If both differ, A's wins (deterministic via lex source-ID ordering) with a warning.filter: union of both halves' FILTER tokens;PASSis dropped if any non-PASS label is present (stricter wins).qual: minimum of the two halves' quality scores.- Other INFO fields: prefer A's; the other half is reachable
via
combined.source_variants.
| PARAMETER | DESCRIPTION |
|---|---|
vc
|
Input collection. May contain a mix of structural and non-structural variants.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
VariantCollection
|
A new collection. SV rows that were halves of paired BNDs are replaced by combined rows; everything else (including SNVs/indels/MNVs and unpaired SVs) passes through. |
Source code in varcode/transforms/__init__.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
varcode.transforms.left_align_indels(vc)
¶
Shift indels to their canonical leftmost equivalent position. (preserves)
Indels in homopolymer or short-tandem-repeat regions can be
represented at any of several equivalent positions — CTT->T
inside a CT-repeat means the same biological event as
CT->_ two positions to the left. Tools that compare variants
by (contig, start, ref, alt) see those representations as
distinct calls. Left-alignment normalizes to a single canonical
representation per indel: the leftmost equivalent position.
The algorithm is the standard variant-normalization left-shift
used by bcftools norm and GATK LeftAlignAndTrimVariants,
applied as an opt-in VariantCollection -> VariantCollection
transform rather than baked into VCF load.
Reference sequence is read via the genome the variants carry —
no explicit reference parameter. Coverage tiers (see
:mod:varcode.genome_sequence):
- Chromosome FASTA attached (via :class:
varcode.Genome'sfastaslot): indels everywhere shift to canonical positions, including in introns and intergenic regions. - No FASTA (default pyensembl install): indels fully within
an exon shift via the transcript cDNA fallback. Intronic and
intergenic indels pass through unchanged. Indels that start
exonic but would shift across an exon boundary stop at the
boundary and carry
info["left_align_partial"] = True.
| PARAMETER | DESCRIPTION |
|---|---|
vc
|
Input collection. May contain a mix of SNVs, MNVs, indels, complex variants, and SVs — only pure indels (length-different REF/ALT with one side empty after suffix trimming) are considered for shifting. Everything else passes through.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
VariantCollection
|
A new collection with indels at their canonical leftmost
positions. Variants that shifted carry
|
See
|
TYPE:
|
six (location × FASTA-attached) combinations and the metadata
|
|
fields the transform writes.
|
|
Examples:
Source code in varcode/transforms/__init__.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 | |
File loading¶
varcode.vcf.load_vcf(path, genome=None, reference_vcf_key='reference', only_passing=True, allow_extended_nucleotides=False, include_info=True, chunk_size=10 ** 5, max_variants=None, sort_key=variant_ascending_position_sort_key, distinct=True, normalize_contig_names=True, convert_ucsc_contig_names=True, parse_structural_variants=False, genome_fasta=None)
¶
Load reference name and Variant objects from the given VCF filename.
Local files are parsed directly. HTTP/HTTPS URLs are downloaded to a
temporary file and load_vcf recurses on the local copy; pandas
doesn't reliably stream gzipped HTTP responses, so we materialize first.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to VCF (.vcf) or compressed VCF (.vcf.gz).
TYPE:
|
genome
|
Optionally pass in a PyEnsembl Genome object, name of reference, or PyEnsembl release version to specify the reference associated with a VCF (otherwise infer reference from VCF using reference_vcf_key)
TYPE:
|
reference_vcf_key
|
Name of metadata field which contains path to reference FASTA file (default = 'reference')
TYPE:
|
only_passing
|
If true, any entries whose FILTER field is not one of "." or "PASS" is dropped.
TYPE:
|
allow_extended_nucleotides
|
Allow characters other that A,C,T,G in the ref and alt strings.
TYPE:
|
include_info
|
Whether to parse the INFO and per-sample columns. If you don't need these, set to False for faster parsing.
TYPE:
|
chunk_size
|
Number of records to load in memory at once.
DEFAULT:
|
max_variants
|
If specified, return only the first max_variants variants.
TYPE:
|
sort_key
|
Function which maps each element to a sorting criterion. Set to None to not to sort the variants.
TYPE:
|
distinct
|
Don't keep repeated variants
TYPE:
|
normalize_contig_names
|
By default contig names will be normalized by converting integers to strings (e.g. 1 -> "1"), and converting any letters after "chr" to uppercase (e.g. "chrx" -> "chrX"). If you don't want this behavior then pass normalize_contig_names=False.
TYPE:
|
convert_ucsc_contig_names
|
Convert chromosome names from hg19 (e.g. "chr1") to equivalent names for GRCh37 (e.g. "1"). By default this is set to True. If None, it also evaluates to True if the genome of the VCF is a UCSC reference.
TYPE:
|
genome_fasta
|
Optionally attach a chromosome FASTA to the resolved genome
before parsing. Equivalent to wrapping with
TYPE:
|
Source code in varcode/vcf.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
varcode.load_maf(path, optional_cols=[], sort_key=variant_ascending_position_sort_key, distinct=True, raise_on_error=True, encoding=None, nrows=None)
¶
Load reference name and Variant objects from MAF filename.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to MAF (*.maf).
TYPE:
|
optional_cols
|
A list of MAF columns to include as metadata if they are present in the MAF. Does not result in an error if those columns are not present.
TYPE:
|
sort_key
|
Function which maps each element to a sorting criterion. Set to None to not to sort the variants.
TYPE:
|
distinct
|
Don't keep repeated variants
TYPE:
|
raise_on_error
|
Raise an exception upon encountering an error or just log a warning.
TYPE:
|
encoding
|
Encoding to use for UTF when reading MAF file.
TYPE:
|
nrows
|
Limit to number of rows loaded
TYPE:
|
Source code in varcode/maf.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
varcode.load_maf_dataframe(path, nrows=None, raise_on_error=True, encoding=None)
¶
Load the guaranteed columns of a TCGA MAF file into a DataFrame
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to MAF file
TYPE:
|
nrows
|
Optional limit to number of rows loaded
TYPE:
|
raise_on_error
|
Raise an exception upon encountering an error or log an error
TYPE:
|
encoding
|
Encoding to use for UTF when reading MAF file.
TYPE:
|
Source code in varcode/maf.py
Exceptions¶
varcode.ReferenceMismatchError(variant, transcript, expected_ref, observed_ref, transcript_offset=None, genome_start=None, genome_end=None)
¶
Bases: ValueError
Raised when a variant's reported ref allele does not match the reference genome at the variant's position.
This most often means one of:
- The variant was called against a different reference build than the one being used for annotation (e.g. GRCh37 vs GRCh38).
- The variant's ref field was populated with the patient's germline allele rather than the canonical reference. VCF requires the ref field to match the reference genome; germline variants at the same position should be encoded as separate variants.
- Strand confusion: the variant is specified on the negative strand but varcode expects positive-strand coordinates.
Callers who would rather continue past this error can pass
raise_on_error=False to :meth:Variant.effects to receive
Failure effects instead.
Source code in varcode/errors.py
varcode.SampleNotFoundError
¶
Bases: KeyError
Raised when genotype info is requested for a sample that isn't present in the VariantCollection's source VCF(s).
varcode.GenomeBuildMismatchError(somatic_reference, germline_reference)
¶
Bases: ValueError
Raised when a germline VCF and a somatic VCF were called against different reference genome builds (e.g. GRCh37 vs GRCh38). Effect coordinates from the two VCFs cannot be meaningfully composed.
Subclasses :class:ValueError so callers that already catch
ValueError for ReferenceMismatchError continue to work.
Set validate_reference=False on the call site if the user
has explicitly lifted over one VCF into the other build and
knows what they're doing.