Skip to content

Comparison

fleet.compare pairs a candidate dataset against a base on keys, matches variables by name and returns a comparison report; differences never raise. The .compare() verb on every namespace (SharedVerbsMixin) wraps it for pipelines, and fleet compare wraps it for the shell. See Comparing Datasets for the rules of equality and the exit codes. A comparison that cannot run raises ComparisonError, documented with the other exceptions.

compare

fleet.comparison.compare

compare(
    base,
    candidate,
    *,
    keys,
    by=None,
    pairs=None,
    variables=None,
    abs_tol=0.0,
    rel_tol=0.0,
    ignore_trailing_whitespace=False,
    blank_is_missing=False,
    allow_duplicates=False,
    max_print=50,
    base_name=None,
    candidate_name=None
)

Compare a candidate dataset against a base, PROC COMPARE style.

Observations pair on keys; variables match by name. Equality is exact by default: null equals null, NaN equals NaN, null against NaN differs. abs_tol and rel_tol widen it on the numeric variables and ignore_trailing_whitespace on the string ones; nulls and NaN keep their rule under both. Variables of the same kind (numeric, string, temporal, boolean) but a different dtype compare by value after casting to a common supertype and are listed as dtype differences; variables of different kinds are type conflicts, listed and not compared. An all-null column, which Polars types Null, adopts the other side's dtype. Keys of one kind but different dtypes are cast the same way before pairing. Row order and column order are ignored.

Parameters:

Name Type Description Default
base DataFrame | LazyFrame

The reference dataset, as a DataFrame or LazyFrame.

required
candidate DataFrame | LazyFrame

The dataset measured against the base.

required
keys str | Sequence[str]

Variable(s) that identify one observation on each side. Required; the compare refuses to run when a key is missing or not unique on either side.

required
by str | Sequence[str] | None

Variable(s) the report is sectioned by. They are prepended to keys automatically, so they need not be repeated there, they label the listing's group column, and the observation and values summaries are additionally reported per group. A group present on one side only raises base_only_groups or candidate_only_groups; the verdict stays global.

None
pairs Mapping[str, str] | None

Base variable names mapped to the candidate names that carry them, applied on top of the automatic name matching, so a renamed column is compared rather than reported missing. The report names a paired variable by its base name. A pair whose candidate name is absent reports the base variable as missing from the candidate.

None
variables str | Sequence[str] | None

Restrict the comparison to these variables, in base names. A variable outside the restriction is ignored on both sides: it is neither compared nor reported as missing. The default compares every variable that is not a key. A restriction that names only keys is refused.

None
abs_tol float

Absolute tolerance on the numeric variables. 0.0 (the default) is exact.

0.0
rel_tol float

Relative tolerance on the numeric variables, as a fraction of the base value. 0.0 (the default) is exact. A numeric pair differs when the absolute difference exceeds max(abs_tol, rel_tol * abs(base)); the relative tolerance anchors on the base because the base is the reference, as in SAS and unlike Polars' testing helper. A tolerant comparison is done in Float64, so integers and decimals beyond 2**53 are compared at that precision; the exact default compares them in their own dtype.

0.0
ignore_trailing_whitespace bool

Strip trailing whitespace from both sides of a string before comparing, so SAS's padded character values equal Fleet's stripped ones. String keys are stripped too, before the duplicate-key check, so "S1 " pairs with "S1"; the listing shows the keys stripped and the values as they are. Leading whitespace still differs.

False
blank_is_missing bool

Read an empty string as null on both sides, keys included, as SAS does: SAS has one character missing value, the blank. Use it when one side comes from a tool that kept "" (an R data frame without convert_blanks_to_na). Off by default, because the two frames then give different is_null() results.

False
allow_duplicates bool

Pair duplicate keys by their position within each key group instead of refusing to run. The observation summary then counts the duplicates per side, the duplicate_keys flag is raised and every renderer warns. Order within a key group decides which observations pair, so it is a weaker guarantee than pairing on keys.

False
max_print MaxPrint

Print limits for the text renderer (differences per variable, or a (per_variable, total) pair, or None for everything). The listing on the report is never truncated.

50
base_name str | None

Label for the base in the report, when known.

None
candidate_name str | None

Label for the candidate in the report, when known.

None

Returns:

Name Type Description
A ComparisonReport

class:~fleet.comparison.ComparisonReport. Differences never

ComparisonReport

raise; check report.is_equal and report.flags.

Raises:

Type Description
ComparisonError

A key or BY variable is missing, duplicated (without allow_duplicates) or of an incompatible type on one side, a key reuses a listing column name, a pair or a restriction names a variable no side carries, a restriction names only keys, or a tolerance is negative or not finite.

VerbUsageError

An input is not a Polars frame, or an argument has the wrong type.

Examples:

Prove an independently programmed ADAE reached the production result::

report = fleet.compare(
    adae_prod,
    adae_qc,
    keys=["USUBJID", "AESEQ"],
    base_name="adae (prod)",
    candidate_name="adae (qc)",
)
report.print_report()
assert report.is_equal, report.raised_flags

Section the report by treatment arm, so a difference in one arm stands out::

report = fleet.compare(adsl_prod, adsl_qc, keys="USUBJID", by="TRT01P")
report.observations.per_group

Compare a legacy dataset that named two variables differently, on the variables that are finished::

report = fleet.compare(
    advs_legacy,
    advs_wip,
    keys=["USUBJID", "PARAMCD"],
    pairs={"AVAL": "RESULT"},
    variables=["AVAL", "AVISIT"],
)
Source code in src/fleet/comparison/engine.py
def compare(
    base: pl.DataFrame | pl.LazyFrame,
    candidate: pl.DataFrame | pl.LazyFrame,
    *,
    keys: str | Sequence[str],
    by: str | Sequence[str] | None = None,
    pairs: Mapping[str, str] | None = None,
    variables: str | Sequence[str] | None = None,
    abs_tol: float = 0.0,
    rel_tol: float = 0.0,
    ignore_trailing_whitespace: bool = False,
    blank_is_missing: bool = False,
    allow_duplicates: bool = False,
    max_print: MaxPrint = 50,
    base_name: str | None = None,
    candidate_name: str | None = None,
) -> ComparisonReport:
    """Compare a candidate dataset against a base, PROC COMPARE style.

    Observations pair on ``keys``; variables match by name.  Equality is
    exact by default: null equals null, NaN equals NaN, null against NaN
    differs.  ``abs_tol`` and ``rel_tol`` widen it on the numeric variables
    and ``ignore_trailing_whitespace`` on the string ones; nulls and NaN
    keep their rule under both.  Variables of the same kind (numeric,
    string, temporal, boolean) but a different dtype compare by value after
    casting to a common supertype and are listed as dtype differences;
    variables of different kinds are type conflicts, listed and not
    compared.  An all-null column, which Polars types ``Null``, adopts the
    other side's dtype.  Keys of one kind but different dtypes are cast the
    same way before pairing.  Row order and column order are ignored.

    Args:
        base: The reference dataset, as a DataFrame or LazyFrame.
        candidate: The dataset measured against the base.
        keys: Variable(s) that identify one observation on each side.
            Required; the compare refuses to run when a key is missing or
            not unique on either side.
        by: Variable(s) the report is sectioned by.  They are prepended to
            ``keys`` automatically, so they need not be repeated there,
            they label the listing's ``group`` column, and the observation
            and values summaries are additionally reported per group.  A
            group present on one side only raises ``base_only_groups`` or
            ``candidate_only_groups``; the verdict stays global.
        pairs: Base variable names mapped to the candidate names that carry
            them, applied on top of the automatic name matching, so a
            renamed column is compared rather than reported missing.  The
            report names a paired variable by its **base** name.  A pair
            whose candidate name is absent reports the base variable as
            missing from the candidate.
        variables: Restrict the comparison to these variables, in **base**
            names.  A variable outside the restriction is ignored on both
            sides: it is neither compared nor reported as missing.  The
            default compares every variable that is not a key.  A
            restriction that names only keys is refused.
        abs_tol: Absolute tolerance on the numeric variables.  ``0.0`` (the
            default) is exact.
        rel_tol: Relative tolerance on the numeric variables, as a fraction
            of the **base** value.  ``0.0`` (the default) is exact.  A numeric
            pair differs when the absolute difference exceeds
            ``max(abs_tol, rel_tol * abs(base))``; the relative tolerance
            anchors on the base because the base is the reference, as in
            SAS and unlike Polars' testing helper.
            A tolerant comparison is done in ``Float64``, so integers and
            decimals beyond ``2**53`` are compared at that precision;
            the exact default compares them in their own dtype.
        ignore_trailing_whitespace: Strip trailing whitespace from both
            sides of a string before comparing, so SAS's padded character
            values equal Fleet's stripped ones.  String keys are stripped
            too, before the duplicate-key check, so ``"S1 "`` pairs with
            ``"S1"``; the listing shows the keys stripped and the values as
            they are.  Leading whitespace still differs.
        blank_is_missing: Read an empty string as null on both sides, keys
            included, as SAS does: SAS has one character missing value, the
            blank.  Use it when one side comes from a tool that kept ``""``
            (an R data frame without ``convert_blanks_to_na``).  Off by
            default, because the two frames then give different
            ``is_null()`` results.
        allow_duplicates: Pair duplicate keys by their position within each
            key group instead of refusing to run.  The observation summary
            then counts the duplicates per side, the ``duplicate_keys`` flag
            is raised and every renderer warns.  Order within a key group
            decides which observations pair, so it is a weaker guarantee
            than pairing on keys.
        max_print: Print limits for the text renderer (differences per
            variable, or a ``(per_variable, total)`` pair, or ``None`` for
            everything).  The listing on the report is never truncated.
        base_name: Label for the base in the report, when known.
        candidate_name: Label for the candidate in the report, when known.

    Returns:
        A :class:`~fleet.comparison.ComparisonReport`.  Differences never
        raise; check ``report.is_equal`` and ``report.flags``.

    Raises:
        ComparisonError: A key or BY variable is missing, duplicated (without
            ``allow_duplicates``) or of an incompatible type on one side, a
            key reuses a listing column name, a pair or a restriction names a
            variable no side carries, a restriction names only keys, or a
            tolerance is negative or not finite.
        VerbUsageError: An input is not a Polars frame, or an argument has
            the wrong type.

    Examples:
        Prove an independently programmed ADAE reached the production result::

            report = fleet.compare(
                adae_prod,
                adae_qc,
                keys=["USUBJID", "AESEQ"],
                base_name="adae (prod)",
                candidate_name="adae (qc)",
            )
            report.print_report()
            assert report.is_equal, report.raised_flags

        Section the report by treatment arm, so a difference in one arm
        stands out::

            report = fleet.compare(adsl_prod, adsl_qc, keys="USUBJID", by="TRT01P")
            report.observations.per_group

        Compare a legacy dataset that named two variables differently, on
        the variables that are finished::

            report = fleet.compare(
                advs_legacy,
                advs_wip,
                keys=["USUBJID", "PARAMCD"],
                pairs={"AVAL": "RESULT"},
                variables=["AVAL", "AVISIT"],
            )
    """
    base_lf = _as_lazy(base, "base")
    candidate_lf = _as_lazy(candidate, "candidate")
    by_list = _normalise_by(by)
    key_list = _normalise_keys(keys, by_list)
    _normalise_max_print(max_print)  # validate early, before any work
    base_schema = base_lf.collect_schema()
    candidate_schema = candidate_lf.collect_schema()
    _check_keys_present(key_list, base_schema, candidate_schema)
    # The settings are both the record of the run and the rule the join
    # evaluates, so every option is checked as they are built.
    settings = ComparisonSettings(
        keys=tuple(key_list),
        by=tuple(by_list),
        pairs=_normalise_pairs(pairs, key_list, base_schema),
        variables=_normalise_variables(variables, key_list, base_schema, candidate_schema),
        abs_tol=_normalise_tolerance(abs_tol, "abs_tol"),
        rel_tol=_normalise_tolerance(rel_tol, "rel_tol"),
        ignore_trailing_whitespace=_normalise_flag(
            ignore_trailing_whitespace, "ignore_trailing_whitespace"
        ),
        blank_is_missing=_normalise_flag(blank_is_missing, "blank_is_missing"),
        allow_duplicates=_normalise_flag(allow_duplicates, "allow_duplicates"),
        max_print=max_print,
        base_name=base_name,
        candidate_name=candidate_name,
    )

    key_casts = _key_casts(key_list, base_schema, candidate_schema)
    variables_summary, casts = _classify_variables(
        key_list, base_schema, candidate_schema, settings
    )
    compared = list(variables_summary.compared)
    #: The dtype each compared variable was compared under: the common
    #: supertype where the sides disagreed, the base dtype otherwise.
    compared_dtypes = {c: casts.get(c, base_schema[c]) for c in compared}
    #: The dtype each side stores a compared variable in, before any cast.
    base_dtypes = {c: base_schema[c] for c in compared}
    candidate_dtypes = {c: candidate_schema[settings.pairs.get(c, c)] for c in compared}

    frame = _join(base_lf, candidate_lf, key_list, compared, key_casts, compared_dtypes, settings)
    in_base = pl.col(_IN_BASE).fill_null(False)
    in_candidate = pl.col(_IN_CANDIDATE).fill_null(False)
    duplicates = _duplicates(frame, key_list, in_base, in_candidate, settings.allow_duplicates)

    matched = frame.filter(in_base & in_candidate)
    base_only_keys = frame.filter(in_base & ~in_candidate).select(key_list).sort(key_list)
    candidate_only_keys = frame.filter(~in_base & in_candidate).select(key_list).sort(key_list)
    per_variable, observations_with_differences = _values_summary(matched, compared)
    listing = _listing(
        matched, key_list, by_list, per_variable, compared_dtypes, base_dtypes, candidate_dtypes
    )
    statistics = _statistics(matched, per_variable, compared_dtypes)
    base_only_groups, candidate_only_groups = _one_sided_groups(
        frame, by_list, in_base, in_candidate
    )

    flags = {
        "base_only_variables": bool(variables_summary.base_only),
        "candidate_only_variables": bool(variables_summary.candidate_only),
        "type_conflicts": bool(variables_summary.type_conflicts),
        "base_only_observations": base_only_keys.height > 0,
        "candidate_only_observations": candidate_only_keys.height > 0,
        "values_differ": listing.height > 0,
        "duplicate_keys": any(duplicates),
        "base_only_groups": bool(base_only_groups),
        "candidate_only_groups": bool(candidate_only_groups),
    }
    return ComparisonReport(
        datasets=DatasetSummary(
            base=SideSummary(base_name, frame.filter(in_base).height, len(base_schema)),
            candidate=SideSummary(
                candidate_name, frame.filter(in_candidate).height, len(candidate_schema)
            ),
        ),
        variables=variables_summary,
        observations=ObservationSummary(
            matched=matched.height,
            base_only=base_only_keys.height,
            candidate_only=candidate_only_keys.height,
            base_only_keys=base_only_keys,
            candidate_only_keys=candidate_only_keys,
            base_duplicates=duplicates[0],
            candidate_duplicates=duplicates[1],
            per_group=_observations_per_group(frame, by_list, in_base, in_candidate),
            base_only_groups=base_only_groups,
            candidate_only_groups=candidate_only_groups,
        ),
        values=ValuesSummary(
            per_variable,
            observations_with_differences,
            per_group=_values_per_group(matched, by_list, compared),
        ),
        listing=listing,
        statistics=statistics,
        flags=frozenset(name for name, raised in flags.items() if raised),
        settings=settings,
        version=__version__,
    )

options: show_root_heading: true heading_level: 3

ComparisonReport

fleet.comparison.ComparisonReport dataclass

Outcome of :func:fleet.compare.

Attributes:

Name Type Description
datasets DatasetSummary

Name, rows and variables per side.

variables VariablesSummary

Common, one-sided, conflicting and differently typed variables.

observations ObservationSummary

Matched and one-sided observation counts, with the key values of the one-sided observations, the duplicate counts per side and the per-BY-group breakdown.

values ValuesSummary

Differences per compared variable, and per BY group.

listing DataFrame

Long frame of every differing value, sorted by keys: the key columns, then group (the BY group label, null without BY variables), variable, base and candidate as strings, difference and percent_difference for numeric variables (null otherwise; percent is null when the base is zero or null). Never truncated; max_print only governs what the text and JSON renderers show.

statistics DataFrame

One row per differing variable, in compared order, with the columns of :data:STATISTICS_COLUMNS: differences, its count of differing observations, then the n, mean, std, min and max of the base, the candidate, their difference and its percent, over the matched observations where both sides are finite. An observation null, NaN or infinite on either side is left out the same way, so n counts finite pairs and no measure is NaN or infinite. Only a numeric variable carries the measures; every other kind contributes its count alone.

flags frozenset[str]

The subset of :data:FLAGS this comparison raised.

settings ComparisonSettings

The settings the comparison ran with.

version str

The Fleet version that produced the report.

Source code in src/fleet/comparison/report.py
@dataclass(frozen=True, eq=False)
class ComparisonReport:
    """Outcome of :func:`fleet.compare`.

    Attributes:
        datasets: Name, rows and variables per side.
        variables: Common, one-sided, conflicting and differently typed variables.
        observations: Matched and one-sided observation counts, with the
            key values of the one-sided observations, the duplicate counts
            per side and the per-BY-group breakdown.
        values: Differences per compared variable, and per BY group.
        listing: Long frame of every differing value, sorted by keys: the key
            columns, then ``group`` (the BY group label, null without BY
            variables), ``variable``, ``base`` and ``candidate`` as strings,
            ``difference`` and ``percent_difference`` for numeric variables
            (null otherwise; percent is null when the base is zero or null).
            Never truncated; ``max_print`` only governs what the text and
            JSON renderers show.
        statistics: One row per differing variable, in compared order, with
            the columns of :data:`STATISTICS_COLUMNS`: ``differences``, its
            count of differing observations, then the ``n``, ``mean``,
            ``std``, ``min`` and ``max`` of the base, the candidate, their
            difference and its percent, over the matched observations where
            both sides are finite.  An observation null, NaN or infinite on
            either side is left out the same way, so ``n`` counts finite
            pairs and no measure is NaN or infinite.  Only a numeric
            variable carries the measures; every other kind contributes its
            count alone.
        flags: The subset of :data:`FLAGS` this comparison raised.
        settings: The settings the comparison ran with.
        version: The Fleet version that produced the report.
    """

    datasets: DatasetSummary
    variables: VariablesSummary
    observations: ObservationSummary
    values: ValuesSummary
    listing: pl.DataFrame
    statistics: pl.DataFrame
    flags: frozenset[str]
    settings: ComparisonSettings
    version: str

    @property
    def is_equal(self) -> bool:
        """True only when no flag was raised."""
        return not self.flags

    @property
    def raised_flags(self) -> tuple[str, ...]:
        """The raised flags in their documented order."""
        return tuple(f for f in FLAGS if f in self.flags)

    @property
    def base_label(self) -> str:
        """The base's name as given, or ``"base"``."""
        return self.settings.base_name or "base"

    @property
    def candidate_label(self) -> str:
        """The candidate's name as given, or ``"candidate"``."""
        return self.settings.candidate_name or "candidate"

    @property
    def summary(self) -> str:
        """One line: verdict, sides, matched observations, compared variables, flags."""
        verdict = "EQUAL" if self.is_equal else "NOT EQUAL"
        line = (
            f"{verdict} - {self.base_label} vs {self.candidate_label}: "
            f"{self.observations.matched} matched observations, "
            f"{len(self.variables.compared)} variables compared"
        )
        if self.flags:
            line += f"; flags: {', '.join(self.raised_flags)}"
        return line

    @property
    def warnings(self) -> tuple[str, ...]:
        """What every renderer says above the report; empty when nothing needs saying.

        Pairing duplicate keys by position is a weaker guarantee than pairing
        on keys, and a compare that checked no values can still be EQUAL
        (ADR-0004), so a reader is told before the first number.
        """
        warnings: list[str] = []
        if "duplicate_keys" in self.flags:
            o = self.observations
            warnings.append(
                "Duplicate keys were paired by position within each key group: "
                f"{_plural(o.base_duplicates, 'duplicate observation')} in the base, "
                f"{o.candidate_duplicates} in the candidate."
            )
        if not self.variables.compared:
            warnings.append("No variables were compared besides the keys.")
        if self.datasets.base.rows == 0 and self.datasets.candidate.rows == 0:
            warnings.append("Both datasets have no observations.")
        return tuple(warnings)

    def to_text(self, max_print: MaxPrint | _Unset = _USE_SETTINGS) -> str:
        """Render the report as plain text in PROC COMPARE section order.

        Sections: data set summary, variables summary, observation summary,
        values summary, summary statistics, value listing grouped per
        observation, verdict.  The print limits cap the value listing (per
        variable first, then overall) and the one-sided observation lists;
        the report's own ``listing`` frame is never truncated.

        Args:
            max_print: Differences to print per variable, a
                ``(per_variable, total)`` pair, or ``None`` for everything.
                Defaults to the ``max_print`` the comparison ran with.

        Returns:
            str: The rendered report, one section per block.

        Examples:
            Keep the full text of a comparison next to a build::

                report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
                Path("adsl_compare.txt").write_text(report.to_text(max_print=None))
        """
        from .text import _render_text

        return _render_text(self, self._print_limits(max_print))

    def print_report(self, max_print: MaxPrint | _Unset = _USE_SETTINGS) -> None:
        """Emit :meth:`to_text` through the ``fleet.comparison`` logger.

        By default the report reaches stdout (INFO level); use the standard
        :mod:`logging` API or :func:`fleet.core.log.disable_console` to route
        or silence it.

        Args:
            max_print: As for :meth:`to_text`.

        Examples:
            Print a QC comparison and gate a script on it::

                report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
                report.print_report()
                assert report.is_equal, report.raised_flags
        """
        fleet_log.ensure_default_handler()
        _logger.info(self.to_text(max_print))

    def to_json(
        self, max_print: MaxPrint | _Unset = _USE_SETTINGS, *, indent: int | None = 2
    ) -> str:
        """Render the report as one JSON document for agents, CI jobs and editors.

        Top-level keys, in order: :data:`JSON_KEYS`.  Field names mirror the
        report attributes and the contract is additive-only within a major
        version (keys are added, never removed or renamed).  The value
        listing and the one-sided key lists are truncated to the print
        limits and carry a ``truncated`` marker; :meth:`save_listing` writes
        the complete listing.  Strict JSON: non-finite numbers are null,
        temporal values are ISO 8601 strings.

        Args:
            max_print: As for :meth:`to_text`; governs the listing inside
                the document.
            indent: Passed to :func:`json.dumps`; ``None`` for one line.

        Returns:
            str: The JSON document.

        Examples:
            Let an agent reason about the differences without parsing prose::

                report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
                document = json.loads(report.to_json())
                assert document["is_equal"], document["flags"]
        """
        from .json import _render_json

        return _render_json(self, self._print_limits(max_print), indent)

    def save_json(self, path: str | Path, max_print: MaxPrint | _Unset = _USE_SETTINGS) -> None:
        """Write :meth:`to_json` to *path* (UTF-8, trailing newline).

        Args:
            path: Where to write the document.
            max_print: As for :meth:`to_json`.

        Examples:
            Archive the outcome of a QC comparison next to the build::

                report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
                report.save_json("build/adsl_compare.json")
        """
        Path(path).write_text(self.to_json(max_print) + "\n", encoding="utf-8")

    def to_html(self) -> str:
        """Render the report as one self-contained HTML page for a reviewer.

        The page needs no Python and fetches nothing: its style is embedded
        and there is no script, font or image.  Structural findings (the
        raised flags: one-sided variables and observations, type conflicts,
        ...) are chips at the top; below, only the mismatched observations
        are listed, base and candidate side by side with both cells
        highlighted, one collapsible block per differing variable opening on
        that variable's summary statistics, and one section per BY group when
        the comparison ran with ``by``.
        Nothing is truncated: every unequal value is on the page, whatever
        ``max_print`` the comparison ran with.  For listings beyond a few
        thousand rows, :meth:`save_listing` is the better archive.

        Returns:
            str: The HTML document.

        Examples:
            Hand a reviewer the page instead of a terminal transcript::

                report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
                Path("adae_compare.html").write_text(report.to_html(), encoding="utf-8")
        """
        from .html import _render_html

        return _render_html(self)

    def save_html_report(self, path: str | Path) -> None:
        """Write :meth:`to_html` to *path* (UTF-8).

        Args:
            path: Where to write the page.

        Examples:
            Produce the sign-off page at the end of a QC comparison::

                report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
                report.save_html_report("build/adae_compare.html")
        """
        Path(path).write_text(self.to_html(), encoding="utf-8")

    def save_listing(self, path: str | Path) -> None:
        """Write the complete value listing to *path* as parquet.

        Never truncated: every differing value, with the key columns in their
        own dtypes followed by :data:`LISTING_COLUMNS` (``group``,
        ``variable``, ``base`` and ``candidate`` as strings, ``difference``
        and ``percent_difference`` as floats).  An equal comparison writes an
        empty frame with the same schema.

        Args:
            path: Where to write the parquet file.

        Examples:
            Keep every difference for a reviewer, then query it lazily::

                report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
                report.save_listing("build/adae_differences.parquet")
                worst = pl.scan_parquet("build/adae_differences.parquet").filter(
                    pl.col("percent_difference").abs() > 10
                )
        """
        self.listing.write_parquet(path)

    def _print_limits(self, max_print: MaxPrint | _Unset) -> PrintLimits:
        """Resolve a renderer's ``max_print`` argument, defaulting to the settings'."""
        limit = self.settings.max_print if isinstance(max_print, _Unset) else max_print
        return _normalise_max_print(limit)

    def __str__(self) -> str:
        """The text report with the settings' print limits, so ``print(report)`` reads."""
        return self.to_text()

is_equal property

is_equal

True only when no flag was raised.

raised_flags property

raised_flags

The raised flags in their documented order.

base_label property

base_label

The base's name as given, or "base".

candidate_label property

candidate_label

The candidate's name as given, or "candidate".

summary property

summary

One line: verdict, sides, matched observations, compared variables, flags.

warnings property

warnings

What every renderer says above the report; empty when nothing needs saying.

Pairing duplicate keys by position is a weaker guarantee than pairing on keys, and a compare that checked no values can still be EQUAL (ADR-0004), so a reader is told before the first number.

to_text

to_text(max_print=_USE_SETTINGS)

Render the report as plain text in PROC COMPARE section order.

Sections: data set summary, variables summary, observation summary, values summary, summary statistics, value listing grouped per observation, verdict. The print limits cap the value listing (per variable first, then overall) and the one-sided observation lists; the report's own listing frame is never truncated.

Parameters:

Name Type Description Default
max_print MaxPrint | _Unset

Differences to print per variable, a (per_variable, total) pair, or None for everything. Defaults to the max_print the comparison ran with.

_USE_SETTINGS

Returns:

Name Type Description
str str

The rendered report, one section per block.

Examples:

Keep the full text of a comparison next to a build::

report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
Path("adsl_compare.txt").write_text(report.to_text(max_print=None))
Source code in src/fleet/comparison/report.py
def to_text(self, max_print: MaxPrint | _Unset = _USE_SETTINGS) -> str:
    """Render the report as plain text in PROC COMPARE section order.

    Sections: data set summary, variables summary, observation summary,
    values summary, summary statistics, value listing grouped per
    observation, verdict.  The print limits cap the value listing (per
    variable first, then overall) and the one-sided observation lists;
    the report's own ``listing`` frame is never truncated.

    Args:
        max_print: Differences to print per variable, a
            ``(per_variable, total)`` pair, or ``None`` for everything.
            Defaults to the ``max_print`` the comparison ran with.

    Returns:
        str: The rendered report, one section per block.

    Examples:
        Keep the full text of a comparison next to a build::

            report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
            Path("adsl_compare.txt").write_text(report.to_text(max_print=None))
    """
    from .text import _render_text

    return _render_text(self, self._print_limits(max_print))

print_report

print_report(max_print=_USE_SETTINGS)

Emit :meth:to_text through the fleet.comparison logger.

By default the report reaches stdout (INFO level); use the standard :mod:logging API or :func:fleet.core.log.disable_console to route or silence it.

Parameters:

Name Type Description Default
max_print MaxPrint | _Unset

As for :meth:to_text.

_USE_SETTINGS

Examples:

Print a QC comparison and gate a script on it::

report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
report.print_report()
assert report.is_equal, report.raised_flags
Source code in src/fleet/comparison/report.py
def print_report(self, max_print: MaxPrint | _Unset = _USE_SETTINGS) -> None:
    """Emit :meth:`to_text` through the ``fleet.comparison`` logger.

    By default the report reaches stdout (INFO level); use the standard
    :mod:`logging` API or :func:`fleet.core.log.disable_console` to route
    or silence it.

    Args:
        max_print: As for :meth:`to_text`.

    Examples:
        Print a QC comparison and gate a script on it::

            report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
            report.print_report()
            assert report.is_equal, report.raised_flags
    """
    fleet_log.ensure_default_handler()
    _logger.info(self.to_text(max_print))

to_json

to_json(max_print=_USE_SETTINGS, *, indent=2)

Render the report as one JSON document for agents, CI jobs and editors.

Top-level keys, in order: :data:JSON_KEYS. Field names mirror the report attributes and the contract is additive-only within a major version (keys are added, never removed or renamed). The value listing and the one-sided key lists are truncated to the print limits and carry a truncated marker; :meth:save_listing writes the complete listing. Strict JSON: non-finite numbers are null, temporal values are ISO 8601 strings.

Parameters:

Name Type Description Default
max_print MaxPrint | _Unset

As for :meth:to_text; governs the listing inside the document.

_USE_SETTINGS
indent int | None

Passed to :func:json.dumps; None for one line.

2

Returns:

Name Type Description
str str

The JSON document.

Examples:

Let an agent reason about the differences without parsing prose::

report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
document = json.loads(report.to_json())
assert document["is_equal"], document["flags"]
Source code in src/fleet/comparison/report.py
def to_json(
    self, max_print: MaxPrint | _Unset = _USE_SETTINGS, *, indent: int | None = 2
) -> str:
    """Render the report as one JSON document for agents, CI jobs and editors.

    Top-level keys, in order: :data:`JSON_KEYS`.  Field names mirror the
    report attributes and the contract is additive-only within a major
    version (keys are added, never removed or renamed).  The value
    listing and the one-sided key lists are truncated to the print
    limits and carry a ``truncated`` marker; :meth:`save_listing` writes
    the complete listing.  Strict JSON: non-finite numbers are null,
    temporal values are ISO 8601 strings.

    Args:
        max_print: As for :meth:`to_text`; governs the listing inside
            the document.
        indent: Passed to :func:`json.dumps`; ``None`` for one line.

    Returns:
        str: The JSON document.

    Examples:
        Let an agent reason about the differences without parsing prose::

            report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
            document = json.loads(report.to_json())
            assert document["is_equal"], document["flags"]
    """
    from .json import _render_json

    return _render_json(self, self._print_limits(max_print), indent)

save_json

save_json(path, max_print=_USE_SETTINGS)

Write :meth:to_json to path (UTF-8, trailing newline).

Parameters:

Name Type Description Default
path str | Path

Where to write the document.

required
max_print MaxPrint | _Unset

As for :meth:to_json.

_USE_SETTINGS

Examples:

Archive the outcome of a QC comparison next to the build::

report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
report.save_json("build/adsl_compare.json")
Source code in src/fleet/comparison/report.py
def save_json(self, path: str | Path, max_print: MaxPrint | _Unset = _USE_SETTINGS) -> None:
    """Write :meth:`to_json` to *path* (UTF-8, trailing newline).

    Args:
        path: Where to write the document.
        max_print: As for :meth:`to_json`.

    Examples:
        Archive the outcome of a QC comparison next to the build::

            report = fleet.compare(adsl_prod, adsl_qc, keys=["USUBJID"])
            report.save_json("build/adsl_compare.json")
    """
    Path(path).write_text(self.to_json(max_print) + "\n", encoding="utf-8")

to_html

to_html()

Render the report as one self-contained HTML page for a reviewer.

The page needs no Python and fetches nothing: its style is embedded and there is no script, font or image. Structural findings (the raised flags: one-sided variables and observations, type conflicts, ...) are chips at the top; below, only the mismatched observations are listed, base and candidate side by side with both cells highlighted, one collapsible block per differing variable opening on that variable's summary statistics, and one section per BY group when the comparison ran with by. Nothing is truncated: every unequal value is on the page, whatever max_print the comparison ran with. For listings beyond a few thousand rows, :meth:save_listing is the better archive.

Returns:

Name Type Description
str str

The HTML document.

Examples:

Hand a reviewer the page instead of a terminal transcript::

report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
Path("adae_compare.html").write_text(report.to_html(), encoding="utf-8")
Source code in src/fleet/comparison/report.py
def to_html(self) -> str:
    """Render the report as one self-contained HTML page for a reviewer.

    The page needs no Python and fetches nothing: its style is embedded
    and there is no script, font or image.  Structural findings (the
    raised flags: one-sided variables and observations, type conflicts,
    ...) are chips at the top; below, only the mismatched observations
    are listed, base and candidate side by side with both cells
    highlighted, one collapsible block per differing variable opening on
    that variable's summary statistics, and one section per BY group when
    the comparison ran with ``by``.
    Nothing is truncated: every unequal value is on the page, whatever
    ``max_print`` the comparison ran with.  For listings beyond a few
    thousand rows, :meth:`save_listing` is the better archive.

    Returns:
        str: The HTML document.

    Examples:
        Hand a reviewer the page instead of a terminal transcript::

            report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
            Path("adae_compare.html").write_text(report.to_html(), encoding="utf-8")
    """
    from .html import _render_html

    return _render_html(self)

save_html_report

save_html_report(path)

Write :meth:to_html to path (UTF-8).

Parameters:

Name Type Description Default
path str | Path

Where to write the page.

required

Examples:

Produce the sign-off page at the end of a QC comparison::

report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
report.save_html_report("build/adae_compare.html")
Source code in src/fleet/comparison/report.py
def save_html_report(self, path: str | Path) -> None:
    """Write :meth:`to_html` to *path* (UTF-8).

    Args:
        path: Where to write the page.

    Examples:
        Produce the sign-off page at the end of a QC comparison::

            report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
            report.save_html_report("build/adae_compare.html")
    """
    Path(path).write_text(self.to_html(), encoding="utf-8")

save_listing

save_listing(path)

Write the complete value listing to path as parquet.

Never truncated: every differing value, with the key columns in their own dtypes followed by :data:LISTING_COLUMNS (group, variable, base and candidate as strings, difference and percent_difference as floats). An equal comparison writes an empty frame with the same schema.

Parameters:

Name Type Description Default
path str | Path

Where to write the parquet file.

required

Examples:

Keep every difference for a reviewer, then query it lazily::

report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
report.save_listing("build/adae_differences.parquet")
worst = pl.scan_parquet("build/adae_differences.parquet").filter(
    pl.col("percent_difference").abs() > 10
)
Source code in src/fleet/comparison/report.py
def save_listing(self, path: str | Path) -> None:
    """Write the complete value listing to *path* as parquet.

    Never truncated: every differing value, with the key columns in their
    own dtypes followed by :data:`LISTING_COLUMNS` (``group``,
    ``variable``, ``base`` and ``candidate`` as strings, ``difference``
    and ``percent_difference`` as floats).  An equal comparison writes an
    empty frame with the same schema.

    Args:
        path: Where to write the parquet file.

    Examples:
        Keep every difference for a reviewer, then query it lazily::

            report = fleet.compare(adae_prod, adae_qc, keys=["USUBJID", "AESEQ"])
            report.save_listing("build/adae_differences.parquet")
            worst = pl.scan_parquet("build/adae_differences.parquet").filter(
                pl.col("percent_difference").abs() > 10
            )
    """
    self.listing.write_parquet(path)

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

Summaries

fleet.comparison.DatasetSummary dataclass

Name, rows and variables of the base and the candidate.

Source code in src/fleet/comparison/report.py
@dataclass(frozen=True)
class DatasetSummary:
    """Name, rows and variables of the base and the candidate."""

    base: SideSummary
    candidate: SideSummary

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

fleet.comparison.VariablesSummary dataclass

Which variables were common, one-sided, conflicting or merely differently typed.

Keys are never counted here; they identify observations rather than being compared.

Source code in src/fleet/comparison/report.py
@dataclass(frozen=True)
class VariablesSummary:
    """Which variables were common, one-sided, conflicting or merely differently typed.

    Keys are never counted here; they identify observations rather than
    being compared.
    """

    common: tuple[str, ...]
    base_only: tuple[str, ...]
    candidate_only: tuple[str, ...]
    #: Same name, different kind (numeric against string, ...): listed, not compared.
    type_conflicts: tuple[VariableDtypes, ...]
    #: Same kind, different dtype: compared after casting to a common supertype.
    dtype_differences: tuple[VariableDtypes, ...]

    @property
    def compared(self) -> tuple[str, ...]:
        """The common variables whose values were actually compared."""
        conflicts = {c.variable for c in self.type_conflicts}
        return tuple(v for v in self.common if v not in conflicts)

compared property

compared

The common variables whose values were actually compared.

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

fleet.comparison.ObservationSummary dataclass

How observations paired on the keys, with the key values of the unpaired ones.

Source code in src/fleet/comparison/report.py
@dataclass(frozen=True, eq=False)
class ObservationSummary:
    """How observations paired on the keys, with the key values of the unpaired ones."""

    matched: int
    base_only: int
    candidate_only: int
    #: Key values of the observations found only in the base, sorted by keys.
    base_only_keys: pl.DataFrame
    #: Key values of the observations found only in the candidate, sorted by keys.
    candidate_only_keys: pl.DataFrame
    #: Observations beyond the first in their key group, per side; non-zero only
    #: under ``allow_duplicates``, since duplicates otherwise stop the compare.
    base_duplicates: int = 0
    candidate_duplicates: int = 0
    #: One row per BY group, in group order: ``group`` (str), ``matched``,
    #: ``base_only``, ``candidate_only`` (int).  Empty without BY variables.
    per_group: pl.DataFrame = dataclasses.field(default_factory=lambda: _empty(GROUP_OBSERVATIONS))
    #: Labels of the groups found on one side only.
    base_only_groups: tuple[str, ...] = ()
    candidate_only_groups: tuple[str, ...] = ()

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

fleet.comparison.ValuesSummary dataclass

Differences per compared variable over the matched observations.

Source code in src/fleet/comparison/report.py
@dataclass(frozen=True, eq=False)
class ValuesSummary:
    """Differences per compared variable over the matched observations."""

    #: One row per compared variable: ``variable`` (str), ``differences`` (int).
    per_variable: pl.DataFrame
    observations_with_differences: int
    #: One row per BY group with matched observations, in group order: ``group``
    #: (str), ``variables_with_differences``, ``observations_with_differences``,
    #: ``differences`` (int).  Empty without BY variables.
    per_group: pl.DataFrame = dataclasses.field(default_factory=lambda: _empty(GROUP_VALUES))

    @property
    def variables_with_differences(self) -> int:
        """How many compared variables differ on at least one observation."""
        return self.per_variable.filter(pl.col("differences") > 0).height

    @property
    def total_differences(self) -> int:
        """How many values differ in all, summed over the compared variables."""
        return int(self.per_variable["differences"].sum())

variables_with_differences property

variables_with_differences

How many compared variables differ on at least one observation.

total_differences property

total_differences

How many values differ in all, summed over the compared variables.

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

Settings

The options a comparison ran with, so a run can be reproduced. abs_tol, rel_tol and ignore_trailing_whitespace are the three that change what counts as equal — see tolerances and trailing whitespace. by sections the report per BY group, allow_duplicates pairs duplicate keys by position, and pairs and variables rename and restrict what is compared — see variable pairs and restriction.

fleet.comparison.ComparisonSettings dataclass

The settings a comparison ran with, so a run can be reproduced.

Three of them decide what counts as equal, so this is also where the renderers read the rule in effect from (:attr:equality).

Source code in src/fleet/comparison/report.py
@dataclass(frozen=True)
class ComparisonSettings:
    """The settings a comparison ran with, so a run can be reproduced.

    Three of them decide what counts as equal, so this is also where the
    renderers read the rule in effect from (:attr:`equality`).
    """

    #: The variables observations paired on, BY variables first.
    keys: tuple[str, ...]
    #: The variables the report is sectioned by; they are part of :attr:`keys`.
    by: tuple[str, ...]
    #: Base variable names mapped to the candidate names carrying them, on top
    #: of the automatic name matching; empty when every variable matched by name.
    pairs: dict[str, str]
    #: The variables the comparison was restricted to, in base names; ``None``
    #: when every variable that is not a key was compared.
    variables: tuple[str, ...] | None
    #: Absolute tolerance on the numeric variables; ``0.0`` is exact.
    abs_tol: float
    #: Relative tolerance on the numeric variables, as a fraction of the **base**
    #: value; ``0.0`` is exact.
    rel_tol: float
    #: Whether trailing whitespace was stripped from both sides of a string
    #: before comparing.
    ignore_trailing_whitespace: bool
    #: Whether an empty string read as null on both sides, keys included.
    blank_is_missing: bool
    #: Whether duplicate keys were paired by position instead of stopping the compare.
    allow_duplicates: bool
    max_print: MaxPrint
    base_name: str | None
    candidate_name: str | None

    @property
    def tolerant(self) -> bool:
        """True when either tolerance is set, so numeric values compare within it."""
        return bool(self.abs_tol or self.rel_tol)

    @property
    def pair_labels(self) -> str:
        """The variable pairs as ``BASE = CANDIDATE``, for the report headers; empty when none."""
        return ", ".join(f"{b} = {c}" for b, c in self.pairs.items())

    @property
    def equality(self) -> str:
        """The equality rule in effect, as one phrase for the report headers.

        ``"exact"`` by default, otherwise the tolerances in effect, followed
        by ``"ignoring trailing whitespace"`` when strings were stripped —
        a qualifier rather than a second verdict, so the phrase reads as one
        rule::

            "exact"
            "abs_tol=1e-06, rel_tol=0.001"
            "exact, ignoring trailing whitespace"
        """
        parts = [
            f"abs_tol={self.abs_tol:g}, rel_tol={self.rel_tol:g}" if self.tolerant else "exact"
        ]
        if self.ignore_trailing_whitespace:
            parts.append("ignoring trailing whitespace")
        if self.blank_is_missing:
            parts.append("blank equals missing")
        return ", ".join(parts)

tolerant property

tolerant

True when either tolerance is set, so numeric values compare within it.

pair_labels property

pair_labels

The variable pairs as BASE = CANDIDATE, for the report headers; empty when none.

equality property

equality

The equality rule in effect, as one phrase for the report headers.

"exact" by default, otherwise the tolerances in effect, followed by "ignoring trailing whitespace" when strings were stripped — a qualifier rather than a second verdict, so the phrase reads as one rule::

"exact"
"abs_tol=1e-06, rel_tol=0.001"
"exact, ignoring trailing whitespace"

options: show_root_heading: true heading_level: 3 filters: ["!^_"]