Skip to content

ORFs API

For installation, reference binding, genetic codes, and evidence limitations, see ORF annotation. Ordinary transcript annotation uses variant.effects(); add extra_orfs= to that workflow when you want an EffectCollection containing additional ORF consequences.

Choose an entry point

Task Entry point Result
Load reference records load_orf_catalog(...) ORFdata catalogue
Annotate a validated reference ORF annotate_orf_variants(variants, reference) ORFAnnotation
Annotate overlapping catalogue records predict_orf_effects(variants, ...) Tuple of ORFAnnotation objects
Compare a mapped observed RNA product annotate_orf_rna_product(reference, product) ORFProductAnnotation
Export the observed-product comparison directly annotate_orf_product(reference, product) Dictionary for JSON export

The tuple from predict_orf_effects is not an EffectCollection. Empty results mean no catalogue model was selected; they do not establish that no ORF can be affected. Keep each annotation's unresolved reason and alternative outcomes. The supplied reference and observed product must retain their coordinate and reference context; a protein string alone cannot supply that mapping.

Annotation functions

varcode.load_orf_catalog(*args, **kwargs)

Load the shared orfdata reference; install varcode[orf] to use it.

Source code in varcode/orf.py
def load_orf_catalog(*args, **kwargs):
    """Load the shared orfdata reference; install ``varcode[orf]`` to use it."""
    try:
        from orfdata import load_catalog as load
    except ImportError as error:
        raise ImportError("Install varcode[orf] for the shared reference catalogue") from error
    return load(*args, **kwargs)

varcode.annotate_orf_variants(variants, reference, **kwargs)

Annotate variants relative to a validated orfdata.ReferenceORF.

The reference's coding fields and reference.evidence describe the base ORF; catalogue record/model are optional. The returned annotation retains that reference and all alternative modified products. The parent RNA can be annotated protein-coding or noncoding. Native peptide detection never establishes mutant translation.

Source code in varcode/orf.py
def annotate_orf_variants(variants, reference, **kwargs):
    """Annotate variants relative to a validated ``orfdata.ReferenceORF``.

    The reference's coding fields and ``reference.evidence`` describe the base
    ORF; catalogue ``record``/``model`` are optional. The returned annotation retains that reference and all alternative
    modified products. The parent RNA can be annotated protein-coding or
    noncoding. Native peptide detection never establishes mutant translation.
    """
    return _annotate_orf_variants(variants, reference.record, reference.transcript,
                                  genome_build=reference.context.genome_build,
                                  reference=reference, **kwargs)

varcode.predict_orf_effects(variants, *, catalog=None, transcripts=None, **kwargs)

Return additive annotations for overlapping catalogue models.

variants is one variant or an explicitly known-cis group. Transcript lookup uses the variant's genome unless an iterable is supplied. Failed model validation is exported as unresolved, never silently discarded. An empty tuple means no reference model overlapped this query, not that the variants cannot create or affect translation upstream of a CDS.

Source code in varcode/orf.py
def predict_orf_effects(variants, *, catalog=None, transcripts=None, **kwargs):
    """Return additive annotations for overlapping catalogue models.

    ``variants`` is one variant or an explicitly known-cis group. Transcript
    lookup uses the variant's genome unless an iterable is supplied. Failed
    model validation is exported as unresolved, never silently discarded.
    An empty tuple means no reference model overlapped this query, not that
    the variants cannot create or affect translation upstream of a CDS.
    """
    variants = (variants,) if hasattr(variants, "contig") else tuple(variants)
    if not variants:
        return ()
    catalog = load_orf_catalog() if catalog is None else catalog
    genome = variants[0].genome
    build = variants[0].reference_name
    if build != catalog.genome_build:
        raise ValueError("Catalogue assembly mismatch")
    by_id = None
    if transcripts is not None:
        by_id = {}
        for transcript in transcripts:
            key = str(transcript.id).split(".")[0]
            if key in by_id:
                raise ValueError("Ambiguous supplied transcript identifier: %s" % key)
            by_id[key] = transcript
    results = []
    for record in catalog.records:
        # Include splice sites inside the ORF envelope and initiation context.
        positions = (record.coding_blocks[0][0], record.coding_blocks[-1][1])
        context = record.initiation_context
        if context is not None:
            positions += tuple(context.genomic_positions)
        if not any(_contig(v.contig, build) == _contig(record.contig, build)
                   and v.start <= max(positions) + 6 and v.end >= min(positions) - 6
                   for v in variants):
            continue
        try:
            key = record.transcript_id.split(".")[0]
            transcript = genome.transcript_by_id(key) if by_id is None else by_id[key]
            annotation = _annotate_orf_variants(
                variants, record, transcript, genome_build=build,
                metadata=catalog.metadata, **kwargs)
        except (KeyError, ValueError) as error:
            from .errors import ReferenceMismatchError
            if isinstance(error, ReferenceMismatchError):
                raise
            # There is no validated transcript to attach a MutationEffect to.
            # Keep the failure at the ORF-annotation boundary instead of
            # manufacturing a transcript or passing None to a transcript effect.
            annotation = ORFAnnotation(
                record=record, effect=None, variants=variants,
                catalogue_metadata=catalog.metadata, unresolved_reason=str(error))
        results.append(annotation)
    return tuple(results)

varcode.annotate_orf_rna_product(reference, product)

Annotate an observed/reconstructed RNA product with mapped base ancestry.

product is a :class:RealizedTranscriptProduct. Its evidence must carry base_origins: one (contig, position, strand) or None per cDNA base. These placements must come from the reconstruction, not peptide similarity. RNA support in product.evidence remains separate from reference MS. Only a uniquely retained complete reference start anchors translation.

Returns an :class:ORFProductAnnotation with native reference, effect and product attributes. Unresolved results have no product and carry a reason. Use to_dict() for JSON export.

Source code in varcode/orf.py
def annotate_orf_rna_product(reference, product):
    """Annotate an observed/reconstructed RNA product with mapped base ancestry.

    ``product`` is a :class:`RealizedTranscriptProduct`. Its evidence must carry
    ``base_origins``: one ``(contig, position, strand)`` or None per cDNA base.
    These placements must come from the reconstruction, not peptide similarity.
    RNA support in ``product.evidence`` remains separate from reference MS.
    Only a uniquely retained complete reference start anchors translation.

    Returns an :class:`ORFProductAnnotation` with native ``reference``,
    ``effect`` and ``product`` attributes. Unresolved results have no product
    and carry a ``reason``. Use ``to_dict()`` for JSON export.
    """
    view = _ORFTranscript(reference)
    record = reference
    product_genome = getattr(product.transcript, "genome", None)
    if product_genome is None:
        raise ValueError("RNA product reference Genome is required")
    from orfdata import ReferenceContext
    # The bound reference is the explicit context for custom Genome metadata
    # gaps. Existing metadata must agree; aliases use the shared taxonomy map.
    ReferenceContext.from_genome(product_genome, context=reference.context)
    sequence = product.cdna_sequence
    origins = product.evidence.get("base_origins", ())
    if sequence is None or len(sequence) != len(origins):
        raise ValueError("A sequence and one base origin per nucleotide are required")
    reason = _unsupported_reference(view) or (None if view.complete else "partial_orf_rna_product_unavailable")
    if reason is not None:
        return ORFProductAnnotation(reference=reference, status="unresolved", reason=reason,
                                    cdna_sequence=sequence, evidence=product.evidence)
    positions = tuple(o[1] if o is not None and _contig(o[0], reference.genome_build) == _contig(record.contig, reference.genome_build)
                      and o[2] == record.strand else None for o in origins)
    starts = [i for i in range(len(positions) - 2)
              if positions[i:i + 3] == tuple(view.start_codon_positions)]
    if len(starts) != 1:
        return ORFProductAnnotation(reference=reference,
                    status="unresolved", reason="reference_start_missing_or_duplicated",
                    cdna_sequence=sequence, evidence=product.evidence)
    start = starts[0]
    table = codon_table_for_transcript(view)
    start_present = sequence[start:start + 3] in table.start_codons
    coding = sequence[start:]
    protein = translate_sequence(coding[:len(coding) // 3 * 3], codon_table=table, to_stop=True) if start_present else ""
    if protein:
        protein = "M" + protein[1:]
    from copy import copy
    product_view = copy(view)
    product_view.start_codon_spliced_offsets = tuple(range(start, start + 3))
    mt = MutantTranscript(reference_transcript=product_view, cdna_sequence=sequence,
                          mutant_protein_sequence=protein,
                          evidence={**product.evidence, "start_codon_offset": start})
    # The shared classifier compares protein outcomes; DNA linkage and source
    # placements remain in the RNA evidence supplied by the caller.
    effect = (classify_from_protein_diff(None, product_view, record.protein_sequence, protein,
                                       mutant_transcript=mt) if start_present else StartLoss(None, view, mutant_transcript=mt))
    observed = RealizedTranscriptProduct(
        view, sequence, protein, product.junction_signature, start_present,
        {**product.evidence, "genomic_positions": positions})
    return ORFProductAnnotation(reference=reference,
                status="conditional_translation", effect=effect,
                product=_product(view, observed), cdna_sequence=sequence,
                evidence=product.evidence)

varcode.annotate_orf_product(reference, product)

Compatibility JSON export; prefer :func:annotate_orf_rna_product.

This original entry point returns a dictionary because downstream RNA exporters embed its result directly in JSON. New Python callers should use annotate_orf_rna_product and access the returned object's attributes.

Source code in varcode/orf.py
def annotate_orf_product(reference, product):
    """Compatibility JSON export; prefer :func:`annotate_orf_rna_product`.

    This original entry point returns a dictionary because downstream RNA
    exporters embed its result directly in JSON. New Python callers should use
    ``annotate_orf_rna_product`` and access the returned object's attributes.
    """
    return annotate_orf_rna_product(reference, product).to_dict()

Result models

varcode.ORFAnnotation(record: Optional[ORFRecord], effect: Optional[MutationEffect], reference: Optional[ReferenceORF] = None, variants: tuple = (), outcomes: Tuple[ORFOutcome, ...] = (), catalogue_metadata: Optional[Mapping] = None, variant_locations: tuple = (), unresolved_reason: Optional[str] = None, unavailable_operations: Mapping = dict()) dataclass

Per-ORF consequences available through outcomes as Python objects.

A failed reference binding leaves reference and effect as None, with an explicit unresolved_reason. to_dict() is for export only.

data property

Compatibility export; use attributes for in-process access.

varcode.ORFOutcome(effect: MutationEffect, baseline: ORFProduct, mutant: Optional[ORFProduct], hypothesis: Optional[EffectHypothesis] = None, probability: Optional[float] = None, phase_mass: Optional[float] = None, source: Optional[str] = None, unresolved_reason: Optional[str] = None) dataclass

One consequence and its baseline/mutant products, with uncertainty intact.

varcode.ORFProduct(cdna_sequence: Optional[str], protein_sequence: Optional[str], start_codon_present: Optional[bool], termination: str, stop_cdna_offset: Optional[int], initiation_context: InitiationContext, junction_signature: tuple = (), evidence: Mapping = dict(), reference_evidence: Mapping = dict()) dataclass

A realized ORF's sequences, initiation context and reference evidence.

Unavailable sequences remain None. Reference peptide retention is not evidence that this product was translated or presented by MHC.

to_dict()

Export the established product schema without changing native fields.

Source code in varcode/orf.py
def to_dict(self):
    """Export the established product schema without changing native fields."""
    context = self.initiation_context
    if context.unavailable_reason:
        initiation = dict(status="unavailable", reason=context.unavailable_reason)
    else:
        initiation = dict(
            upstream=context.upstream, start_codon=context.start_codon,
            downstream=context.downstream, start_offset=context.start_offset,
            five_prime_complete=context.five_prime_complete,
            interpretation="sequence_prior_only; initiation_not_measured")
    return dict(
        cdna_sequence=self.cdna_sequence, protein_sequence=self.protein_sequence,
        start_codon_present=self.start_codon_present, termination=self.termination,
        stop_cdna_offset=self.stop_cdna_offset, initiation_context=initiation,
        junction_signature=_plain(self.junction_signature),
        evidence=_plain(self.evidence), reference_evidence=_plain(self.reference_evidence))

varcode.ORFProductAnnotation(reference: ReferenceORF, status: str, effect: Optional[MutationEffect] = None, product: Optional[ORFProduct] = None, reason: Optional[str] = None, cdna_sequence: Optional[str] = None, evidence: Mapping = dict()) dataclass

Consequence of a mapped RNA product relative to a reference ORF.

Attribute access retains native objects. Use to_dict() for JSON export.

Upstream-ORF compatibility API

These names preserve the earlier record-plus-transcript interface. Prefer the bound-reference functions above for new integrations. The upstream-only catalogue default is retained; the wrappers are not all interchangeable aliases for the general catalogue API.

UORFAnnotation is an alias of ORFAnnotation.

varcode.UORFAnnotation(record: Optional[ORFRecord], effect: Optional[MutationEffect], reference: Optional[ReferenceORF] = None, variants: tuple = (), outcomes: Tuple[ORFOutcome, ...] = (), catalogue_metadata: Optional[Mapping] = None, variant_locations: tuple = (), unresolved_reason: Optional[str] = None, unavailable_operations: Mapping = dict()) dataclass

Per-ORF consequences available through outcomes as Python objects.

A failed reference binding leaves reference and effect as None, with an explicit unresolved_reason. to_dict() is for export only.

varcode.ORFTranscript(record, transcript, *, genome_build, reference_context=None)

Bases: _ORFTranscript

Legacy engine view; use record.bind(transcript) for the base object.

Source code in varcode/uorf.py
def __init__(self, record, transcript, *, genome_build, reference_context=None):
    super().__init__(_bind(record, transcript, genome_build, reference_context=reference_context))

varcode.load_uorf_catalog(*args, **kwargs)

Load the legacy upstream-ORF catalogue through ORFdata.

Arguments are forwarded to orfdata.load_uorf_catalog. Requires the varcode[orf] extra. Use :func:varcode.load_orf_catalog for the general ORF catalogue; this compatibility function keeps its upstream-only selection.

Source code in varcode/uorf.py
def load_uorf_catalog(*args, **kwargs):
    """Load the legacy upstream-ORF catalogue through ORFdata.

    Arguments are forwarded to ``orfdata.load_uorf_catalog``. Requires the
    ``varcode[orf]`` extra. Use :func:`varcode.load_orf_catalog` for the
    general ORF catalogue; this compatibility function keeps its upstream-only
    selection.
    """
    from orfdata import load_uorf_catalog as load
    return load(*args, **kwargs)

varcode.annotate_uorf_variants(variants, record, transcript, *, genome_build, **kwargs)

Annotate variants on a legacy record bound to a supplied transcript.

Returns an :class:varcode.ORFAnnotation. genome_build identifies the record's placement; additional keywords go to the shared ORF annotation engine. New callers can bind the reference and use :func:varcode.annotate_orf_variants directly.

Source code in varcode/uorf.py
def annotate_uorf_variants(variants, record, transcript, *, genome_build, **kwargs):
    """Annotate variants on a legacy record bound to a supplied transcript.

    Returns an :class:`varcode.ORFAnnotation`. ``genome_build`` identifies the
    record's placement; additional keywords go to the shared ORF annotation
    engine. New callers can bind the reference and use
    :func:`varcode.annotate_orf_variants` directly.
    """
    return _annotate_orf_variants(variants, record, transcript,
                                 genome_build=genome_build, **kwargs)

varcode.annotate_uorf_product(record, transcript, product, *, genome_build, reference_context=None)

Compare an observed product with a legacy record/transcript placement.

Returns a JSON-compatible dictionary. The record is bound using genome_build and optional reference_context before delegating to :func:varcode.annotate_orf_product.

Source code in varcode/uorf.py
def annotate_uorf_product(record, transcript, product, *, genome_build, reference_context=None):
    """Compare an observed product with a legacy record/transcript placement.

    Returns a JSON-compatible dictionary. The record is bound using
    ``genome_build`` and optional ``reference_context`` before delegating to
    :func:`varcode.annotate_orf_product`.
    """
    return annotate_orf_product(_bind(record, transcript, genome_build,
                                     reference_context=reference_context), product)

varcode.predict_uorf_effects(variants, *, catalog=None, **kwargs)

Return a tuple of ORFAnnotation objects from the upstream-ORF catalogue.

Omitted catalog loads :func:load_uorf_catalog. Remaining arguments are forwarded to :func:varcode.predict_orf_effects; supply a catalogue explicitly to control its source and reference context.

Source code in varcode/uorf.py
def predict_uorf_effects(variants, *, catalog=None, **kwargs):
    """Return a tuple of ORFAnnotation objects from the upstream-ORF catalogue.

    Omitted ``catalog`` loads :func:`load_uorf_catalog`. Remaining arguments
    are forwarded to :func:`varcode.predict_orf_effects`; supply a catalogue
    explicitly to control its source and reference context.
    """
    return predict_orf_effects(variants,
                              catalog=load_uorf_catalog() if catalog is None else catalog,
                              **kwargs)