Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Conversion

A conversion moves a law to the representation that a distribution class or a capability protocol names, and it keeps the law's event spec. This page documents the convert operation and the converter registry it selects from, and Converter, which a new converter subclasses, is on Registries for extensions.

Converting a law

convert(d, target)

Convert d to the representation target names.

using(method=..., exact_only=...) selects the converter, and using(method_options=...) sets the options the selected converter reads, such as check_support. A converter that draws, such as moment matching, takes num_samples draws: its option of that name when method_options gives one, and otherwise the call's num_samples control, which the call's provenance then records. The converted law keeps d's support. A converter refuses a result on another support unless the option check_support=False overrides the refusal.

Parameters:

Name Type Description Default
d Distribution

The source law.

required
target type

A distribution class or a capability protocol.

required

Returns:

Type Description
Distribution

A law of the target class, or claiming the target protocol, with d's event spec. Under check_support=False its support is the converted law's own, such as the support of a fitted family.

Raises:

Type Description
ApplicabilityError

If target is not a class.

ResolutionError

If d does not satisfy target and no converter applies.

ValueError

If the converted law does not carry d's event spec, which includes its support unless check_support=False.

Source code in probpipe/operations/_convert.py
@_Conversion
def convert(d: Distribution, target: type):
    """Convert *d* to the representation *target* names.

    ``using(method=..., exact_only=...)`` selects the converter, and
    ``using(method_options=...)`` sets the options the selected
    converter reads, such as ``check_support``. A converter that draws, such
    as moment matching, takes ``num_samples`` draws: its option of that name
    when ``method_options`` gives one, and otherwise the call's
    ``num_samples`` control, which the call's provenance then records. The
    converted law keeps *d*'s support. A converter refuses a result on another
    support unless the option ``check_support=False`` overrides the refusal.

    Parameters
    ----------
    d : Distribution
        The source law.
    target : type
        A distribution class or a capability protocol.

    Returns
    -------
    Distribution
        A law of the target class, or claiming the target protocol, with *d*'s
        event spec. Under ``check_support=False`` its support is the
        converted law's own, such as the support of a fitted family.

    Raises
    ------
    ApplicabilityError
        If *target* is not a class.
    ResolutionError
        If *d* does not satisfy *target* and no converter applies.
    ValueError
        If the converted law does not carry *d*'s event spec, which
        includes its support unless ``check_support=False``.
    """

The converter registry

converter_registry = ConverterRegistry(name='converters', description='Converters between representations of a law, keyed on the source type and the target.') module-attribute

The global registry of converters, keyed on the source type and the requested target.

probpipe.distributions.ConverterRegistry(*, name='', description='')

Bases: BinaryDispatchRegistry[Converter]

The binary dispatch registry of converters, keyed on the source type and the target.

The target enters the key as itself, not as its type. A converter admits a requested target when a target it declares is that class or protocol or a subclass of it, so a converter producing a more specific representation or a refined capability serves the request.

The registry's check and execute test the source first: a law that already satisfies the target, its claim and guard included, is reported feasible and exact with no converter selected, and execute returns it as it is. Otherwise a converter is selected as II.7 states, and the registry holds it to the conversion contract:

  1. its check returns a ConversionInfo;
  2. a feasible promise carries the source's event spec;
  3. for a capability target, the promised capabilities include the target or a refinement of it, and a guard of the target that only the converted law can decide leaves the report unresolved, pending that guard;
  4. the converted law carries the source's event spec and satisfies the target, which settles a guard left pending.

The result of a conversion records the source and the converter's name and exactness in its provenance.

Source code in probpipe/core/_dispatch.py
def __init__(self, *, name: str = "", description: str = "") -> None:
    self._name = name
    self._description = description
    self._registrations: list[_Registration[M]] = []
    self._by_name: dict[str, _Registration[M]] = {}
    self._priority_overrides: dict[str, int | None] = {}
    self._type_cache: dict[Any, list[_Registration[M]]] = {}
    self._cache_token = abc.get_cache_token()

check(*args, method=None, exact_only=False, **options)

Report how a conversion would run, without running anything.

Parameters:

Name Type Description Default
*args Any

The source and the target.

()
method str or None

A registered converter to probe instead of auto-selecting.

None
exact_only bool

If True, approximate converters are excluded.

False
**options Any

Converter options, passed to each converter's check.

{}

Returns:

Type Description
ConversionInfo

The report of the source as it is when it satisfies the target or its satisfaction is unresolved; otherwise that of the first converter in selection order that is not infeasible, or of the named one; otherwise an infeasible report listing each converter tried.

Raises:

Type Description
ResolutionError

If method is not a registered name.

TypeError

If there are fewer than two positional arguments, the target is not a class, or a converter's check returns another report type.

ValueError

If a converter promises a law that does not carry the source's event spec.

Source code in probpipe/distributions/_conversion.py
def check(
    self,
    *args: Any,
    method: str | None = None,
    exact_only: bool = False,
    **options: Any,
) -> ConversionInfo:
    """Report how a conversion would run, without running anything.

    Parameters
    ----------
    *args : Any
        The source and the target.
    method : str or None
        A registered converter to probe instead of auto-selecting.
    exact_only : bool
        If ``True``, approximate converters are excluded.
    **options : Any
        Converter options, passed to each converter's ``check``.

    Returns
    -------
    ConversionInfo
        The report of the source as it is when it satisfies the target or
        its satisfaction is unresolved; otherwise that of the first
        converter in selection order that is not infeasible, or of the named
        one; otherwise an infeasible report listing each converter tried.

    Raises
    ------
    ResolutionError
        If *method* is not a registered name.
    TypeError
        If there are fewer than two positional arguments, the target is not
        a class, or a converter's ``check`` returns another report type.
    ValueError
        If a converter promises a law that does not carry the source's event
        spec.
    """
    return self._plan(args, method, exact_only, dict(options), listing=False).info

execute(*args, method=None, exact_only=False, **options)

Convert the source to the target and return the converted law.

A source that already satisfies the target is returned as it is.

Parameters:

Name Type Description Default
*args Any

The source and the target, passed with options to the selected converter's check and execute.

()
method str or None

A registered converter to run instead of auto-selecting.

None
exact_only bool

If True, approximate converters are excluded.

False
**options Any

Converter options, which the selected converter reads; a backend object's event spec is the option event_spec.

{}

Returns:

Type Description
Distribution

The source itself, or the converted law. A converted law that the converter left without provenance records the source and the converter's name and exactness in its provenance.

Raises:

Type Description
ResolutionError

If no converter is feasible, the first converter that is not infeasible is unresolved, method names a converter that is not registered, is infeasible, or is approximate while exact_only is set, or a guard of the target rejects the converted law.

TypeError

As check raises it, or if the converted law is not a Distribution that satisfies the target.

ValueError

If the promise or the converted law does not carry the source's event spec.

Source code in probpipe/distributions/_conversion.py
def execute(
    self,
    *args: Any,
    method: str | None = None,
    exact_only: bool = False,
    **options: Any,
) -> Any:
    """Convert the source to the target and return the converted law.

    A source that already satisfies the target is returned as it is.

    Parameters
    ----------
    *args : Any
        The source and the target, passed with *options* to the selected
        converter's ``check`` and ``execute``.
    method : str or None
        A registered converter to run instead of auto-selecting.
    exact_only : bool
        If ``True``, approximate converters are excluded.
    **options : Any
        Converter options, which the selected converter reads; a backend
        object's event spec is the option ``event_spec``.

    Returns
    -------
    Distribution
        The source itself, or the converted law. A converted law that the
        converter left without provenance records the source and the
        converter's name and exactness in its provenance.

    Raises
    ------
    ResolutionError
        If no converter is feasible, the first converter that is not
        infeasible is unresolved, *method* names a converter that is not
        registered, is infeasible, or is approximate while *exact_only* is
        set, or a guard of the target rejects the converted law.
    TypeError
        As :meth:`check` raises it, or if the converted law is not a
        ``Distribution`` that satisfies the target.
    ValueError
        If the promise or the converted law does not carry the source's
        event spec.
    """
    options = dict(options)
    plan = self._plan(args, method, exact_only, options)
    info = plan.info
    if plan.registration is None and info.feasible is True:
        return args[0]
    if info.feasible is False:
        raise ResolutionError(
            info.description
            if plan.registration is None
            else f"Method {plan.registration.name!r} is not applicable: {info.description}"
        )
    if info.feasible is None and plan.awaiting is None:
        pending = ", ".join(info.pending)
        if plan.registration is None:
            raise ResolutionError(
                f"cannot yet tell whether {public_class_name(type(args[0]))} satisfies "
                f"{_target_name(args[1])}; waiting on: {pending}"
            )
        raise ResolutionError(
            f"Method {plan.registration.name!r} is unresolved; pending: {pending}"
        )
    registration = plan.registration
    result = registration.method.execute(*args, **options)
    self._check_result(registration, args, options, result, plan.awaiting)
    if isinstance(result, TrackedTerm) and result.provenance is None:
        source = args[0]
        result.with_provenance(
            Provenance.create(
                "convert",
                parents=[source] if isinstance(source, TrackedTerm) else [],
                metadata={"converter": registration.name, "exact": registration.exact},
            )
        )
    return result

convert(source, target_type, *, method=None, exact_only=False, **options)

Convert source to target_type, returning a law that satisfies it.

Parameters:

Name Type Description Default
source Distribution or a backend distribution

The law to convert, or a backend object to bring into ProbPipe.

required
target_type type

A distribution class or a capability protocol.

required
method str or None

A registered converter to run instead of auto-selecting.

None
exact_only bool

If True, approximate converters are excluded.

False
**options Any

Converter options, which the selected converter reads; a backend object's event spec is the option event_spec.

{}

Returns:

Type Description
Distribution

source itself when it already satisfies target_type, and otherwise the converted law.

Raises:

Type Description
ResolutionError

If no converter is feasible under the controls, or method names one that is not registered or not applicable.

TypeError

If target_type is not a class, or a converter breaks the conversion contract in kind.

ValueError

If the promise or the converted law does not carry the source's event spec.

Source code in probpipe/distributions/_conversion.py
def convert(
    self,
    source: Any,
    target_type: type,
    *,
    method: str | None = None,
    exact_only: bool = False,
    **options: Any,
) -> Any:
    """Convert *source* to *target_type*, returning a law that satisfies it.

    Parameters
    ----------
    source : Distribution or a backend distribution
        The law to convert, or a backend object to bring into ProbPipe.
    target_type : type
        A distribution class or a capability protocol.
    method : str or None
        A registered converter to run instead of auto-selecting.
    exact_only : bool
        If ``True``, approximate converters are excluded.
    **options : Any
        Converter options, which the selected converter reads; a backend
        object's event spec is the option ``event_spec``.

    Returns
    -------
    Distribution
        *source* itself when it already satisfies *target_type*, and
        otherwise the converted law.

    Raises
    ------
    ResolutionError
        If no converter is feasible under the controls, or *method* names one
        that is not registered or not applicable.
    TypeError
        If *target_type* is not a class, or a converter breaks the
        conversion contract in kind.
    ValueError
        If the promise or the converted law does not carry the source's
        event spec.
    """
    return self.execute(source, target_type, method=method, exact_only=exact_only, **options)

is_distribution_type(obj)

Whether obj is a ProbPipe law or an object a registered converter reads.

A backend distribution counts when a converter declares its type among its sources, so the function engine brings it into ProbPipe.

Source code in probpipe/distributions/_conversion.py
def is_distribution_type(self, obj: Any) -> bool:
    """Whether *obj* is a ProbPipe law or an object a registered converter reads.

    A backend distribution counts when a converter declares its type among
    its sources, so the function engine brings it into ProbPipe.
    """
    if isinstance(obj, Distribution):
        return True
    return any(
        isinstance(obj, source)
        for registration in self._registrations
        for source in registration.supported_types[0]
    )

ConversionInfo(feasible, description='', pending=tuple(), actionable=False, method_name=None, exact=None, target_spec=None, target_class=None, capabilities=(), claims_random_events=False) dataclass

Bases: MethodInfo

The report of one conversion, before it executes.

A converter's check returns one, and the registry's check returns one in every state. A feasible report promises the spec the result carries and states whether executing the conversion claims a random event, and the registry's report also states whether the conversion is exact; an infeasible report leaves the promise at its defaults, which promise nothing.

A converter states only its promise and leaves method_name and exact unset. The registry sets both on the report it returns, from the registration of the converter it selected, so a report from the registry names its converter and carries that converter's declared exactness.

Attributes:

Name Type Description
target_spec DistributionSpec or None

The spec the result will carry, None unless feasible.

target_class type or None

The representation class of the result, when known.

capabilities tuple of type

The capability protocols guaranteed on the result.

claims_random_events bool

True when executing the conversion claims at least one workflow-owned random event (V.8), so its result depends on the workflow scope's seed; a shipped converter claims one when it draws from the source. False when it claims none, so its result is a deterministic function of the source and the converter options. check decides it without drawing, and a report that selects no converter states False.

Raises:

Type Description
TypeError

If claims_random_events is not a bool, or on a condition Feasibility rejects.

ValueError

If method_name is set without exact; if exact is set without method_name on a report that is infeasible or not exact; if a feasible report promises no target_spec; or on a condition Feasibility rejects.

Notes

ConversionInfo relaxes the rule of MethodInfo that a feasible or unresolved report names its method; the rule holds for the registry's report of a selected converter. A report with no method_name is a converter's own report, before the registry names it; an infeasible report of the registry, whose description lists each converter tried; or the report of a source that already satisfies the target, which needs no conversion and so is exact, with exact=True. The pending requirements of an unresolved report are those of Feasibility.