Skip to content

Gr1 iocontract

Typed GR(1) assume-guarantee contracts with bounded next formulas.

The public representation separates temporal structure from Boolean/arithmetic cores. Each term belongs to one of three buckets:

INIT(phi) phi must hold in the first state. INV(phi) phi must hold at every state (the GR(1) formula always phi). LIV(phi) phi must recur infinitely often (always eventually phi).

Several terms in a bucket are conjunctive. Liveness terms deliberately remain separate: LIV(p), LIV(q) means that both p and q recur, not that p and q must recur simultaneously.

Creating a contract from user-facing text

Use :meth:GR1IoContract.from_dict and declare every interface variable's sort. Formula strings use base interface names; time indices are an internal implementation detail::

contract = GR1IoContract.from_dict({
    "input_vars": ["request", "temperature"],
    "output_vars": ["grant"],
    "variable_sorts": {
        "request": "bool",
        "grant": "bool",
        "temperature": "real",
    },
    "assumptions": {
        "init": ["temperature >= 0"],
        "inv": ["temperature <= 100"],
        "liv": ["request"],
    },
    "guarantees": {
        "init": ["!grant"],
        "inv": ["request -> X(grant)"],
        "liv": ["grant"],
    },
})

User-input naming rule

Users must enter and declare base variable names, such as q, grant, and temperature. Do not enter flattened implementation names such as q_0 or q_1 in input_vars, output_vars, variable_sorts, or formula strings. Express temporal depth with the bounded-next operator::

# Correct user input
"input_vars": ["q"]
"variable_sorts": {"q": "bool"}
"inv": ["r = X(q)", "X(X(q)) -> r"]

# Incorrect user input: these names are reserved for internal Z3 use
"input_vars": ["q_0"]
"variable_sorts": {"q_0": "bool"}
"inv": ["r_0 = q_1"]

If q_0 is declared as user input, the parser treats the entire string q_0 as a base name and its current-time internal symbol becomes q_0_0. It does not mean the current value of q. Therefore always write q for the current value, X(q) for the next value, and X(X(q)) for the value two steps ahead.

Supported core syntax includes !/not, &/and, |/or, ->/=>, <->, comparisons, exact decimal and rational arithmetic, parentheses, Boolean literals, and nested X(...) or next(...). For example, X(X(counter)) = counter + 2 is valid when counter is an integer. The outer always and eventually operators are supplied by the bucket; users do not write G, F, or U inside a core. Variables must be declared as bool, int, or real so parsing and serialization never guess a sort.

Next-state flattening and names

The parser retains an immutable :class:GR1SyntaxNode tree for structural renaming and readable serialization, while translating p to p_0, X(p) to p_1, and nested next operators to greater depths for Z3. Contract interfaces always expose the base name p. Formula bookkeeping, relevance, elimination, and renaming understand the relationship between a base name and all of its flattened instances. Renaming p to r thus renames p_0, p_1, and every other depth without accidental textual replacement inside unrelated names.

Generated and serialized output follows the same user-facing convention. For example, a QE result stored internally as q_1 == r_0 is displayed as X(q) = r. Small mixed Boolean/linear QE formulas additionally undergo a conservative interval canonicalization: Boolean modes are enumerated, exact per-mode arithmetic bounds are extracted, and common bounds are factored from conditioned implications. A candidate replaces the executable expression only after Z3 proves it equivalent to the raw QE result. Unsupported formulas fall back unchanged. core.raw_expr and :meth:GR1IoContract.debug_dump retain the solver result, while normal printing uses bucket-oriented canonical formulas and bounded X(...) syntax. Both forms are preserved in versioned gr1_machine serialization for lossless restoration.

For programmatic construction, :class:GR1NextFlattener provides typed Z3 variables and an X operation::

fl = GR1NextFlattener()
request = fl.Bool("request")
grant = fl.Bool("grant")
core = fl.core("request -> X(grant)",
               z3.Implies(request, fl.X(grant)))

Refinement and relaxation

Variable elimination implements the finite-window CAVE constructions. INIT and INV terms are conjoined by bucket before quantifier elimination because existential quantification does not distribute over conjunction. Refinement uses universal implication from the context; relaxation existentially projects the conjunction of context and target. Shifted invariant guards are expanded through the greatest next depth involved, and output variables are recovered from the resulting Z3 expression itself. In particular, INV relaxation uses Gamma_inv^[0:h] through the target invariant's horizon; the target and context roles remain distinct so a context relation such as p=q contributes both p_0=q_0 and p_1=q_1 when needed.

GR(1) composition and quotient operate on canonical bucket obligations. Generic assumption saturation is contract-redundant when no hidden variable remains, but conjoining it into generated cores would erase whether a formula originated as INIT, INV, or a separate LIV liveness term. A GR(1)-specific algebra hook therefore preserves those canonical cores in the redundant case, while falling back to ordinary contextual relaxation whenever assumptions genuinely aid elimination. Quotient CAVE similarly keeps divisor guarantees distinct from system assumptions.

Every target liveness core enters the same complete candidate construction: GF psi_i,0 uses universal implication from the invariant window alone, and G psi_i,j uses that window and the j-th context liveness core, for EVERY j. The synthetic horizon is the target's syntax depth; each genuine support horizon is the maximum of target and support syntax depths. No variable-overlap or viability filter precedes projection. Selection prefers a true core, then a non-false core in canonical synthetic-first order, preserving temporal tags; it makes no global weakestness or temporal Pareto claim. Relaxation projects the complete liveness bucket and then removes true, equivalent, and redundant liveness results. Its standalone decomposed strongestness applies to the raw construction (simplify=False); optional context-relative simplification is a later representation reduction. LIV-only simplification also removes a common global next shift, using GF(X^k(phi)) <=> GF(phi). Relative offsets are preserved: liveness cores p_1 & q_2 and p_3 & q_4 share the canonical core p_0 & q_1, whereas p_1 & q_2 and p_1 & q_3 remain distinct. This narrow rule is not applied to INIT or INV and is not a general LTL simplifier. Separate liveness obligations are never merged into one liveness core.

Unicode presentation is intentionally separate from storage. INIT terms may be displayed as one conjunction, and INV terms may be displayed using □phi ∧ □psi = □(phi ∧ psi). LIV terms are never placed beneath one shared □◇: in general □◇phi ∧ □◇psi is not □◇(phi ∧ psi). These display choices do not modify :class:GR1TermList, serialized text, or machine formulas. At contract level, the Unicode view may additionally reduce guarantees under assumptions. Such a display residual is accepted under the contextual condition A => (G_internal <=> G_display); the full guarantee remains stored and is used by every semantic operation and serialization API.

Post-CAVE semantic reduction

The six CAVE bounds are evaluated literally before redundancy reduction. A separate GR(1)-specific postprocessor may then remove obligations already established by stronger result buckets. In particular, G(phi) establishes phi at time zero, so an INIT consequence implied by the flattened invariant bucket can be removed or reduced modulo that context. Likewise G(phi) implies GF(phi); more generally a LIV core is redundant when the finite shifted invariant closure required by that core implies it. Every partial INIT rewrite is guarded by the SMT proof Gamma_inv_0 & residual <=> Gamma_inv_0 & original. These reductions are post-processing only, are distinct from assumption-relative guarantee reduction, and do not constitute a general LTL minimizer.

Operation-produced contracts retain the pre-reduction buckets in an immutable canonical snapshot. Later composition, quotient, and CAVE elimination consume that snapshot, while a/g and Unicode presentation retain the compact reduced view. The optional versioned gr1_operation_buckets serialization section preserves this distinction across round trips; older dictionaries use their stored buckets as the canonical fallback.

Persistence and behavior checks

Human-facing bounded-next text is the primary serialized representation. Versioned gr1_machine data preserves Z3-generated QE formulas that no longer have a parser AST, together with explicit variable sorts, so contracts round-trip after elimination and renaming.

:class:GR1Behavior represents either a finite trace or an ultimately periodic lasso. INIT and every complete invariant window can be checked on a finite trace. Liveness has trace semantics only when loop_start identifies the repeating suffix. Emptiness is intentionally conservative: inconsistent initial constraints are detected by SMT, while full infinite-state GR(1) realizability is outside the scope of :meth:GR1TermList.is_empty.

GR1Behavior dataclass

A finite trace or an ultimately-periodic lasso used for behavior checks.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@dataclass(frozen=True)
class GR1Behavior:
    """A finite trace or an ultimately-periodic lasso used for behavior checks."""

    states: BehaviorStates
    loop_start: Optional[int] = None

    def __post_init__(self) -> None:
        """Validate the nonempty trace and optional repeating-suffix index.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if not self.states:
            raise ValueError("A GR(1) behavior must contain at least one state")
        if self.loop_start is not None and (self.loop_start < 0 or self.loop_start >= len(self.states)):
            raise ValueError("loop_start must index a state in the behavior")

__post_init__()

Validate the nonempty trace and optional repeating-suffix index.

Raises:

Type Description
ValueError

If the supplied value is invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __post_init__(self) -> None:
    """Validate the nonempty trace and optional repeating-suffix index.

    Raises:
        ValueError: If the supplied value is invalid.
    """
    if not self.states:
        raise ValueError("A GR(1) behavior must contain at least one state")
    if self.loop_start is not None and (self.loop_start < 0 or self.loop_start >= len(self.states)):
        raise ValueError("loop_start must index a state in the behavior")

GR1CoreFormula dataclass

Non-temporal core formula φ.

Use: - of(...) -> text-only formulas - of_expr(...) -> Z3-backed formulas, required for elimination - parse_gr1_core(...) -> parse a typed user-facing bounded-next formula

The only temporal operator allowed inside cores is Next, and it should be flattened before manually creating a Z3 expression. GR1CoreParser performs this flattening for string input. User text uses q and X(q); q_0 and q_1 are reserved for the corresponding internal Z3 constants. Generated text is unflattened again for presentation while expr and vars retain the exact machine-level symbols.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@dataclass(frozen=True)
class GR1CoreFormula:
    """
    Non-temporal core formula φ.

    Use:
    - of(...)       -> text-only formulas
    - of_expr(...)  -> Z3-backed formulas, required for elimination
    - parse_gr1_core(...) -> parse a typed user-facing bounded-next formula

    The only temporal operator allowed inside cores is Next, and it should be
    flattened before manually creating a Z3 expression. GR1CoreParser performs
    this flattening for string input.  User text uses ``q`` and ``X(q)``;
    ``q_0`` and ``q_1`` are reserved for the corresponding internal Z3
    constants.  Generated ``text`` is unflattened again for presentation while
    ``expr`` and ``vars`` retain the exact machine-level symbols.
    """

    text: str
    _vars: FrozenSet[Var]
    expr: Optional[Any] = None
    syntax: Optional[GR1SyntaxNode] = None
    raw_expr: Optional[Any] = field(default=None, compare=False, repr=False)
    serialized_machine: Optional[Dict[str, Any]] = field(default=None, compare=False, repr=False)
    next_depth: int = field(default=0, compare=False)

    @staticmethod
    def of(
        text: str,
        vars: Iterable[Var],  # noqa: A002, VNE003
        expr: Optional[Any] = None,
        syntax: Optional[GR1SyntaxNode] = None,
        raw_expr: Optional[Any] = None,
        serialized_machine: Optional[Dict[str, Any]] = None,
        next_depth: int = 0,
    ) -> "GR1CoreFormula":
        """Build a core, optionally attaching an expression and parser AST.

        Args:
            text: Human-readable formula text.
            vars: Variables occurring in the formula.
            expr: Z3 expression to process.
            syntax: Optional parsed syntax tree.
            raw_expr: Original solver/QE expression retained for debugging.
            serialized_machine: Optional serialized machine representation.
            next_depth: Original finite-window depth before simplification.

        Returns:
            The computed 'GR1CoreFormula' result.
        """
        return GR1CoreFormula(
            text=text,
            _vars=frozenset(vars),
            expr=expr,
            syntax=syntax,
            raw_expr=raw_expr,
            serialized_machine=serialized_machine,
            next_depth=next_depth,
        )

    @staticmethod
    def of_expr(
        text: str,
        vars: Iterable[Var],  # noqa: A002, VNE003
        expr: Any,
        syntax: Optional[GR1SyntaxNode] = None,
        raw_expr: Optional[Any] = None,
        serialized_machine: Optional[Dict[str, Any]] = None,
        next_depth: int = 0,
    ) -> "GR1CoreFormula":
        """Build a core that is guaranteed to have a Z3 expression.

        Args:
            text: Human-readable formula text.
            vars: Variables occurring in the formula.
            expr: Z3 expression to process.
            syntax: Optional parsed syntax tree.
            raw_expr: Original solver/QE expression retained for debugging.
            serialized_machine: Optional serialized machine representation.
            next_depth: Original finite-window depth before simplification.

        Returns:
            The computed 'GR1CoreFormula' result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if expr is None:
            raise ValueError("expr must not be None")
        return GR1CoreFormula(
            text=text,
            _vars=frozenset(vars),
            expr=expr,
            syntax=syntax,
            raw_expr=raw_expr,
            serialized_machine=serialized_machine,
            next_depth=next_depth,
        )

    @staticmethod
    def false() -> "GR1CoreFormula":  # noqa: WPS605
        """Return the variable-free unsatisfiable core.

        Returns:
            The computed 'GR1CoreFormula' result.
        """
        return GR1CoreFormula.of_expr("False", [], expr=z3.BoolVal(False))

    @staticmethod
    def true() -> "GR1CoreFormula":  # noqa: WPS605
        """Return the variable-free tautological core.

        Returns:
            The computed 'GR1CoreFormula' result.
        """
        return GR1CoreFormula.of_expr("True", [], expr=z3.BoolVal(True))

    @property
    def vars(self) -> List[Var]:  # noqa: A003
        """Return flattened variables in deterministic name order.

        Returns:
            The computed List[Var] result.
        """
        return sorted(self._vars, key=lambda v: v.name)

    def contains_var(self, v: Var) -> bool:
        """Return whether the exact flattened variable occurs in this core.

        Args:
            v: V.

        Returns:
            The computed bool result.
        """
        return v in self._vars

    def rename_variable(self, source: Var, target: Var) -> "GR1CoreFormula":
        """Rename a base variable structurally in text, AST, and every Z3 depth.

        Args:
            source: Source variable or name.
            target: Target variable, name, or obligation.

        Returns:
            The computed 'GR1CoreFormula' result.
        """
        if source == target:
            return self

        renamed_syntax = self.syntax.rename(source.name, target.name) if self.syntax is not None else None
        if renamed_syntax is not None:
            new_text = renamed_syntax.to_text()
        else:
            new_text = re.sub(
                rf"(?<![A-Za-z0-9_]){re.escape(source.name)}_(\d+)(?![A-Za-z0-9_])",
                lambda match: f"{target.name}_{match.group(1)}",
                self.text,
            )
            new_text = re.sub(
                f"(?<![A-Za-z0-9_]){re.escape(source.name)}(?![A-Za-z0-9_])",
                target.name,
                new_text,
            )
        if self.expr is None:
            new_vars = {target if v == source else v for v in self._vars}
            return GR1CoreFormula(text=new_text, _vars=frozenset(new_vars), expr=None)

        substitutions = []
        # GETVARS-PATCH: original (disabled) ---
        # for z3_var in get_vars(self.expr):
        # GETVARS-PATCH: replacement ---
        for z3_var in _z3_get_vars(self.expr):
            # GETVARS-PATCH: end ---
            base, depth = _parse_flat_name(z3_var.decl().name())
            if base == source.name:
                substitutions.append((z3_var, z3.Const(_shifted_name(target.name, depth), z3_var.sort())))

        new_expr = z3.substitute(self.expr, *substitutions) if substitutions else self.expr
        renamed_raw = self.raw_expr
        if renamed_raw is not None and substitutions:
            renamed_raw = z3.substitute(renamed_raw, *substitutions)
        return _make_core_from_expr(
            new_expr,
            text=new_text,
            syntax=renamed_syntax,
            raw_expr=renamed_raw,
            next_depth=_core_next_depth(self),
        )

    def __str__(self) -> str:
        """Return the readable core formula.

        Returns:
            The computed str result.
        """
        return self.text

vars property

Return flattened variables in deterministic name order.

Returns:

Type Description
List[Var]

The computed List[Var] result.

__str__()

Return the readable core formula.

Returns:

Type Description
str

The computed str result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __str__(self) -> str:
    """Return the readable core formula.

    Returns:
        The computed str result.
    """
    return self.text

contains_var(v)

Return whether the exact flattened variable occurs in this core.

Parameters:

Name Type Description Default
v Var

V.

required

Returns:

Type Description
bool

The computed bool result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def contains_var(self, v: Var) -> bool:
    """Return whether the exact flattened variable occurs in this core.

    Args:
        v: V.

    Returns:
        The computed bool result.
    """
    return v in self._vars

false() staticmethod

Return the variable-free unsatisfiable core.

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def false() -> "GR1CoreFormula":  # noqa: WPS605
    """Return the variable-free unsatisfiable core.

    Returns:
        The computed 'GR1CoreFormula' result.
    """
    return GR1CoreFormula.of_expr("False", [], expr=z3.BoolVal(False))

of(text, vars, expr=None, syntax=None, raw_expr=None, serialized_machine=None, next_depth=0) staticmethod

Build a core, optionally attaching an expression and parser AST.

Parameters:

Name Type Description Default
text str

Human-readable formula text.

required
vars Iterable[Var]

Variables occurring in the formula.

required
expr Optional[Any]

Z3 expression to process.

None
syntax Optional[GR1SyntaxNode]

Optional parsed syntax tree.

None
raw_expr Optional[Any]

Original solver/QE expression retained for debugging.

None
serialized_machine Optional[Dict[str, Any]]

Optional serialized machine representation.

None
next_depth int

Original finite-window depth before simplification.

0

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def of(
    text: str,
    vars: Iterable[Var],  # noqa: A002, VNE003
    expr: Optional[Any] = None,
    syntax: Optional[GR1SyntaxNode] = None,
    raw_expr: Optional[Any] = None,
    serialized_machine: Optional[Dict[str, Any]] = None,
    next_depth: int = 0,
) -> "GR1CoreFormula":
    """Build a core, optionally attaching an expression and parser AST.

    Args:
        text: Human-readable formula text.
        vars: Variables occurring in the formula.
        expr: Z3 expression to process.
        syntax: Optional parsed syntax tree.
        raw_expr: Original solver/QE expression retained for debugging.
        serialized_machine: Optional serialized machine representation.
        next_depth: Original finite-window depth before simplification.

    Returns:
        The computed 'GR1CoreFormula' result.
    """
    return GR1CoreFormula(
        text=text,
        _vars=frozenset(vars),
        expr=expr,
        syntax=syntax,
        raw_expr=raw_expr,
        serialized_machine=serialized_machine,
        next_depth=next_depth,
    )

of_expr(text, vars, expr, syntax=None, raw_expr=None, serialized_machine=None, next_depth=0) staticmethod

Build a core that is guaranteed to have a Z3 expression.

Parameters:

Name Type Description Default
text str

Human-readable formula text.

required
vars Iterable[Var]

Variables occurring in the formula.

required
expr Any

Z3 expression to process.

required
syntax Optional[GR1SyntaxNode]

Optional parsed syntax tree.

None
raw_expr Optional[Any]

Original solver/QE expression retained for debugging.

None
serialized_machine Optional[Dict[str, Any]]

Optional serialized machine representation.

None
next_depth int

Original finite-window depth before simplification.

0

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Raises:

Type Description
ValueError

If the supplied value is invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def of_expr(
    text: str,
    vars: Iterable[Var],  # noqa: A002, VNE003
    expr: Any,
    syntax: Optional[GR1SyntaxNode] = None,
    raw_expr: Optional[Any] = None,
    serialized_machine: Optional[Dict[str, Any]] = None,
    next_depth: int = 0,
) -> "GR1CoreFormula":
    """Build a core that is guaranteed to have a Z3 expression.

    Args:
        text: Human-readable formula text.
        vars: Variables occurring in the formula.
        expr: Z3 expression to process.
        syntax: Optional parsed syntax tree.
        raw_expr: Original solver/QE expression retained for debugging.
        serialized_machine: Optional serialized machine representation.
        next_depth: Original finite-window depth before simplification.

    Returns:
        The computed 'GR1CoreFormula' result.

    Raises:
        ValueError: If the supplied value is invalid.
    """
    if expr is None:
        raise ValueError("expr must not be None")
    return GR1CoreFormula(
        text=text,
        _vars=frozenset(vars),
        expr=expr,
        syntax=syntax,
        raw_expr=raw_expr,
        serialized_machine=serialized_machine,
        next_depth=next_depth,
    )

rename_variable(source, target)

Rename a base variable structurally in text, AST, and every Z3 depth.

Parameters:

Name Type Description Default
source Var

Source variable or name.

required
target Var

Target variable, name, or obligation.

required

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def rename_variable(self, source: Var, target: Var) -> "GR1CoreFormula":
    """Rename a base variable structurally in text, AST, and every Z3 depth.

    Args:
        source: Source variable or name.
        target: Target variable, name, or obligation.

    Returns:
        The computed 'GR1CoreFormula' result.
    """
    if source == target:
        return self

    renamed_syntax = self.syntax.rename(source.name, target.name) if self.syntax is not None else None
    if renamed_syntax is not None:
        new_text = renamed_syntax.to_text()
    else:
        new_text = re.sub(
            rf"(?<![A-Za-z0-9_]){re.escape(source.name)}_(\d+)(?![A-Za-z0-9_])",
            lambda match: f"{target.name}_{match.group(1)}",
            self.text,
        )
        new_text = re.sub(
            f"(?<![A-Za-z0-9_]){re.escape(source.name)}(?![A-Za-z0-9_])",
            target.name,
            new_text,
        )
    if self.expr is None:
        new_vars = {target if v == source else v for v in self._vars}
        return GR1CoreFormula(text=new_text, _vars=frozenset(new_vars), expr=None)

    substitutions = []
    # GETVARS-PATCH: original (disabled) ---
    # for z3_var in get_vars(self.expr):
    # GETVARS-PATCH: replacement ---
    for z3_var in _z3_get_vars(self.expr):
        # GETVARS-PATCH: end ---
        base, depth = _parse_flat_name(z3_var.decl().name())
        if base == source.name:
            substitutions.append((z3_var, z3.Const(_shifted_name(target.name, depth), z3_var.sort())))

    new_expr = z3.substitute(self.expr, *substitutions) if substitutions else self.expr
    renamed_raw = self.raw_expr
    if renamed_raw is not None and substitutions:
        renamed_raw = z3.substitute(renamed_raw, *substitutions)
    return _make_core_from_expr(
        new_expr,
        text=new_text,
        syntax=renamed_syntax,
        raw_expr=renamed_raw,
        next_depth=_core_next_depth(self),
    )

true() staticmethod

Return the variable-free tautological core.

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def true() -> "GR1CoreFormula":  # noqa: WPS605
    """Return the variable-free tautological core.

    Returns:
        The computed 'GR1CoreFormula' result.
    """
    return GR1CoreFormula.of_expr("True", [], expr=z3.BoolVal(True))

GR1CoreParser

Parse typed bounded-next core formulas into flattened Z3 expressions.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
class GR1CoreParser:
    """Parse typed bounded-next core formulas into flattened Z3 expressions."""

    _TOKEN_RE = re.compile(  # noqa: WPS115
        r"\s*(?:(?P<number>(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)"
        "|(?P<identifier>[A-Za-z_][A-Za-z0-9_]*)"
        r"|(?P<operator><->|->|=>|<=|>=|==|!=|&&|\|\||[()!&|+\-*/<>=]))"
    )

    def __init__(self, variable_sorts: Dict[str, Any]):
        """Initialize from explicit ``name -> bool/int/real`` declarations.

        Args:
            variable_sorts: Declared sort for each base variable.
        """
        self._sorts = {name: _validated_variable_sort(name, sort) for name, sort in variable_sorts.items()}
        self._tokens: List[Tuple[str, str, int]] = []
        self._index = 0

    def parse(self, formula_text: str) -> "GR1CoreFormula":
        """Parse one Boolean core, flattening nested X/next applications.

        Args:
            formula_text: User-facing bounded-next formula.

        Returns:
            The computed 'GR1CoreFormula' result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        self._tokens = self._tokenize(formula_text)
        self._index = 0
        if not self._tokens:
            raise ValueError("GR(1) core formula must not be empty")

        syntax = self._parse_iff()
        if self._index != len(self._tokens):
            _, value, position = self._tokens[self._index]
            raise ValueError(f"Unexpected token {value!r} at position {position}")
        expr = _compile_parser_syntax(syntax, self._sorts, formula_text)
        return _make_core_from_expr(expr, text=syntax.to_text(), syntax=syntax, next_depth=syntax.next_depth())

    def _tokenize(self, formula_text: str) -> List[Tuple[str, str, int]]:
        """Split text into tokens while retaining source positions for errors.

        Args:
            formula_text: User-facing bounded-next formula.

        Returns:
            The computed List[Tuple[str, str, int]] result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        text = formula_text.strip()
        tokens: List[Tuple[str, str, int]] = []
        position = 0
        while position < len(text):
            match = self._TOKEN_RE.match(text, position)
            if match is None:
                raise ValueError(f"Unexpected character {text[position]!r} at position {position}")
            kind = cast(str, match.lastgroup)
            tokens.append((kind, match.group(kind), match.start(kind)))
            position = match.end()
        return tokens

    def _peek(self, *values: str) -> bool:
        """Return whether the next token matches any supplied spelling.

        Args:
            *values: Values to process.

        Returns:
            The computed bool result.
        """
        return self._index < len(self._tokens) and self._tokens[self._index][1].lower() in values

    def _take(self) -> Tuple[str, str, int]:
        """Consume the next token or reject unexpected end of input.

        Returns:
            The computed Tuple[str, str, int] result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if self._index >= len(self._tokens):
            raise ValueError("Unexpected end of GR(1) formula")
        token = self._tokens[self._index]
        self._index += 1
        return token

    def _accept(self, *values: str) -> bool:
        """Consume a matching token and report whether one was present.

        Args:
            *values: Values to process.

        Returns:
            The computed bool result.
        """
        if self._peek(*values):
            self._index += 1
            return True
        return False

    def _expect(self, value: str) -> None:
        """Require and consume ``value`` with a position-aware error.

        Args:
            value: Value to process.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if not self._accept(value):
            position = self._tokens[self._index][2] if self._index < len(self._tokens) else "end"
            raise ValueError(f"Expected {value!r} at position {position}")

    def _parse_iff(self) -> GR1SyntaxNode:
        """Parse the equivalence precedence level.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_implies()
        while self._accept("<->"):
            left = GR1SyntaxNode("binary", "<->", (left, self._parse_implies()))
        return left

    def _parse_implies(self) -> GR1SyntaxNode:
        """Parse right-associative implication.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_or()
        if self._accept("->", "=>"):
            return GR1SyntaxNode("binary", "->", (left, self._parse_implies()))
        return left

    def _parse_or(self) -> GR1SyntaxNode:
        """Parse Boolean disjunction.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_and()
        while self._accept("|", "||", "or"):
            left = GR1SyntaxNode("binary", "or", (left, self._parse_and()))
        return left

    def _parse_and(self) -> GR1SyntaxNode:
        """Parse Boolean conjunction.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_not()
        while self._accept("&", "&&", "and"):
            left = GR1SyntaxNode("binary", "and", (left, self._parse_not()))
        return left

    def _parse_not(self) -> GR1SyntaxNode:
        """Parse Boolean negation.

        Returns:
            The computed GR1SyntaxNode result.
        """
        if self._accept("!", "not"):
            return GR1SyntaxNode("unary", "not", (self._parse_not(),))
        return self._parse_comparison()

    def _parse_comparison(self) -> GR1SyntaxNode:
        """Parse at most one equality or ordered comparison.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_additive()
        if self._peek("=", "==", "!=", "<", "<=", ">", ">="):
            operator = self._take()[1]
            normalized = "=" if operator == "==" else operator
            return GR1SyntaxNode("binary", normalized, (left, self._parse_additive()))
        return left

    def _parse_additive(self) -> GR1SyntaxNode:
        """Parse left-associative addition and subtraction.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_multiplicative()
        while self._peek("+", "-"):
            operator = self._take()[1]
            left = GR1SyntaxNode("binary", operator, (left, self._parse_multiplicative()))
        return left

    def _parse_multiplicative(self) -> GR1SyntaxNode:
        """Parse left-associative multiplication and division.

        Returns:
            The computed GR1SyntaxNode result.
        """
        left = self._parse_unary()
        while self._peek("*", "/"):
            operator = self._take()[1]
            left = GR1SyntaxNode("binary", operator, (left, self._parse_unary()))
        return left

    def _parse_unary(self) -> GR1SyntaxNode:
        """Parse unary numeric signs.

        Returns:
            The computed GR1SyntaxNode result.
        """
        if self._accept("+"):
            return GR1SyntaxNode("unary", "+", (self._parse_unary(),))
        if self._accept("-"):
            return GR1SyntaxNode("unary", "-", (self._parse_unary(),))
        return self._parse_primary()

    def _parse_primary(self) -> GR1SyntaxNode:
        """Parse literals, variables, grouping, and ``X``/``next`` calls.

        Returns:
            The computed GR1SyntaxNode result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if self._accept("("):
            expr = self._parse_iff()
            self._expect(")")
            return expr

        kind, value, position = self._take()
        if kind == "number":
            return GR1SyntaxNode("number", value)
        if kind != "identifier":
            raise ValueError(f"Expected an expression at position {position}, got {value!r}")
        return _parse_identifier_primary(self, value, position)

__init__(variable_sorts)

Initialize from explicit name -> bool/int/real declarations.

Parameters:

Name Type Description Default
variable_sorts Dict[str, Any]

Declared sort for each base variable.

required
Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __init__(self, variable_sorts: Dict[str, Any]):
    """Initialize from explicit ``name -> bool/int/real`` declarations.

    Args:
        variable_sorts: Declared sort for each base variable.
    """
    self._sorts = {name: _validated_variable_sort(name, sort) for name, sort in variable_sorts.items()}
    self._tokens: List[Tuple[str, str, int]] = []
    self._index = 0

parse(formula_text)

Parse one Boolean core, flattening nested X/next applications.

Parameters:

Name Type Description Default
formula_text str

User-facing bounded-next formula.

required

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Raises:

Type Description
ValueError

If the supplied value is invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def parse(self, formula_text: str) -> "GR1CoreFormula":
    """Parse one Boolean core, flattening nested X/next applications.

    Args:
        formula_text: User-facing bounded-next formula.

    Returns:
        The computed 'GR1CoreFormula' result.

    Raises:
        ValueError: If the supplied value is invalid.
    """
    self._tokens = self._tokenize(formula_text)
    self._index = 0
    if not self._tokens:
        raise ValueError("GR(1) core formula must not be empty")

    syntax = self._parse_iff()
    if self._index != len(self._tokens):
        _, value, position = self._tokens[self._index]
        raise ValueError(f"Unexpected token {value!r} at position {position}")
    expr = _compile_parser_syntax(syntax, self._sorts, formula_text)
    return _make_core_from_expr(expr, text=syntax.to_text(), syntax=syntax, next_depth=syntax.next_depth())

GR1IoContract

Bases: IoContract[GR1TermList]

GR(1) IO contract whose assumptions and guarantees are GR1TermLists.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
class GR1IoContract(IoContract[GR1TermList]):  # noqa: WPS124
    """GR(1) IO contract whose assumptions and guarantees are GR1TermLists."""

    def __init__(
        self,
        assumptions: GR1TermList,
        guarantees: GR1TermList,
        input_vars: List[Var],
        output_vars: List[Var],
        simplify: Optional[bool] = None,
        variable_sorts: Optional[Dict[str, Any]] = None,
    ) -> None:
        """Build a contract and validate or infer its persistent sort table.

        Args:
            assumptions: Assumptions.
            guarantees: Guarantees.
            input_vars: Input vars.
            output_vars: Output vars.
            simplify: Whether to simplify the supplied formulas. Internal
                operation construction inherits the operation's explicit raw
                versus final setting.
            variable_sorts: Declared sort for each base variable.
        """
        effective_simplify = _GR1_OPERATION_SIMPLIFY.get() if simplify is None else simplify
        operation_assumptions = assumptions.copy()
        operation_guarantees = guarantees.copy()
        super().__init__(assumptions, guarantees, input_vars, output_vars, effective_simplify)
        self._operation_assumptions = operation_assumptions
        self._operation_guarantees = operation_guarantees

        inferred = _infer_variable_sorts(self.a, self.g)
        self.variable_sorts = _normalized_variable_sorts(variable_sorts, inferred)

    def __copy__(self) -> "GR1IoContract":
        """Return an independent copy including canonical operation buckets.

        Returns:
            Independent contract copy.
        """
        return self.copy()

    def __deepcopy__(self, memo: Dict[int, Any]) -> "GR1IoContract":
        """Return an independent deep copy including canonical operation buckets.

        Args:
            memo: Deep-copy memoization dictionary.

        Returns:
            Independent contract copy.
        """
        del memo
        return self.copy()

    def copy(self) -> "GR1IoContract":
        """Copy the contract while preserving declarations for unused variables.

        Returns:
            The computed 'GR1IoContract' result.
        """
        copied = GR1IoContract(
            assumptions=self.a.copy(),
            guarantees=self.g.copy(),
            input_vars=self.inputvars.copy(),
            output_vars=self.outputvars.copy(),
            simplify=False,
            variable_sorts=self.variable_sorts,
        )
        copied._set_operation_buckets(self._operation_assumptions, self._operation_guarantees)
        return copied

    def canonical_debug_dump(self) -> str:
        """Return canonical operation buckets without changing stored buckets.

        Returns:
            Canonical debug representation.
        """
        canonical = self._operation_copy()
        return canonical.debug_dump()

    def merge(self, other: "GR1IoContract") -> "GR1IoContract":
        """Merge two contracts while preserving every GR(1) bucket.

        GR(1) is closed under contract merge: assumptions and guarantees are
        conjoined bucket by bucket. INIT and INV terms are concatenated as
        ordinary conjunctions. LIV terms are also concatenated as distinct
        clauses, so ``GF(phi) & GF(psi)`` never becomes ``GF(phi & psi)``.
        No abstraction, projection, quantifier elimination, or CAVE machinery
        is invoked.

        Interface variables follow :meth:`IoContract.merge`: inputs and outputs
        are stable unions, and the constructor rejects variables classified as
        both input and output.

        Args:
            other: GR(1) contract to merge with this contract.

        Returns:
            Exact bucket-preserving conjunction of both contracts.

        Raises:
            IncompatibleArgsError: If contract types, interfaces, or sorts are incompatible.
        """
        if not isinstance(self, type(other)):
            raise IncompatibleArgsError("Asked to merge incompatible contracts")
        merged = GR1IoContract(
            assumptions=_merge_gr1_term_lists(self.a, other.a),
            guarantees=_merge_gr1_term_lists(self.g, other.g),
            input_vars=list_union(self.inputvars, other.inputvars),
            output_vars=list_union(self.outputvars, other.outputvars),
            simplify=False,
            variable_sorts=_merge_variable_sort_maps(self.variable_sorts, other.variable_sorts),
        )
        merged._set_operation_buckets(
            _merge_gr1_term_lists(self._operation_assumptions, other._operation_assumptions),
            _merge_gr1_term_lists(self._operation_guarantees, other._operation_guarantees),
        )
        return merged

    def pretty(self, annotate_redundancy: bool = True) -> str:
        """Return a sectioned bucket view using explicit ``G`` and ``GF``.

        Canonical expressions are split into readable conjunction lines. INIT
        guarantee atoms already implied by assumptions are omitted from this
        view only. Stored semantics and serialization remain unchanged. A LIV
        guarantee established by assumption INV/LIV support is retained but may
        be annotated as redundant.

        Args:
            annotate_redundancy: Mark assumption-established liveness terms.

        Returns:
            Human-readable contract text.
        """
        lines = [
            f"inputs:  [{', '.join(variable.name for variable in self.inputvars)}]",
            f"outputs: [{', '.join(variable.name for variable in self.outputvars)}]",
        ]
        lines.extend(
            _pretty_side_lines(
                self,
                "ASSUMPTIONS",
                self.a,
                guarantees=False,
                annotate_redundancy=annotate_redundancy,
            )
        )
        lines.extend(
            _pretty_side_lines(
                self,
                "GUARANTEES",
                self.g,
                guarantees=True,
                annotate_redundancy=annotate_redundancy,
            )
        )
        return "\n".join(lines)

    def presentation_view(
        self,
        candidate_assumptions: Optional[GR1TermList] = None,
        candidate_guarantees: Optional[GR1TermList] = None,
        assumption_relative: bool = True,
    ) -> Tuple[GR1TermList, GR1TermList]:
        """Return detached, SMT-certified buckets intended only for rendering.

        Automatic candidates use inexpensive Z3 tactics and Boolean-mode
        consequence mining. Optional caller candidates are hints, not trusted
        replacements: assumption safety buckets require unconditional
        equivalence, and guarantee safety buckets require equivalence under the
        appropriate shifted contract assumptions. LIV hints are deliberately
        ignored so distinct justice obligations cannot be synchronized.

        Args:
            candidate_assumptions: Optional proposed assumption presentation.
            candidate_guarantees: Optional proposed guarantee presentation.
            assumption_relative: Whether guarantees are reduced under assumptions.

        Returns:
            Detached assumption and guarantee presentation lists.
        """
        true_context = z3.BoolVal(True)
        assumptions = _presentation_safety_view(self.a.copy(), true_context, true_context)
        guarantees = _assumption_relative_guarantee_view(self) if assumption_relative else self.g.copy()
        guarantee_init_context = _assumption_context_for_guarantee_bucket(
            self.a, guarantees.init_terms(), include_init=True
        )
        guarantee_inv_context = _assumption_context_for_guarantee_bucket(
            self.a, guarantees.inv_terms(), include_init=False
        )
        guarantees = _presentation_safety_view(guarantees, guarantee_init_context, guarantee_inv_context)

        assumptions = _replace_presentation_safety_buckets(
            self.a, assumptions, candidate_assumptions, guarantee_side=False
        )
        guarantees = _replace_presentation_safety_buckets(self.a, guarantees, candidate_guarantees, guarantee_side=True)
        return assumptions, guarantees

    def to_pretty_string(
        self,
        compact: bool = False,
        assumption_relative: bool = True,
        candidate_assumptions: Optional[GR1TermList] = None,
        candidate_guarantees: Optional[GR1TermList] = None,
    ) -> str:
        """Return an observational Unicode assume-guarantee contract view.

        This is an additional presentation API. The existing ASCII
        :meth:`pretty`, :meth:`debug_dump`, serialization, and ``__str__``
        behavior remain unchanged.

        Args:
            compact: Render ``A = ...`` and ``G = ...`` instead of bucket views.
            assumption_relative: Reduce only the displayed guarantees under
                assumptions using SMT-verified GR(1) rules. Set to ``False``
                to display every internally stored guarantee.
            candidate_assumptions: Optional presentation-only safety formulas.
                They are accepted only when unconditionally equivalent.
            candidate_guarantees: Optional presentation-only safety formulas.
                They are accepted only when equivalent under shifted assumptions.

                These are formatting settings only. In contrast, the
                ``simplify`` parameter on construction, composition, and
                quotient controls the formulas stored in the returned
                contract. ``print(contract)`` continues to use the compatible
                ASCII :meth:`pretty` view; call this method explicitly for
                Unicode output.

        Returns:
            Unicode user-facing contract text.
        """
        inputs = ", ".join(variable.name for variable in self.inputvars) or "none"
        outputs = ", ".join(variable.name for variable in self.outputvars) or "none"
        assumption_view, guarantee_view = self.presentation_view(
            candidate_assumptions=candidate_assumptions,
            candidate_guarantees=candidate_guarantees,
            assumption_relative=assumption_relative,
        )
        assumption_text = assumption_view.to_pretty_string(compact=compact)
        guarantee_text = guarantee_view.to_pretty_string(compact=compact)
        if compact:
            return "\n".join(
                [
                    f"Inputs:  {inputs}",
                    f"Outputs: {outputs}",
                    "",
                    f"A = {assumption_text}",
                    f"G = {guarantee_text}",
                ]
            )
        assumption_lines = assumption_text.splitlines()
        guarantee_lines = guarantee_text.splitlines()
        return "\n".join(
            [
                f"Inputs:  {inputs}",
                f"Outputs: {outputs}",
                "",
                "Assumptions",
                *[f"  {line}" for line in assumption_lines],
                "",
                "Guarantees",
                *[f"  {line}" for line in guarantee_lines],
            ]
        )

    def debug_dump(self) -> str:
        """Return bucketed raw solver/QE expressions for diagnostics.

        Returns:
            Diagnostic contract text.
        """
        lines = [
            f"inputs:  [{', '.join(variable.name for variable in self.inputvars)}]",
            f"outputs: [{', '.join(variable.name for variable in self.outputvars)}]",
        ]
        for label, term_list in (("ASSUMPTIONS", self.a), ("GUARANTEES", self.g)):
            lines.extend(_debug_side_lines(label, term_list))
        return "\n".join(lines)

    def __str__(self) -> str:
        """Return the normal bucket-oriented user-facing representation.

        Returns:
            User-facing contract text.
        """
        return self.pretty()

    @staticmethod
    def from_buckets(
        *,
        input_vars: List[str],
        output_vars: List[str],
        a_init: Optional[List[GR1CoreFormula]] = None,
        a_inv: Optional[List[GR1CoreFormula]] = None,
        a_liv: Optional[List[GR1CoreFormula]] = None,
        g_init: Optional[List[GR1CoreFormula]] = None,
        g_inv: Optional[List[GR1CoreFormula]] = None,
        g_liv: Optional[List[GR1CoreFormula]] = None,
        simplify: bool = True,
    ) -> "GR1IoContract":
        """Construct a contract from pre-built cores grouped by GR(1) bucket.

        Args:
            input_vars: Input vars.
            output_vars: Output vars.
            a_init: A init.
            a_inv: A inv.
            a_liv: A liv.
            g_init: G init.
            g_inv: G inv.
            g_liv: G liv.
            simplify: Whether to simplify the resulting formulas.

        Returns:
            The computed 'GR1IoContract' result.
        """
        assumptions = GR1TermList.from_bucket_formulas(
            init=a_init,
            inv=a_inv,
            liv=a_liv,
        )
        guarantees = GR1TermList.from_bucket_formulas(
            init=g_init,
            inv=g_inv,
            liv=g_liv,
        )

        return GR1IoContract(
            assumptions=assumptions,
            guarantees=guarantees,
            input_vars=[Var(x) for x in input_vars],
            output_vars=[Var(x) for x in output_vars],
            simplify=simplify,
        )

    @staticmethod
    def from_dict(
        contract: Dict[str, Any],
        var_map: Optional[FormulaVarMap] = None,
        simplify: bool = True,
        variable_sorts: Optional[VariableSortMap] = None,
    ) -> "GR1IoContract":
        """Restore typed user text, falling back to versioned machine formulas.

                ``variable_sorts`` may be passed explicitly or embedded in ``contract``.
                Legacy ``var_map`` input creates text-only cores and cannot support QE.

        Args:
            contract: Contract.
            var_map: Mapping from formula text to variable names.
            simplify: Whether to simplify the resulting formulas.
            variable_sorts: Declared sort for each base variable.

        Returns:
            The computed 'GR1IoContract' result.

        Raises:
            ValueError: If serialized data or variable sorts are invalid.
        """
        assumptions_text, guarantees_text = _contract_bucket_dicts(contract)
        variable_sorts = _serialized_variable_sorts(contract, var_map, variable_sorts)
        machine = _serialized_machine(contract)
        assumptions_machine = None
        guarantees_machine = None
        if machine is not None:
            assumptions_machine = cast(Optional[Dict[str, Any]], machine.get("assumptions"))
            guarantees_machine = cast(Optional[Dict[str, Any]], machine.get("guarantees"))

        assumptions = _load_serialized_buckets(assumptions_text, assumptions_machine, var_map, variable_sorts)
        guarantees = _load_serialized_buckets(guarantees_text, guarantees_machine, var_map, variable_sorts)

        restored = GR1IoContract(
            assumptions=assumptions,
            guarantees=guarantees,
            input_vars=[Var(x) for x in cast(List[str], contract["input_vars"])],
            output_vars=[Var(x) for x in cast(List[str], contract["output_vars"])],
            simplify=simplify,
            variable_sorts=variable_sorts,
        )
        operation_payload = contract.get("gr1_operation_buckets")
        if operation_payload is not None:
            if not isinstance(operation_payload, dict) or operation_payload.get("version") != 1:
                raise ValueError("Unsupported or invalid GR(1) operation-bucket serialization version")
            operation_assumptions = _serialized_operation_side(
                operation_payload, "assumptions", var_map, variable_sorts
            )
            operation_guarantees = _serialized_operation_side(operation_payload, "guarantees", var_map, variable_sorts)
            restored._set_operation_buckets(operation_assumptions, operation_guarantees)
        else:
            restored._set_operation_buckets(restored.a, restored.g)
        return restored

    def rename_variables(self, variable_mappings: List[Tuple[str, str]]) -> "GR1IoContract":
        """Apply a sequence of base-variable renamings to a copied contract.

        Args:
            variable_mappings: Variable mappings.

        Returns:
            The computed 'GR1IoContract' result.
        """
        new_contract: GR1IoContract = self.copy()
        for src, dst in variable_mappings:
            new_contract = new_contract.rename_variable(Var(src), Var(dst))
        return new_contract

    def rename_variable(self, source_var: Var, target_var: Var) -> "GR1IoContract":
        """Rename one base interface variable and all of its flattened copies.

        Args:
            source_var: Source var.
            target_var: Target var.

        Returns:
            The computed 'GR1IoContract' result.

        Raises:
            ValueError: If serialized data or variable sorts are invalid.
        """
        renamed = super().rename_variable(source_var, target_var)
        renamed._set_operation_buckets(
            self._operation_assumptions.rename_variable(source_var, target_var),
            self._operation_guarantees.rename_variable(source_var, target_var),
        )
        renamed.variable_sorts = dict(self.variable_sorts)
        if source_var.name in renamed.variable_sorts:
            source_sort = renamed.variable_sorts.pop(source_var.name)
            existing_sort = renamed.variable_sorts.get(target_var.name)
            if existing_sort is not None and existing_sort != source_sort:
                raise ValueError(
                    f"Cannot rename {source_var.name!r} to {target_var.name!r}: "
                    f"sorts {source_sort} and {existing_sort} conflict"
                )
            renamed.variable_sorts[target_var.name] = source_sort
        return renamed

    def to_dict(self) -> Dict[str, Any]:
        """Serialize readable buckets, sorts, and versioned generated expressions.

        Returns:
            The computed Dict[str, Any] result.
        """
        contract: Dict[str, Any] = {
            "input_vars": [str(x) for x in self.inputvars],
            "output_vars": [str(x) for x in self.outputvars],
            "assumptions": self.a.to_bucket_dict(),
            "guarantees": self.g.to_bucket_dict(),
        }
        if self.variable_sorts:
            contract["variable_sorts"] = dict(sorted(self.variable_sorts.items()))
        contract["gr1_machine"] = {
            "version": 1,
            "assumptions": _machine_bucket_payload(self.a),
            "guarantees": _machine_bucket_payload(self.g),
        }
        contract["gr1_operation_buckets"] = {
            "version": 1,
            "assumptions": {
                "text": self._operation_assumptions.to_bucket_dict(),
                "machine": _machine_bucket_payload(self._operation_assumptions),
            },
            "guarantees": {
                "text": self._operation_guarantees.to_bucket_dict(),
                "machine": _machine_bucket_payload(self._operation_guarantees),
            },
        }
        return contract

    def to_machine_dict(self) -> ser_gr1_contract:
        """Return :meth:`to_dict` with the public serialized-contract type.

        Returns:
            The computed ser_gr1_contract result.
        """
        return cast(ser_gr1_contract, self.to_dict())

    def compose(
        self,
        other: "GR1IoContract",
        vars_to_keep: Optional[List[str]] = None,
        simplify: bool = True,
    ) -> "GR1IoContract":
        """Compose contracts, optionally preserving named internal variables.

        Args:
            other: Other term list or contract.
            vars_to_keep: Vars to keep.
            simplify: Whether to simplify the resulting formulas.

        Returns:
            The computed 'GR1IoContract' result.
        """
        if vars_to_keep is None:
            vars_to_keep = []
        result, _ = self.compose_tactics(other, vars_to_keep, simplify)
        return result

    def compose_tactics(
        self,
        other: "GR1IoContract",
        vars_to_keep: Optional[List[str]] = None,
        simplify: bool = True,
        tactics_order: Optional[List[int]] = None,
    ) -> Tuple["GR1IoContract", List[TacticStatistics]]:
        """Compose while exposing elimination tactic statistics.

        Args:
            other: Other term list or contract.
            vars_to_keep: Vars to keep.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Any result.
        """
        if vars_to_keep is None:
            vars_to_keep = []
        if tactics_order is None:
            tactics_order = []
        merged_sorts = _merge_variable_sort_maps(self.variable_sorts, other.variable_sorts)
        with _OperationSimplifyContext(False):
            raw, stats = IoContract.compose_tactics(
                self._operation_copy(),
                other._operation_copy(),
                [Var(x) for x in vars_to_keep],
                simplify=False,
                tactics_order=tactics_order,
            )
            raw.variable_sorts = _normalized_variable_sorts(
                {var.name: merged_sorts[var.name] for var in raw.vars if var.name in merged_sorts},
                _infer_variable_sorts(raw.a, raw.g),
            )
            return self._finalize_operation_result(raw, simplify), stats

    def quotient(
        self,
        other: "GR1IoContract",
        additional_inputs: Optional[VariableInputs] = None,
        simplify: bool = True,
    ) -> "GR1IoContract":
        """Compute a quotient with optional additional input names.

        Args:
            other: Other term list or contract.
            additional_inputs: Additional inputs.
            simplify: Whether to simplify the resulting formulas.

        Returns:
            The computed 'GR1IoContract' result.
        """
        if additional_inputs is None:
            additional_inputs = []

        result, _ = self.quotient_tactics(other, additional_inputs, simplify)
        return result

    def quotient_tactics(
        self,
        other: "GR1IoContract",
        additional_inputs: Optional[VariableInputs] = None,
        simplify: bool = True,
        tactics_order: Optional[List[int]] = None,
    ) -> Tuple["GR1IoContract", List[TacticStatistics]]:
        """Compute a quotient while exposing tactic statistics.

        Args:
            other: Other term list or contract.
            additional_inputs: Additional inputs.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Tuple['GR1IoContract', List[TacticStatistics]] result.
        """
        if additional_inputs is None:
            additional_inputs = []

        if tactics_order is None:
            tactics_order = []

        merged_sorts = _merge_variable_sort_maps(self.variable_sorts, other.variable_sorts)
        with _OperationSimplifyContext(False):
            raw, stats = IoContract.quotient_tactics(
                self._operation_copy(),
                other._operation_copy(),
                [item if isinstance(item, Var) else Var(item) for item in additional_inputs],
                simplify=False,
                tactics_order=tactics_order,
            )
            raw.variable_sorts = _normalized_variable_sorts(
                {var.name: merged_sorts[var.name] for var in raw.vars if var.name in merged_sorts},
                _infer_variable_sorts(raw.a, raw.g),
            )
            return self._finalize_operation_result(raw, simplify), stats

    def _set_operation_buckets(self, assumptions: GR1TermList, guarantees: GR1TermList) -> None:
        """Store independent canonical buckets used by future GR(1) operations.

        Args:
            assumptions: Canonical assumption buckets.
            guarantees: Canonical guarantee buckets.
        """
        self._operation_assumptions = assumptions.copy()
        self._operation_guarantees = guarantees.copy()

    def _operation_copy(self) -> "GR1IoContract":
        """Build a contract exposing canonical buckets to generic algebra.

        Returns:
            Contract containing canonical operation buckets.
        """
        return GR1IoContract(
            assumptions=self._operation_assumptions,
            guarantees=self._operation_guarantees,
            input_vars=self.inputvars,
            output_vars=self.outputvars,
            simplify=False,
            variable_sorts=self.variable_sorts,
        )

    @staticmethod
    def _finalize_operation_result(raw: "GR1IoContract", simplify: bool) -> "GR1IoContract":
        """Attach raw CAVE buckets and optionally construct their reduced view.

        Args:
            raw: Raw operation result.
            simplify: Whether to construct the reduced view.

        Returns:
            Finalized operation result.
        """
        if not simplify:
            return raw
        reduced_assumptions = raw.a.simplify()
        reduced_guarantees = raw.g.simplify(reduced_assumptions)
        reduced_guarantees = GR1TermList(
            reduced_guarantees.init_terms()
            + reduced_guarantees.inv_terms()
            + sorted(reduced_guarantees.liv_terms(), key=lambda term: term.core.text)
        )
        reduced = GR1IoContract(
            assumptions=reduced_assumptions,
            guarantees=reduced_guarantees,
            input_vars=raw.inputvars,
            output_vars=raw.outputvars,
            simplify=False,
            variable_sorts=raw.variable_sorts,
        )
        reduced._set_operation_buckets(raw.a, raw.g)
        return reduced

__copy__()

Return an independent copy including canonical operation buckets.

Returns:

Type Description
'GR1IoContract'

Independent contract copy.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __copy__(self) -> "GR1IoContract":
    """Return an independent copy including canonical operation buckets.

    Returns:
        Independent contract copy.
    """
    return self.copy()

__deepcopy__(memo)

Return an independent deep copy including canonical operation buckets.

Parameters:

Name Type Description Default
memo Dict[int, Any]

Deep-copy memoization dictionary.

required

Returns:

Type Description
'GR1IoContract'

Independent contract copy.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __deepcopy__(self, memo: Dict[int, Any]) -> "GR1IoContract":
    """Return an independent deep copy including canonical operation buckets.

    Args:
        memo: Deep-copy memoization dictionary.

    Returns:
        Independent contract copy.
    """
    del memo
    return self.copy()

__init__(assumptions, guarantees, input_vars, output_vars, simplify=None, variable_sorts=None)

Build a contract and validate or infer its persistent sort table.

Parameters:

Name Type Description Default
assumptions GR1TermList

Assumptions.

required
guarantees GR1TermList

Guarantees.

required
input_vars List[Var]

Input vars.

required
output_vars List[Var]

Output vars.

required
simplify Optional[bool]

Whether to simplify the supplied formulas. Internal operation construction inherits the operation's explicit raw versus final setting.

None
variable_sorts Optional[Dict[str, Any]]

Declared sort for each base variable.

None
Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __init__(
    self,
    assumptions: GR1TermList,
    guarantees: GR1TermList,
    input_vars: List[Var],
    output_vars: List[Var],
    simplify: Optional[bool] = None,
    variable_sorts: Optional[Dict[str, Any]] = None,
) -> None:
    """Build a contract and validate or infer its persistent sort table.

    Args:
        assumptions: Assumptions.
        guarantees: Guarantees.
        input_vars: Input vars.
        output_vars: Output vars.
        simplify: Whether to simplify the supplied formulas. Internal
            operation construction inherits the operation's explicit raw
            versus final setting.
        variable_sorts: Declared sort for each base variable.
    """
    effective_simplify = _GR1_OPERATION_SIMPLIFY.get() if simplify is None else simplify
    operation_assumptions = assumptions.copy()
    operation_guarantees = guarantees.copy()
    super().__init__(assumptions, guarantees, input_vars, output_vars, effective_simplify)
    self._operation_assumptions = operation_assumptions
    self._operation_guarantees = operation_guarantees

    inferred = _infer_variable_sorts(self.a, self.g)
    self.variable_sorts = _normalized_variable_sorts(variable_sorts, inferred)

__str__()

Return the normal bucket-oriented user-facing representation.

Returns:

Type Description
str

User-facing contract text.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __str__(self) -> str:
    """Return the normal bucket-oriented user-facing representation.

    Returns:
        User-facing contract text.
    """
    return self.pretty()

canonical_debug_dump()

Return canonical operation buckets without changing stored buckets.

Returns:

Type Description
str

Canonical debug representation.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def canonical_debug_dump(self) -> str:
    """Return canonical operation buckets without changing stored buckets.

    Returns:
        Canonical debug representation.
    """
    canonical = self._operation_copy()
    return canonical.debug_dump()

compose(other, vars_to_keep=None, simplify=True)

Compose contracts, optionally preserving named internal variables.

Parameters:

Name Type Description Default
other 'GR1IoContract'

Other term list or contract.

required
vars_to_keep Optional[List[str]]

Vars to keep.

None
simplify bool

Whether to simplify the resulting formulas.

True

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def compose(
    self,
    other: "GR1IoContract",
    vars_to_keep: Optional[List[str]] = None,
    simplify: bool = True,
) -> "GR1IoContract":
    """Compose contracts, optionally preserving named internal variables.

    Args:
        other: Other term list or contract.
        vars_to_keep: Vars to keep.
        simplify: Whether to simplify the resulting formulas.

    Returns:
        The computed 'GR1IoContract' result.
    """
    if vars_to_keep is None:
        vars_to_keep = []
    result, _ = self.compose_tactics(other, vars_to_keep, simplify)
    return result

compose_tactics(other, vars_to_keep=None, simplify=True, tactics_order=None)

Compose while exposing elimination tactic statistics.

Parameters:

Name Type Description Default
other 'GR1IoContract'

Other term list or contract.

required
vars_to_keep Optional[List[str]]

Vars to keep.

None
simplify bool

Whether to simplify the resulting formulas.

True
tactics_order Optional[List[int]]

Preferred quantifier-elimination tactic order.

None

Returns:

Type Description
Tuple['GR1IoContract', List[TacticStatistics]]

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def compose_tactics(
    self,
    other: "GR1IoContract",
    vars_to_keep: Optional[List[str]] = None,
    simplify: bool = True,
    tactics_order: Optional[List[int]] = None,
) -> Tuple["GR1IoContract", List[TacticStatistics]]:
    """Compose while exposing elimination tactic statistics.

    Args:
        other: Other term list or contract.
        vars_to_keep: Vars to keep.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Any result.
    """
    if vars_to_keep is None:
        vars_to_keep = []
    if tactics_order is None:
        tactics_order = []
    merged_sorts = _merge_variable_sort_maps(self.variable_sorts, other.variable_sorts)
    with _OperationSimplifyContext(False):
        raw, stats = IoContract.compose_tactics(
            self._operation_copy(),
            other._operation_copy(),
            [Var(x) for x in vars_to_keep],
            simplify=False,
            tactics_order=tactics_order,
        )
        raw.variable_sorts = _normalized_variable_sorts(
            {var.name: merged_sorts[var.name] for var in raw.vars if var.name in merged_sorts},
            _infer_variable_sorts(raw.a, raw.g),
        )
        return self._finalize_operation_result(raw, simplify), stats

copy()

Copy the contract while preserving declarations for unused variables.

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def copy(self) -> "GR1IoContract":
    """Copy the contract while preserving declarations for unused variables.

    Returns:
        The computed 'GR1IoContract' result.
    """
    copied = GR1IoContract(
        assumptions=self.a.copy(),
        guarantees=self.g.copy(),
        input_vars=self.inputvars.copy(),
        output_vars=self.outputvars.copy(),
        simplify=False,
        variable_sorts=self.variable_sorts,
    )
    copied._set_operation_buckets(self._operation_assumptions, self._operation_guarantees)
    return copied

debug_dump()

Return bucketed raw solver/QE expressions for diagnostics.

Returns:

Type Description
str

Diagnostic contract text.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def debug_dump(self) -> str:
    """Return bucketed raw solver/QE expressions for diagnostics.

    Returns:
        Diagnostic contract text.
    """
    lines = [
        f"inputs:  [{', '.join(variable.name for variable in self.inputvars)}]",
        f"outputs: [{', '.join(variable.name for variable in self.outputvars)}]",
    ]
    for label, term_list in (("ASSUMPTIONS", self.a), ("GUARANTEES", self.g)):
        lines.extend(_debug_side_lines(label, term_list))
    return "\n".join(lines)

from_buckets(*, input_vars, output_vars, a_init=None, a_inv=None, a_liv=None, g_init=None, g_inv=None, g_liv=None, simplify=True) staticmethod

Construct a contract from pre-built cores grouped by GR(1) bucket.

Parameters:

Name Type Description Default
input_vars List[str]

Input vars.

required
output_vars List[str]

Output vars.

required
a_init Optional[List[GR1CoreFormula]]

A init.

None
a_inv Optional[List[GR1CoreFormula]]

A inv.

None
a_liv Optional[List[GR1CoreFormula]]

A liv.

None
g_init Optional[List[GR1CoreFormula]]

G init.

None
g_inv Optional[List[GR1CoreFormula]]

G inv.

None
g_liv Optional[List[GR1CoreFormula]]

G liv.

None
simplify bool

Whether to simplify the resulting formulas.

True

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def from_buckets(
    *,
    input_vars: List[str],
    output_vars: List[str],
    a_init: Optional[List[GR1CoreFormula]] = None,
    a_inv: Optional[List[GR1CoreFormula]] = None,
    a_liv: Optional[List[GR1CoreFormula]] = None,
    g_init: Optional[List[GR1CoreFormula]] = None,
    g_inv: Optional[List[GR1CoreFormula]] = None,
    g_liv: Optional[List[GR1CoreFormula]] = None,
    simplify: bool = True,
) -> "GR1IoContract":
    """Construct a contract from pre-built cores grouped by GR(1) bucket.

    Args:
        input_vars: Input vars.
        output_vars: Output vars.
        a_init: A init.
        a_inv: A inv.
        a_liv: A liv.
        g_init: G init.
        g_inv: G inv.
        g_liv: G liv.
        simplify: Whether to simplify the resulting formulas.

    Returns:
        The computed 'GR1IoContract' result.
    """
    assumptions = GR1TermList.from_bucket_formulas(
        init=a_init,
        inv=a_inv,
        liv=a_liv,
    )
    guarantees = GR1TermList.from_bucket_formulas(
        init=g_init,
        inv=g_inv,
        liv=g_liv,
    )

    return GR1IoContract(
        assumptions=assumptions,
        guarantees=guarantees,
        input_vars=[Var(x) for x in input_vars],
        output_vars=[Var(x) for x in output_vars],
        simplify=simplify,
    )

from_dict(contract, var_map=None, simplify=True, variable_sorts=None) staticmethod

Restore typed user text, falling back to versioned machine formulas.

    ``variable_sorts`` may be passed explicitly or embedded in ``contract``.
    Legacy ``var_map`` input creates text-only cores and cannot support QE.

Parameters:

Name Type Description Default
contract Dict[str, Any]

Contract.

required
var_map Optional[FormulaVarMap]

Mapping from formula text to variable names.

None
simplify bool

Whether to simplify the resulting formulas.

True
variable_sorts Optional[VariableSortMap]

Declared sort for each base variable.

None

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Raises:

Type Description
ValueError

If serialized data or variable sorts are invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def from_dict(
    contract: Dict[str, Any],
    var_map: Optional[FormulaVarMap] = None,
    simplify: bool = True,
    variable_sorts: Optional[VariableSortMap] = None,
) -> "GR1IoContract":
    """Restore typed user text, falling back to versioned machine formulas.

            ``variable_sorts`` may be passed explicitly or embedded in ``contract``.
            Legacy ``var_map`` input creates text-only cores and cannot support QE.

    Args:
        contract: Contract.
        var_map: Mapping from formula text to variable names.
        simplify: Whether to simplify the resulting formulas.
        variable_sorts: Declared sort for each base variable.

    Returns:
        The computed 'GR1IoContract' result.

    Raises:
        ValueError: If serialized data or variable sorts are invalid.
    """
    assumptions_text, guarantees_text = _contract_bucket_dicts(contract)
    variable_sorts = _serialized_variable_sorts(contract, var_map, variable_sorts)
    machine = _serialized_machine(contract)
    assumptions_machine = None
    guarantees_machine = None
    if machine is not None:
        assumptions_machine = cast(Optional[Dict[str, Any]], machine.get("assumptions"))
        guarantees_machine = cast(Optional[Dict[str, Any]], machine.get("guarantees"))

    assumptions = _load_serialized_buckets(assumptions_text, assumptions_machine, var_map, variable_sorts)
    guarantees = _load_serialized_buckets(guarantees_text, guarantees_machine, var_map, variable_sorts)

    restored = GR1IoContract(
        assumptions=assumptions,
        guarantees=guarantees,
        input_vars=[Var(x) for x in cast(List[str], contract["input_vars"])],
        output_vars=[Var(x) for x in cast(List[str], contract["output_vars"])],
        simplify=simplify,
        variable_sorts=variable_sorts,
    )
    operation_payload = contract.get("gr1_operation_buckets")
    if operation_payload is not None:
        if not isinstance(operation_payload, dict) or operation_payload.get("version") != 1:
            raise ValueError("Unsupported or invalid GR(1) operation-bucket serialization version")
        operation_assumptions = _serialized_operation_side(
            operation_payload, "assumptions", var_map, variable_sorts
        )
        operation_guarantees = _serialized_operation_side(operation_payload, "guarantees", var_map, variable_sorts)
        restored._set_operation_buckets(operation_assumptions, operation_guarantees)
    else:
        restored._set_operation_buckets(restored.a, restored.g)
    return restored

merge(other)

Merge two contracts while preserving every GR(1) bucket.

GR(1) is closed under contract merge: assumptions and guarantees are conjoined bucket by bucket. INIT and INV terms are concatenated as ordinary conjunctions. LIV terms are also concatenated as distinct clauses, so GF(phi) & GF(psi) never becomes GF(phi & psi). No abstraction, projection, quantifier elimination, or CAVE machinery is invoked.

Interface variables follow :meth:IoContract.merge: inputs and outputs are stable unions, and the constructor rejects variables classified as both input and output.

Parameters:

Name Type Description Default
other 'GR1IoContract'

GR(1) contract to merge with this contract.

required

Returns:

Type Description
'GR1IoContract'

Exact bucket-preserving conjunction of both contracts.

Raises:

Type Description
IncompatibleArgsError

If contract types, interfaces, or sorts are incompatible.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def merge(self, other: "GR1IoContract") -> "GR1IoContract":
    """Merge two contracts while preserving every GR(1) bucket.

    GR(1) is closed under contract merge: assumptions and guarantees are
    conjoined bucket by bucket. INIT and INV terms are concatenated as
    ordinary conjunctions. LIV terms are also concatenated as distinct
    clauses, so ``GF(phi) & GF(psi)`` never becomes ``GF(phi & psi)``.
    No abstraction, projection, quantifier elimination, or CAVE machinery
    is invoked.

    Interface variables follow :meth:`IoContract.merge`: inputs and outputs
    are stable unions, and the constructor rejects variables classified as
    both input and output.

    Args:
        other: GR(1) contract to merge with this contract.

    Returns:
        Exact bucket-preserving conjunction of both contracts.

    Raises:
        IncompatibleArgsError: If contract types, interfaces, or sorts are incompatible.
    """
    if not isinstance(self, type(other)):
        raise IncompatibleArgsError("Asked to merge incompatible contracts")
    merged = GR1IoContract(
        assumptions=_merge_gr1_term_lists(self.a, other.a),
        guarantees=_merge_gr1_term_lists(self.g, other.g),
        input_vars=list_union(self.inputvars, other.inputvars),
        output_vars=list_union(self.outputvars, other.outputvars),
        simplify=False,
        variable_sorts=_merge_variable_sort_maps(self.variable_sorts, other.variable_sorts),
    )
    merged._set_operation_buckets(
        _merge_gr1_term_lists(self._operation_assumptions, other._operation_assumptions),
        _merge_gr1_term_lists(self._operation_guarantees, other._operation_guarantees),
    )
    return merged

presentation_view(candidate_assumptions=None, candidate_guarantees=None, assumption_relative=True)

Return detached, SMT-certified buckets intended only for rendering.

Automatic candidates use inexpensive Z3 tactics and Boolean-mode consequence mining. Optional caller candidates are hints, not trusted replacements: assumption safety buckets require unconditional equivalence, and guarantee safety buckets require equivalence under the appropriate shifted contract assumptions. LIV hints are deliberately ignored so distinct justice obligations cannot be synchronized.

Parameters:

Name Type Description Default
candidate_assumptions Optional[GR1TermList]

Optional proposed assumption presentation.

None
candidate_guarantees Optional[GR1TermList]

Optional proposed guarantee presentation.

None
assumption_relative bool

Whether guarantees are reduced under assumptions.

True

Returns:

Type Description
Tuple[GR1TermList, GR1TermList]

Detached assumption and guarantee presentation lists.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def presentation_view(
    self,
    candidate_assumptions: Optional[GR1TermList] = None,
    candidate_guarantees: Optional[GR1TermList] = None,
    assumption_relative: bool = True,
) -> Tuple[GR1TermList, GR1TermList]:
    """Return detached, SMT-certified buckets intended only for rendering.

    Automatic candidates use inexpensive Z3 tactics and Boolean-mode
    consequence mining. Optional caller candidates are hints, not trusted
    replacements: assumption safety buckets require unconditional
    equivalence, and guarantee safety buckets require equivalence under the
    appropriate shifted contract assumptions. LIV hints are deliberately
    ignored so distinct justice obligations cannot be synchronized.

    Args:
        candidate_assumptions: Optional proposed assumption presentation.
        candidate_guarantees: Optional proposed guarantee presentation.
        assumption_relative: Whether guarantees are reduced under assumptions.

    Returns:
        Detached assumption and guarantee presentation lists.
    """
    true_context = z3.BoolVal(True)
    assumptions = _presentation_safety_view(self.a.copy(), true_context, true_context)
    guarantees = _assumption_relative_guarantee_view(self) if assumption_relative else self.g.copy()
    guarantee_init_context = _assumption_context_for_guarantee_bucket(
        self.a, guarantees.init_terms(), include_init=True
    )
    guarantee_inv_context = _assumption_context_for_guarantee_bucket(
        self.a, guarantees.inv_terms(), include_init=False
    )
    guarantees = _presentation_safety_view(guarantees, guarantee_init_context, guarantee_inv_context)

    assumptions = _replace_presentation_safety_buckets(
        self.a, assumptions, candidate_assumptions, guarantee_side=False
    )
    guarantees = _replace_presentation_safety_buckets(self.a, guarantees, candidate_guarantees, guarantee_side=True)
    return assumptions, guarantees

pretty(annotate_redundancy=True)

Return a sectioned bucket view using explicit G and GF.

Canonical expressions are split into readable conjunction lines. INIT guarantee atoms already implied by assumptions are omitted from this view only. Stored semantics and serialization remain unchanged. A LIV guarantee established by assumption INV/LIV support is retained but may be annotated as redundant.

Parameters:

Name Type Description Default
annotate_redundancy bool

Mark assumption-established liveness terms.

True

Returns:

Type Description
str

Human-readable contract text.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def pretty(self, annotate_redundancy: bool = True) -> str:
    """Return a sectioned bucket view using explicit ``G`` and ``GF``.

    Canonical expressions are split into readable conjunction lines. INIT
    guarantee atoms already implied by assumptions are omitted from this
    view only. Stored semantics and serialization remain unchanged. A LIV
    guarantee established by assumption INV/LIV support is retained but may
    be annotated as redundant.

    Args:
        annotate_redundancy: Mark assumption-established liveness terms.

    Returns:
        Human-readable contract text.
    """
    lines = [
        f"inputs:  [{', '.join(variable.name for variable in self.inputvars)}]",
        f"outputs: [{', '.join(variable.name for variable in self.outputvars)}]",
    ]
    lines.extend(
        _pretty_side_lines(
            self,
            "ASSUMPTIONS",
            self.a,
            guarantees=False,
            annotate_redundancy=annotate_redundancy,
        )
    )
    lines.extend(
        _pretty_side_lines(
            self,
            "GUARANTEES",
            self.g,
            guarantees=True,
            annotate_redundancy=annotate_redundancy,
        )
    )
    return "\n".join(lines)

quotient(other, additional_inputs=None, simplify=True)

Compute a quotient with optional additional input names.

Parameters:

Name Type Description Default
other 'GR1IoContract'

Other term list or contract.

required
additional_inputs Optional[VariableInputs]

Additional inputs.

None
simplify bool

Whether to simplify the resulting formulas.

True

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def quotient(
    self,
    other: "GR1IoContract",
    additional_inputs: Optional[VariableInputs] = None,
    simplify: bool = True,
) -> "GR1IoContract":
    """Compute a quotient with optional additional input names.

    Args:
        other: Other term list or contract.
        additional_inputs: Additional inputs.
        simplify: Whether to simplify the resulting formulas.

    Returns:
        The computed 'GR1IoContract' result.
    """
    if additional_inputs is None:
        additional_inputs = []

    result, _ = self.quotient_tactics(other, additional_inputs, simplify)
    return result

quotient_tactics(other, additional_inputs=None, simplify=True, tactics_order=None)

Compute a quotient while exposing tactic statistics.

Parameters:

Name Type Description Default
other 'GR1IoContract'

Other term list or contract.

required
additional_inputs Optional[VariableInputs]

Additional inputs.

None
simplify bool

Whether to simplify the resulting formulas.

True
tactics_order Optional[List[int]]

Preferred quantifier-elimination tactic order.

None

Returns:

Type Description
Tuple['GR1IoContract', List[TacticStatistics]]

The computed Tuple['GR1IoContract', List[TacticStatistics]] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def quotient_tactics(
    self,
    other: "GR1IoContract",
    additional_inputs: Optional[VariableInputs] = None,
    simplify: bool = True,
    tactics_order: Optional[List[int]] = None,
) -> Tuple["GR1IoContract", List[TacticStatistics]]:
    """Compute a quotient while exposing tactic statistics.

    Args:
        other: Other term list or contract.
        additional_inputs: Additional inputs.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Tuple['GR1IoContract', List[TacticStatistics]] result.
    """
    if additional_inputs is None:
        additional_inputs = []

    if tactics_order is None:
        tactics_order = []

    merged_sorts = _merge_variable_sort_maps(self.variable_sorts, other.variable_sorts)
    with _OperationSimplifyContext(False):
        raw, stats = IoContract.quotient_tactics(
            self._operation_copy(),
            other._operation_copy(),
            [item if isinstance(item, Var) else Var(item) for item in additional_inputs],
            simplify=False,
            tactics_order=tactics_order,
        )
        raw.variable_sorts = _normalized_variable_sorts(
            {var.name: merged_sorts[var.name] for var in raw.vars if var.name in merged_sorts},
            _infer_variable_sorts(raw.a, raw.g),
        )
        return self._finalize_operation_result(raw, simplify), stats

rename_variable(source_var, target_var)

Rename one base interface variable and all of its flattened copies.

Parameters:

Name Type Description Default
source_var Var

Source var.

required
target_var Var

Target var.

required

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Raises:

Type Description
ValueError

If serialized data or variable sorts are invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def rename_variable(self, source_var: Var, target_var: Var) -> "GR1IoContract":
    """Rename one base interface variable and all of its flattened copies.

    Args:
        source_var: Source var.
        target_var: Target var.

    Returns:
        The computed 'GR1IoContract' result.

    Raises:
        ValueError: If serialized data or variable sorts are invalid.
    """
    renamed = super().rename_variable(source_var, target_var)
    renamed._set_operation_buckets(
        self._operation_assumptions.rename_variable(source_var, target_var),
        self._operation_guarantees.rename_variable(source_var, target_var),
    )
    renamed.variable_sorts = dict(self.variable_sorts)
    if source_var.name in renamed.variable_sorts:
        source_sort = renamed.variable_sorts.pop(source_var.name)
        existing_sort = renamed.variable_sorts.get(target_var.name)
        if existing_sort is not None and existing_sort != source_sort:
            raise ValueError(
                f"Cannot rename {source_var.name!r} to {target_var.name!r}: "
                f"sorts {source_sort} and {existing_sort} conflict"
            )
        renamed.variable_sorts[target_var.name] = source_sort
    return renamed

rename_variables(variable_mappings)

Apply a sequence of base-variable renamings to a copied contract.

Parameters:

Name Type Description Default
variable_mappings List[Tuple[str, str]]

Variable mappings.

required

Returns:

Type Description
'GR1IoContract'

The computed 'GR1IoContract' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def rename_variables(self, variable_mappings: List[Tuple[str, str]]) -> "GR1IoContract":
    """Apply a sequence of base-variable renamings to a copied contract.

    Args:
        variable_mappings: Variable mappings.

    Returns:
        The computed 'GR1IoContract' result.
    """
    new_contract: GR1IoContract = self.copy()
    for src, dst in variable_mappings:
        new_contract = new_contract.rename_variable(Var(src), Var(dst))
    return new_contract

to_dict()

Serialize readable buckets, sorts, and versioned generated expressions.

Returns:

Type Description
Dict[str, Any]

The computed Dict[str, Any] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_dict(self) -> Dict[str, Any]:
    """Serialize readable buckets, sorts, and versioned generated expressions.

    Returns:
        The computed Dict[str, Any] result.
    """
    contract: Dict[str, Any] = {
        "input_vars": [str(x) for x in self.inputvars],
        "output_vars": [str(x) for x in self.outputvars],
        "assumptions": self.a.to_bucket_dict(),
        "guarantees": self.g.to_bucket_dict(),
    }
    if self.variable_sorts:
        contract["variable_sorts"] = dict(sorted(self.variable_sorts.items()))
    contract["gr1_machine"] = {
        "version": 1,
        "assumptions": _machine_bucket_payload(self.a),
        "guarantees": _machine_bucket_payload(self.g),
    }
    contract["gr1_operation_buckets"] = {
        "version": 1,
        "assumptions": {
            "text": self._operation_assumptions.to_bucket_dict(),
            "machine": _machine_bucket_payload(self._operation_assumptions),
        },
        "guarantees": {
            "text": self._operation_guarantees.to_bucket_dict(),
            "machine": _machine_bucket_payload(self._operation_guarantees),
        },
    }
    return contract

to_machine_dict()

Return :meth:to_dict with the public serialized-contract type.

Returns:

Type Description
ser_gr1_contract

The computed ser_gr1_contract result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_machine_dict(self) -> ser_gr1_contract:
    """Return :meth:`to_dict` with the public serialized-contract type.

    Returns:
        The computed ser_gr1_contract result.
    """
    return cast(ser_gr1_contract, self.to_dict())

to_pretty_string(compact=False, assumption_relative=True, candidate_assumptions=None, candidate_guarantees=None)

Return an observational Unicode assume-guarantee contract view.

This is an additional presentation API. The existing ASCII :meth:pretty, :meth:debug_dump, serialization, and __str__ behavior remain unchanged.

Parameters:

Name Type Description Default
compact bool

Render A = ... and G = ... instead of bucket views.

False
assumption_relative bool

Reduce only the displayed guarantees under assumptions using SMT-verified GR(1) rules. Set to False to display every internally stored guarantee.

True
candidate_assumptions Optional[GR1TermList]

Optional presentation-only safety formulas. They are accepted only when unconditionally equivalent.

None
candidate_guarantees Optional[GR1TermList]

Optional presentation-only safety formulas. They are accepted only when equivalent under shifted assumptions.

These are formatting settings only. In contrast, the simplify parameter on construction, composition, and quotient controls the formulas stored in the returned contract. print(contract) continues to use the compatible ASCII :meth:pretty view; call this method explicitly for Unicode output.

None

Returns:

Type Description
str

Unicode user-facing contract text.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_pretty_string(
    self,
    compact: bool = False,
    assumption_relative: bool = True,
    candidate_assumptions: Optional[GR1TermList] = None,
    candidate_guarantees: Optional[GR1TermList] = None,
) -> str:
    """Return an observational Unicode assume-guarantee contract view.

    This is an additional presentation API. The existing ASCII
    :meth:`pretty`, :meth:`debug_dump`, serialization, and ``__str__``
    behavior remain unchanged.

    Args:
        compact: Render ``A = ...`` and ``G = ...`` instead of bucket views.
        assumption_relative: Reduce only the displayed guarantees under
            assumptions using SMT-verified GR(1) rules. Set to ``False``
            to display every internally stored guarantee.
        candidate_assumptions: Optional presentation-only safety formulas.
            They are accepted only when unconditionally equivalent.
        candidate_guarantees: Optional presentation-only safety formulas.
            They are accepted only when equivalent under shifted assumptions.

            These are formatting settings only. In contrast, the
            ``simplify`` parameter on construction, composition, and
            quotient controls the formulas stored in the returned
            contract. ``print(contract)`` continues to use the compatible
            ASCII :meth:`pretty` view; call this method explicitly for
            Unicode output.

    Returns:
        Unicode user-facing contract text.
    """
    inputs = ", ".join(variable.name for variable in self.inputvars) or "none"
    outputs = ", ".join(variable.name for variable in self.outputvars) or "none"
    assumption_view, guarantee_view = self.presentation_view(
        candidate_assumptions=candidate_assumptions,
        candidate_guarantees=candidate_guarantees,
        assumption_relative=assumption_relative,
    )
    assumption_text = assumption_view.to_pretty_string(compact=compact)
    guarantee_text = guarantee_view.to_pretty_string(compact=compact)
    if compact:
        return "\n".join(
            [
                f"Inputs:  {inputs}",
                f"Outputs: {outputs}",
                "",
                f"A = {assumption_text}",
                f"G = {guarantee_text}",
            ]
        )
    assumption_lines = assumption_text.splitlines()
    guarantee_lines = guarantee_text.splitlines()
    return "\n".join(
        [
            f"Inputs:  {inputs}",
            f"Outputs: {outputs}",
            "",
            "Assumptions",
            *[f"  {line}" for line in assumption_lines],
            "",
            "Guarantees",
            *[f"  {line}" for line in guarantee_lines],
        ]
    )

GR1NextFlattener

Helper for constructing GR(1) core formulas with a syntactic next operator X.

Standard flattened naming convention

p is internally treated as p_0 X(p) becomes p_1 X(X(p)) becomes p_2

Example

fl = GR1NextFlattener() P = fl.Bool("p") Q = fl.Bool("q")

expr = fl.X(z3.And(P, fl.X(Q))) core = fl.core("X(p & X(q))", expr)

The expression above is flattened as

And(p_1, q_2)

Notes
  • X only shifts uninterpreted constants appearing in the Z3 expression.
  • It preserves the Z3 sort of each variable.
  • The result is a normal GR1CoreFormula with explicit flattened Vars.
Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
class GR1NextFlattener:
    """
    Helper for constructing GR(1) core formulas with a syntactic next operator X.

    Standard flattened naming convention:
        p      is internally treated as p_0
        X(p)  becomes p_1
        X(X(p)) becomes p_2

    Example:
        fl = GR1NextFlattener()
        P = fl.Bool("p")
        Q = fl.Bool("q")

        expr = fl.X(z3.And(P, fl.X(Q)))
        core = fl.core("X(p & X(q))", expr)

    The expression above is flattened as:
        And(p_1, q_2)

    Notes:
        - X only shifts uninterpreted constants appearing in the Z3 expression.
        - It preserves the Z3 sort of each variable.
        - The result is a normal GR1CoreFormula with explicit flattened Vars.
    """

    def __init__(self, *, current_suffix: str = "_0", next_separator: str = "_"):
        """Create a flattener with configurable current and depth separators.

        Args:
            current_suffix: Suffix representing the current state.
            next_separator: Separator used before a next-state index.
        """
        self.current_suffix = current_suffix
        self.next_separator = next_separator

        # Maps flattened variable name -> Z3 variable.
        self._z3_vars: Dict[str, Any] = {}

        # Maps flattened variable name -> Pacti Var.
        self._vars: Dict[str, Var] = {}

        # Maps original base variable name -> sort.
        self._sorts: Dict[str, Any] = {}

    # ------------------------------------------------------------------
    # Variable constructors
    # ------------------------------------------------------------------

    def Bool(self, name: str) -> Any:  # noqa: N802
        """Create and return the current-time Boolean ``name_0``.

        Args:
            name: Variable name.

        Returns:
            The computed Any result.
        """
        return self._mk_base_var(name, z3.BoolSort())

    def Real(self, name: str) -> Any:  # noqa: N802
        """Create and return the current-time real ``name_0``.

        Args:
            name: Variable name.

        Returns:
            The computed Any result.
        """
        return self._mk_base_var(name, z3.RealSort())

    def Int(self, name: str) -> Any:  # noqa: N802
        """Create and return the current-time integer ``name_0``.

        Args:
            name: Variable name.

        Returns:
            The computed Any result.
        """
        return self._mk_base_var(name, z3.IntSort())

    # ------------------------------------------------------------------
    # Next operator
    # ------------------------------------------------------------------

    def X(self, expr: Any) -> Any:  # noqa: N802
        """Syntactic next operator.

        Shifts every flattened variable in expr forward by one time step.

        Examples:
            X(p_0) = p_1
            X(q_1) = q_2
            X(p_0 & q_1) = p_1 & q_2

        Args:
            expr: Z3 expression to process.

        Returns:
            The computed Any result.
        """
        substitutions = []

        # GETVARS-PATCH: original (disabled) ---
        # for v in get_vars(expr):
        # GETVARS-PATCH: replacement ---
        for v in _z3_get_vars(expr):
            # GETVARS-PATCH: end ---
            old_name = v.decl().name()
            base, depth = self._parse_flat_name(old_name)
            new_name = self._shifted_name(base, depth + 1)
            new_var = self._mk_flat_var(new_name, v.sort())
            substitutions.append((v, new_var))

        if not substitutions:
            return expr

        return z3.simplify(z3.substitute(expr, *substitutions))

    # ------------------------------------------------------------------
    # Core construction
    # ------------------------------------------------------------------

    def core(self, text: str, expr: Any) -> "GR1CoreFormula":
        """Build a GR1CoreFormula from a flattened Z3 expression.

        Args:
            text: Human-readable formula text.
            expr: Z3 expression to process.

        Returns:
            The computed 'GR1CoreFormula' result.
        """
        vars_ = []
        # GETVARS-PATCH: original (disabled) ---
        # for v in get_vars(expr):
        # GETVARS-PATCH: replacement ---
        for v in _z3_get_vars(expr):
            # GETVARS-PATCH: end ---
            name = v.decl().name()
            vars_.append(Var(name))
            self._vars[name] = Var(name)
            self._z3_vars[name] = v

        return GR1CoreFormula.of_expr(
            text=text,
            vars=vars_,
            expr=expr,
        )

    # ------------------------------------------------------------------
    # Naming helpers
    # ------------------------------------------------------------------

    def _mk_base_var(self, name: str, sort: Any) -> Any:
        """Create the current-time version of a variable.

                User-facing name:
                    p

                Internal flattened name:
                    p_0

        Args:
            name: Variable name.
            sort: Z3 sort of the variable.

        Returns:
            The computed Any result.

        Raises:
            ValueError: The name already has a different sort.
        """
        if name in self._sorts and self._sorts[name] != sort:
            raise ValueError(f"Variable {name!r} already has sort {self._sorts[name]}, not {sort}")
        flat_name = self._shifted_name(name, 0)
        variable = self._mk_flat_var(flat_name, sort)
        self._sorts[name] = sort
        return variable

    def _mk_flat_var(self, flat_name: str, sort: Any) -> Any:
        """Intern one flattened Z3 constant while preserving its sort.

        Args:
            flat_name: Flattened internal variable name.
            sort: Z3 sort of the variable.

        Returns:
            The computed Any result.

        Raises:
            ValueError: The cached constant has a different sort.
        """
        if flat_name in self._z3_vars and self._z3_vars[flat_name].sort() != sort:
            raise ValueError(f"Variable {flat_name!r} already has a conflicting sort")
        if flat_name not in self._z3_vars:
            self._z3_vars[flat_name] = z3.Const(flat_name, sort)
            self._vars[flat_name] = Var(flat_name)
        return self._z3_vars[flat_name]

    def _shifted_name(self, base: str, depth: int) -> str:
        """Construct this flattener's internal name for ``depth``.

        Args:
            base: Base variable name.
            depth: Bounded-next depth.

        Returns:
            The computed str result.
        """
        return f"{base}{self.next_separator}{depth}"

    def _parse_flat_name(self, name: str) -> Tuple[str, int]:
        """Parse flattened variable names.

                Supports:
                    p       -> (p, 0)
                    p_0     -> (p, 0)
                    p_1     -> (p, 1)
                    q_12    -> (q, 12)

                If the name is not in flattened form, treat it as depth 0.

        Args:
            name: Variable name.

        Returns:
            The computed Tuple[str, int] result.
        """
        if self.next_separator not in name:
            return name, 0

        base, maybe_depth = name.rsplit(self.next_separator, 1)

        if maybe_depth.isdigit():
            return base, int(maybe_depth)

        return name, 0

Bool(name)

Create and return the current-time Boolean name_0.

Parameters:

Name Type Description Default
name str

Variable name.

required

Returns:

Type Description
Any

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def Bool(self, name: str) -> Any:  # noqa: N802
    """Create and return the current-time Boolean ``name_0``.

    Args:
        name: Variable name.

    Returns:
        The computed Any result.
    """
    return self._mk_base_var(name, z3.BoolSort())

Int(name)

Create and return the current-time integer name_0.

Parameters:

Name Type Description Default
name str

Variable name.

required

Returns:

Type Description
Any

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def Int(self, name: str) -> Any:  # noqa: N802
    """Create and return the current-time integer ``name_0``.

    Args:
        name: Variable name.

    Returns:
        The computed Any result.
    """
    return self._mk_base_var(name, z3.IntSort())

Real(name)

Create and return the current-time real name_0.

Parameters:

Name Type Description Default
name str

Variable name.

required

Returns:

Type Description
Any

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def Real(self, name: str) -> Any:  # noqa: N802
    """Create and return the current-time real ``name_0``.

    Args:
        name: Variable name.

    Returns:
        The computed Any result.
    """
    return self._mk_base_var(name, z3.RealSort())

X(expr)

Syntactic next operator.

Shifts every flattened variable in expr forward by one time step.

Examples:

X(p_0) = p_1 X(q_1) = q_2 X(p_0 & q_1) = p_1 & q_2

Parameters:

Name Type Description Default
expr Any

Z3 expression to process.

required

Returns:

Type Description
Any

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def X(self, expr: Any) -> Any:  # noqa: N802
    """Syntactic next operator.

    Shifts every flattened variable in expr forward by one time step.

    Examples:
        X(p_0) = p_1
        X(q_1) = q_2
        X(p_0 & q_1) = p_1 & q_2

    Args:
        expr: Z3 expression to process.

    Returns:
        The computed Any result.
    """
    substitutions = []

    # GETVARS-PATCH: original (disabled) ---
    # for v in get_vars(expr):
    # GETVARS-PATCH: replacement ---
    for v in _z3_get_vars(expr):
        # GETVARS-PATCH: end ---
        old_name = v.decl().name()
        base, depth = self._parse_flat_name(old_name)
        new_name = self._shifted_name(base, depth + 1)
        new_var = self._mk_flat_var(new_name, v.sort())
        substitutions.append((v, new_var))

    if not substitutions:
        return expr

    return z3.simplify(z3.substitute(expr, *substitutions))

__init__(*, current_suffix='_0', next_separator='_')

Create a flattener with configurable current and depth separators.

Parameters:

Name Type Description Default
current_suffix str

Suffix representing the current state.

'_0'
next_separator str

Separator used before a next-state index.

'_'
Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __init__(self, *, current_suffix: str = "_0", next_separator: str = "_"):
    """Create a flattener with configurable current and depth separators.

    Args:
        current_suffix: Suffix representing the current state.
        next_separator: Separator used before a next-state index.
    """
    self.current_suffix = current_suffix
    self.next_separator = next_separator

    # Maps flattened variable name -> Z3 variable.
    self._z3_vars: Dict[str, Any] = {}

    # Maps flattened variable name -> Pacti Var.
    self._vars: Dict[str, Var] = {}

    # Maps original base variable name -> sort.
    self._sorts: Dict[str, Any] = {}

core(text, expr)

Build a GR1CoreFormula from a flattened Z3 expression.

Parameters:

Name Type Description Default
text str

Human-readable formula text.

required
expr Any

Z3 expression to process.

required

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def core(self, text: str, expr: Any) -> "GR1CoreFormula":
    """Build a GR1CoreFormula from a flattened Z3 expression.

    Args:
        text: Human-readable formula text.
        expr: Z3 expression to process.

    Returns:
        The computed 'GR1CoreFormula' result.
    """
    vars_ = []
    # GETVARS-PATCH: original (disabled) ---
    # for v in get_vars(expr):
    # GETVARS-PATCH: replacement ---
    for v in _z3_get_vars(expr):
        # GETVARS-PATCH: end ---
        name = v.decl().name()
        vars_.append(Var(name))
        self._vars[name] = Var(name)
        self._z3_vars[name] = v

    return GR1CoreFormula.of_expr(
        text=text,
        vars=vars_,
        expr=expr,
    )

GR1SolverError

Bases: RuntimeError

A required solver decision or quantifier elimination was unavailable.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
class GR1SolverError(RuntimeError):
    """A required solver decision or quantifier elimination was unavailable."""

GR1SyntaxNode dataclass

Immutable user-facing AST for a bounded-next GR(1) core.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@dataclass(frozen=True)
class GR1SyntaxNode:
    """Immutable user-facing AST for a bounded-next GR(1) core."""

    kind: str
    value: Optional[str] = None
    children: Tuple["GR1SyntaxNode", ...] = ()

    def next_depth(self, depth: int = 0) -> int:
        """Return the greatest Next nesting preceding a variable leaf.

        Args:
            depth: Current nesting depth.

        Returns:
            Maximum Next depth.
        """
        if self.kind == "variable":
            return depth
        return max(
            (child.next_depth(depth + (self.kind == "next")) for child in self.children),
            default=0,
        )

    def rename(self, source: str, target: str) -> "GR1SyntaxNode":
        """Structurally rename exact variable leaves, including below ``X``.

        Args:
            source: Source variable or name.
            target: Target variable, name, or obligation.

        Returns:
            The computed 'GR1SyntaxNode' result.
        """
        value = target if self.kind == "variable" and self.value == source else self.value
        return GR1SyntaxNode(
            self.kind,
            value,
            tuple(child.rename(source, target) for child in self.children),
        )

    def to_text(self) -> str:
        """Render canonical, user-facing bounded-next formula text.

        Returns:
            The computed str result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if self.kind in {"variable", "number", "boolean"}:
            return cast(str, self.value)
        if self.kind == "next":
            return f"X({self.children[0].to_text()})"
        if self.kind == "unary":
            operator = "!" if self.value == "not" else cast(str, self.value)
            return f"{operator}({self.children[0].to_text()})"
        if self.kind == "binary":
            return f"({self.children[0].to_text()} {self.value} {self.children[1].to_text()})"
        raise ValueError(f"Unknown GR(1) syntax-node kind: {self.kind}")

    def to_z3(self, variable_sorts: Dict[str, Any], depth: int = 0, expected_sort: Optional[Any] = None) -> Any:
        """Compile to Z3, flattening variables relative to ``depth``.

        Args:
            variable_sorts: Declared sort for each base variable.
            depth: Bounded-next depth.
            expected_sort: Expected sort inherited from the parent expression.

        Returns:
            The computed Any result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        compilers = {
            "variable": _compile_variable_node,
            "number": _compile_number_node,
            "boolean": _compile_boolean_node,
            "next": _compile_next_node,
            "unary": _compile_unary_node,
            "binary": _compile_binary_node,
        }
        compiler = compilers.get(self.kind)
        if compiler is None:
            raise ValueError(f"Unknown GR(1) syntax-node kind: {self.kind}")
        return compiler(self, variable_sorts, depth, expected_sort)

next_depth(depth=0)

Return the greatest Next nesting preceding a variable leaf.

Parameters:

Name Type Description Default
depth int

Current nesting depth.

0

Returns:

Type Description
int

Maximum Next depth.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def next_depth(self, depth: int = 0) -> int:
    """Return the greatest Next nesting preceding a variable leaf.

    Args:
        depth: Current nesting depth.

    Returns:
        Maximum Next depth.
    """
    if self.kind == "variable":
        return depth
    return max(
        (child.next_depth(depth + (self.kind == "next")) for child in self.children),
        default=0,
    )

rename(source, target)

Structurally rename exact variable leaves, including below X.

Parameters:

Name Type Description Default
source str

Source variable or name.

required
target str

Target variable, name, or obligation.

required

Returns:

Type Description
'GR1SyntaxNode'

The computed 'GR1SyntaxNode' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def rename(self, source: str, target: str) -> "GR1SyntaxNode":
    """Structurally rename exact variable leaves, including below ``X``.

    Args:
        source: Source variable or name.
        target: Target variable, name, or obligation.

    Returns:
        The computed 'GR1SyntaxNode' result.
    """
    value = target if self.kind == "variable" and self.value == source else self.value
    return GR1SyntaxNode(
        self.kind,
        value,
        tuple(child.rename(source, target) for child in self.children),
    )

to_text()

Render canonical, user-facing bounded-next formula text.

Returns:

Type Description
str

The computed str result.

Raises:

Type Description
ValueError

If the supplied value is invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_text(self) -> str:
    """Render canonical, user-facing bounded-next formula text.

    Returns:
        The computed str result.

    Raises:
        ValueError: If the supplied value is invalid.
    """
    if self.kind in {"variable", "number", "boolean"}:
        return cast(str, self.value)
    if self.kind == "next":
        return f"X({self.children[0].to_text()})"
    if self.kind == "unary":
        operator = "!" if self.value == "not" else cast(str, self.value)
        return f"{operator}({self.children[0].to_text()})"
    if self.kind == "binary":
        return f"({self.children[0].to_text()} {self.value} {self.children[1].to_text()})"
    raise ValueError(f"Unknown GR(1) syntax-node kind: {self.kind}")

to_z3(variable_sorts, depth=0, expected_sort=None)

Compile to Z3, flattening variables relative to depth.

Parameters:

Name Type Description Default
variable_sorts Dict[str, Any]

Declared sort for each base variable.

required
depth int

Bounded-next depth.

0
expected_sort Optional[Any]

Expected sort inherited from the parent expression.

None

Returns:

Type Description
Any

The computed Any result.

Raises:

Type Description
ValueError

If the supplied value is invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_z3(self, variable_sorts: Dict[str, Any], depth: int = 0, expected_sort: Optional[Any] = None) -> Any:
    """Compile to Z3, flattening variables relative to ``depth``.

    Args:
        variable_sorts: Declared sort for each base variable.
        depth: Bounded-next depth.
        expected_sort: Expected sort inherited from the parent expression.

    Returns:
        The computed Any result.

    Raises:
        ValueError: If the supplied value is invalid.
    """
    compilers = {
        "variable": _compile_variable_node,
        "number": _compile_number_node,
        "boolean": _compile_boolean_node,
        "next": _compile_next_node,
        "unary": _compile_unary_node,
        "binary": _compile_binary_node,
    }
    compiler = compilers.get(self.kind)
    if compiler is None:
        raise ValueError(f"Unknown GR(1) syntax-node kind: {self.kind}")
    return compiler(self, variable_sorts, depth, expected_sort)

GR1Tag

Bases: str, Enum

Temporal bucket tags for initial, invariant, and liveness formulas.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
class GR1Tag(str, Enum):  # noqa: WPS600
    """Temporal bucket tags for initial, invariant, and liveness formulas."""

    INIT = "init"  # noqa: WPS115
    INV = "inv"  # noqa: WPS115  # □φ
    LIV = "liv"  # noqa: WPS115  # □◇φ

GR1Term dataclass

Bases: Term

A single GR(1) term = (tag, core).

Semantics

Init

φ INV: □φ LIV: □◇φ

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@dataclass(frozen=True)
class GR1Term(Term):
    """
    A single GR(1) term = (tag, core).

    Semantics:
      INIT:  φ
      INV:   □φ
      LIV:   □◇φ
    """

    tag: GR1Tag
    core: GR1CoreFormula

    def __eq__(self, other: object) -> bool:
        """Compare both temporal tag and core formula.

        Args:
            other: Other term list or contract.

        Returns:
            The computed Any result.
        """
        if not isinstance(other, GR1Term):
            return False
        return self.tag == other.tag and self.core == other.core

    def __hash__(self) -> int:
        """Hash consistently with structural term equality.

        Returns:
            The computed Any result.
        """
        return hash((self.tag, self.core))

    @property
    def vars(self) -> List[Var]:  # noqa: A003
        """Expose base interface variables rather than flattened instances.

        Returns:
            The computed List[Var] result.
        """
        return sorted({Var(_base_var_name(v)) for v in self.core.vars}, key=lambda v: v.name)

    def contains_var(self, var_to_seek: Var) -> bool:
        """Test relevance by exact or base-variable name.

        Args:
            var_to_seek: Var to seek.

        Returns:
            The computed bool result.
        """
        return any(
            variable == var_to_seek or _base_var_name(variable) == var_to_seek.name for variable in self.core.vars
        )

    def rename_variable(self, source_var: Var, target_var: Var) -> "GR1Term":
        """Rename one base variable throughout the term's core.

        Args:
            source_var: Source var.
            target_var: Target var.

        Returns:
            The computed 'GR1Term' result.
        """
        if source_var == target_var:
            return self
        return GR1Term(self.tag, self.core.rename_variable(source_var, target_var))

    def copy(self) -> "GR1Term":
        """Copy the immutable term while preserving AST and Z3 data.

        Returns:
            The computed 'GR1Term' result.
        """
        return GR1Term(
            self.tag,
            (
                GR1CoreFormula.of_expr(
                    self.core.text,
                    self.core.vars,
                    self.core.expr,
                    syntax=self.core.syntax,
                    raw_expr=self.core.raw_expr,
                    serialized_machine=copy.deepcopy(self.core.serialized_machine),
                    next_depth=_core_next_depth(self.core),
                )
                if self.core.expr is not None
                else GR1CoreFormula.of(self.core.text, self.core.vars)
            ),
        )

    def __str__(self) -> str:
        """Render the core together with its implicit temporal operator.

        Returns:
            The computed str result.
        """
        if self.tag == GR1Tag.INIT:
            return f"INIT({self.core})"
        if self.tag == GR1Tag.INV:
            return f"INV(□ {self.core})"
        return f"LIV(□◇ {self.core})"

    def __repr__(self) -> str:
        """Return a concise debugging representation.

        Returns:
            The computed str result.
        """
        return f"<GR1Term {self}>"

vars property

Expose base interface variables rather than flattened instances.

Returns:

Type Description
List[Var]

The computed List[Var] result.

__eq__(other)

Compare both temporal tag and core formula.

Parameters:

Name Type Description Default
other object

Other term list or contract.

required

Returns:

Type Description
bool

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __eq__(self, other: object) -> bool:
    """Compare both temporal tag and core formula.

    Args:
        other: Other term list or contract.

    Returns:
        The computed Any result.
    """
    if not isinstance(other, GR1Term):
        return False
    return self.tag == other.tag and self.core == other.core

__hash__()

Hash consistently with structural term equality.

Returns:

Type Description
int

The computed Any result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __hash__(self) -> int:
    """Hash consistently with structural term equality.

    Returns:
        The computed Any result.
    """
    return hash((self.tag, self.core))

__repr__()

Return a concise debugging representation.

Returns:

Type Description
str

The computed str result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __repr__(self) -> str:
    """Return a concise debugging representation.

    Returns:
        The computed str result.
    """
    return f"<GR1Term {self}>"

__str__()

Render the core together with its implicit temporal operator.

Returns:

Type Description
str

The computed str result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __str__(self) -> str:
    """Render the core together with its implicit temporal operator.

    Returns:
        The computed str result.
    """
    if self.tag == GR1Tag.INIT:
        return f"INIT({self.core})"
    if self.tag == GR1Tag.INV:
        return f"INV(□ {self.core})"
    return f"LIV(□◇ {self.core})"

contains_var(var_to_seek)

Test relevance by exact or base-variable name.

Parameters:

Name Type Description Default
var_to_seek Var

Var to seek.

required

Returns:

Type Description
bool

The computed bool result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def contains_var(self, var_to_seek: Var) -> bool:
    """Test relevance by exact or base-variable name.

    Args:
        var_to_seek: Var to seek.

    Returns:
        The computed bool result.
    """
    return any(
        variable == var_to_seek or _base_var_name(variable) == var_to_seek.name for variable in self.core.vars
    )

copy()

Copy the immutable term while preserving AST and Z3 data.

Returns:

Type Description
'GR1Term'

The computed 'GR1Term' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def copy(self) -> "GR1Term":
    """Copy the immutable term while preserving AST and Z3 data.

    Returns:
        The computed 'GR1Term' result.
    """
    return GR1Term(
        self.tag,
        (
            GR1CoreFormula.of_expr(
                self.core.text,
                self.core.vars,
                self.core.expr,
                syntax=self.core.syntax,
                raw_expr=self.core.raw_expr,
                serialized_machine=copy.deepcopy(self.core.serialized_machine),
                next_depth=_core_next_depth(self.core),
            )
            if self.core.expr is not None
            else GR1CoreFormula.of(self.core.text, self.core.vars)
        ),
    )

rename_variable(source_var, target_var)

Rename one base variable throughout the term's core.

Parameters:

Name Type Description Default
source_var Var

Source var.

required
target_var Var

Target var.

required

Returns:

Type Description
'GR1Term'

The computed 'GR1Term' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def rename_variable(self, source_var: Var, target_var: Var) -> "GR1Term":
    """Rename one base variable throughout the term's core.

    Args:
        source_var: Source var.
        target_var: Target var.

    Returns:
        The computed 'GR1Term' result.
    """
    if source_var == target_var:
        return self
    return GR1Term(self.tag, self.core.rename_variable(source_var, target_var))

GR1TermList

Bases: TermList

A conjunction of GR(1) terms.

Multiple LIV terms remain separate

LIV(φ1), LIV(φ2) means □◇φ1 ∧ □◇φ2,

not □◇(φ1 ∧ φ2).

Simplification canonicalizes only uniform global Next shifts of LIV cores; INIT and INV retain their original depths.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
class GR1TermList(TermList):
    """
    A conjunction of GR(1) terms.

    Multiple LIV terms remain separate:
      LIV(φ1), LIV(φ2) means □◇φ1 ∧ □◇φ2,
    not □◇(φ1 ∧ φ2).

    Simplification canonicalizes only uniform global Next shifts of LIV cores;
    INIT and INV retain their original depths.
    """

    def __init__(self, term_list: Optional[List[GR1Term]] = None):
        """Initialize from tagged terms; an omitted list denotes true.

        Args:
            term_list: Term list.
        """
        super().__init__(term_list=term_list or [])

    def init_terms(self) -> List[GR1Term]:
        """Return initial-state terms in their existing order.

        Returns:
            The computed List[GR1Term] result.
        """
        return [cast(GR1Term, t) for t in self.terms if cast(GR1Term, t).tag == GR1Tag.INIT]

    def inv_terms(self) -> List[GR1Term]:
        """Return invariant terms in their existing order.

        Returns:
            The computed List[GR1Term] result.
        """
        return [cast(GR1Term, t) for t in self.terms if cast(GR1Term, t).tag == GR1Tag.INV]

    def liv_terms(self) -> List[GR1Term]:
        """Return separate liveness terms in their existing order.

        Returns:
            The computed List[GR1Term] result.
        """
        return [cast(GR1Term, t) for t in self.terms if cast(GR1Term, t).tag == GR1Tag.LIV]

    def to_bucket_dict(self) -> Dict[str, List[str]]:
        """Serialize readable formula text grouped by temporal bucket.

        Returns:
            The computed Dict[str, List[str]] result.
        """
        return {
            "init": [t.core.text for t in self.init_terms()],
            "inv": [t.core.text for t in self.inv_terms()],
            "liv": [t.core.text for t in self.liv_terms()],
        }

    def copy(self) -> "GR1TermList":
        """Copy every term while preserving bucket order.

        Returns:
            The computed 'GR1TermList' result.
        """
        return GR1TermList([cast(GR1Term, t).copy() for t in self.terms])

    @staticmethod
    def from_bucket_formulas(
        *,
        init: Optional[List[GR1CoreFormula]] = None,
        inv: Optional[List[GR1CoreFormula]] = None,
        liv: Optional[List[GR1CoreFormula]] = None,
    ) -> "GR1TermList":
        """Construct a GR1TermList from formulas grouped by bucket.

        Multiple formulas in each bucket are conjunctive. In particular,
        multiple liveness formulas remain separate liveness terms:
          ∧_i □◇φ_i.

        Args:
            init: Initial-condition formulas.
            inv: Invariant formulas.
            liv: Liveness formulas.

        Returns:
            The computed 'GR1TermList' result.
        """
        terms: List[GR1Term] = []
        for f in init or []:
            terms.append(GR1Term(GR1Tag.INIT, f))
        for f in inv or []:
            terms.append(GR1Term(GR1Tag.INV, f))
        for f in liv or []:
            terms.append(GR1Term(GR1Tag.LIV, f))
        return GR1TermList(terms)

    @staticmethod
    def from_bucket_strings(
        *,
        init: Optional[List[str]] = None,
        inv: Optional[List[str]] = None,
        liv: Optional[List[str]] = None,
        var_map: Optional[FormulaVarMap] = None,
        variable_sorts: Optional[VariableSortMap] = None,
    ) -> "GR1TermList":
        """Convenience constructor when formulas are strings.

        With ``variable_sorts``, formulas are parsed into Z3-backed bounded-next
        cores. Without it, ``var_map`` preserves the legacy text-only behavior.

        Args:
            init: Initial-condition formulas.
            inv: Invariant formulas.
            liv: Liveness formulas.
            var_map: Mapping from formula text to variable names.
            variable_sorts: Declared sort for each base variable.

        Returns:
            The computed 'GR1TermList' result.

        Raises:
            ValueError: If the supplied value is invalid.
        """
        if variable_sorts is not None and var_map is not None:
            raise ValueError("Provide either variable_sorts or var_map, not both")

        parser = GR1CoreParser(variable_sorts) if variable_sorts is not None else None
        var_map = var_map or {}

        return GR1TermList.from_bucket_formulas(
            init=[_parse_bucket_core(text, parser, var_map) for text in (init or [])],
            inv=[_parse_bucket_core(text, parser, var_map) for text in (inv or [])],
            liv=[_parse_bucket_core(text, parser, var_map) for text in (liv or [])],
        )

    def __hash__(self) -> int:
        """Hash the ordered conjunction of terms.

        Returns:
            The computed int result.
        """
        return hash(tuple(self.terms))

    def contains_behavior(self, behavior: Any) -> bool:
        """Check a finite trace or ultimately-periodic lasso against this GR(1) list.

                A plain sequence is interpreted as a finite prefix and can check INIT
                and every complete INV window. LIV requires ``GR1Behavior`` with a
                ``loop_start``, because recurrence cannot be established by a finite
                prefix. On a lasso, each liveness core must occur in the repeating loop.

        Args:
            behavior: Behavior or trace to check.

        Returns:
            The computed bool result.

        """
        trace = _coerce_gr1_behavior(behavior)
        return (
            _contains_init_behavior(self.init_terms(), trace)
            and _contains_inv_behavior(self.inv_terms(), trace)
            and _contains_liv_behavior(self.liv_terms(), trace)
        )

    def simplify(self, context: Optional["GR1TermList"] = None) -> "GR1TermList":
        """Apply post-CAVE redundancy and optional assumption-relative reduction.

        Exact CAVE evaluation precedes this method. Internal reduction first
        removes redundancies within and across this term list's GR(1) buckets;
        a supplied context is then used separately for assume-guarantee
        redundancy. Neither stage changes the six CAVE formulas.

        Args:
            context: Context used by the operation.

        Returns:
            The computed 'GR1TermList' result.
        """
        if any(cast(GR1Term, term).core.expr is None for term in self.terms):
            return _deduplicate_text_terms(self.terms)
        semantic_context = _usable_simplification_context(context)
        return _simplify_expression_terms(self, semantic_context)

    def to_pretty_string(self, compact: bool = False) -> str:
        """Return a read-only Unicode rendering of this GR(1) term list.

        Every INIT core is listed separately, every INV core receives its own
        ``□``, and every LIV core retains its own ``□◇`` operator. Empty
        bucket-view sections are omitted; a completely empty list renders as
        ``true``. No terms, formulas, metadata, or serialization are changed.

        Args:
            compact: Return one semantic conjunction instead of bucket lines.

        Returns:
            Unicode user-facing GR(1) text.
        """
        init = [_unicode_core_text(term.core) for term in self.init_terms()]
        inv = [_unicode_core_text(term.core) for term in self.inv_terms()]
        liv = [_unicode_core_text(term.core) for term in self.liv_terms()]

        if compact:
            clauses: List[str] = []
            clauses.extend(f"({core})" for core in init)
            clauses.extend(f"□({core})" for core in inv)
            # Always delimit the complete justice core.  Without these outer
            # parentheses, a conjunctive core such as ``p ∧ q`` is rendered as
            # ``□◇p ∧ q``, which misleadingly places only ``p`` in the scope
            # of the temporal operator.
            clauses.extend(f"□◇({core})" for core in liv)
            return " ∧ ".join(clauses) if clauses else "true"

        if not init and not inv and not liv:
            return "true"
        lines: List[str] = []
        if init:
            lines.append("INIT:")
            lines.extend(f"  {core}" for core in init)
        if inv:
            lines.append("INV:")
            lines.extend(f"  □({core})" for core in inv)
        if liv:
            lines.append("LIV:")
            lines.extend(f"  □◇({core})" for core in liv)
        return "\n".join(lines)

    def refines(self, other: "GR1TermList") -> bool:
        """Sufficient GR(1) refinement check using Z3 expressions.

                INIT first uses pointwise implication, then a bounded iterative
                shift-closure of only the antecedent/source invariant terms.
                INV uses the same bounded source-closure proof strategy. An UNSAT
                finite-window certificate is sound; SAT means only that refinement
                was not proved within the budget.

                LIV is checked separately.  Every target liveness term must be
                established either by a pointwise-stronger source liveness core or by
                a bounded iterative shift-closure of the source invariant bucket.
                It also combines that closure with each source LIV core (W8).
                Closure alone proves the target globally and therefore recurrently.
                Its finite horizon is a proof-search budget, not a completeness bound.

                This remains a structured sufficient GR(1) check, not a general LTL
                implication solver.  In particular, separate source liveness terms are
                never conjoined inside one ``GF`` obligation.

        Args:
            other: Other term list or contract.

        Returns:
            The computed bool result.
        """
        self._require_exprs("self")
        other._require_exprs("other")

        checks = [
            _init_terms_refine(self.init_terms(), self.inv_terms(), other.init_terms()),
            _inv_terms_refine(self.inv_terms(), other.inv_terms()),
            _liv_terms_refine(self.inv_terms(), self.liv_terms(), other.liv_terms()),
        ]

        return all(checks)

    def is_empty(self) -> bool:
        """Return True when finite-window SMT checks prove no infinite behavior.

                The checks cover inconsistent initial/invariant cores and liveness cores
                that cannot occur under the invariant. False is conservative for harder
                overlap-consistency cases not decided by these finite checks.

        Returns:
            The computed bool result.
        """
        self._require_exprs("self")

        init_expr = _and_expr(self.init_terms())
        if self.init_terms():
            init_guard = _shifted_inv_guard_for_cores(
                self.inv_terms(),
                [term.core for term in self.init_terms()],
            )
            if not _is_sat(z3.And(init_expr, init_guard)):
                return True

        if self.inv_terms() and not _is_sat(_and_expr(self.inv_terms())):
            return True

        for liv_term in self.liv_terms():
            inv_guard = _shifted_inv_guard_for_cores(self.inv_terms(), [liv_term.core])
            if not _is_sat(z3.And(inv_guard, cast(Any, liv_term.core.expr))):
                return True
        return False

    def get_terms_with_vars(self, vars_to_seek: List[Var]) -> "GR1TermList":
        """Return terms mentioning any sought base variable.

        Args:
            vars_to_seek: Vars to seek.

        Returns:
            The computed 'GR1TermList' result.
        """
        return GR1TermList(
            [
                cast(GR1Term, term)
                for term in self.terms
                if any(cast(GR1Term, term).contains_var(variable) for variable in vars_to_seek)
            ]
        )

    def elim_vars_by_refining(
        self,
        context: "GR1TermList",
        vars_to_elim: List[Var],
        simplify: bool,
        tactics_order: List[int],
    ) -> Tuple["GR1TermList", TacticStatistics]:
        """SMT-style refinement elimination for GR(1).

        INIT:
            forall p. [gamma_init ∧ Gamma_inv^[0:h_B] => phi_init],
            B={gamma_init, phi_init}

        INV:
            forall p. [Gamma_inv^[0:h_B] => phi_inv], B={phi_inv}

        Every LIV target, including elimination-free targets:
            construct GF(psi_i,0) from the invariant window alone, and
            G(psi_i,j) from the window and each context liveness core j.
            Synthetic horizon: d(phi_i); genuine: max(d(phi_i), d(gamma_liv,j)).
            Project every branch before deterministic tag-preserving selection.
            No relevance, viability, or mixed-wrapper dominance filtering occurs.

        Context liveness terms are processed separately and are not conjoined.

        Args:
            context: Context used by the operation.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Tuple['GR1TermList', TacticStatistics] result.
        """
        self._require_exprs("self")
        context._require_exprs("context")
        gamma_init_expr = _and_expr(context.init_terms())
        new_terms: List[GR1Term] = []
        combined_init = _conjoin_bucket_terms(GR1Tag.INIT, self.init_terms()) or _true_bucket_term(GR1Tag.INIT)
        combined_inv = _conjoin_bucket_terms(GR1Tag.INV, self.inv_terms())
        refined_init = _refine_gr1_term(combined_init, context, gamma_init_expr, vars_to_elim)
        _append_nontrivial_init(new_terms, refined_init)
        if combined_inv is not None:
            new_terms.append(_refine_gr1_term(combined_inv, context, gamma_init_expr, vars_to_elim))
        for liv_term in self.liv_terms():
            new_terms.append(_refine_gr1_term(liv_term, context, gamma_init_expr, vars_to_elim))

        res = GR1TermList(new_terms)
        if simplify:
            res = res.simplify(context=context)

        stats: TacticStatistics = []
        return res, stats

    def elim_vars_by_relaxing(
        self,
        context: "GR1TermList",
        vars_to_elim: List[Var],
        simplify: bool,
        tactics_order: List[int],
    ) -> Tuple["GR1TermList", TacticStatistics]:
        """SMT-style relaxation elimination for GR(1).

        INIT:
            exists p. [gamma_init ∧ Gamma_inv^[0:h_B] ∧ phi_init],
            B={gamma_init, phi_init}

        INV:
            exists p. [Gamma_inv^[0:h_B] ∧ phi_inv], B={phi_inv}, stored as INV

        LIV:
            project every context and target liveness core separately, discard
            trivial projections, and remove equivalent or implied cores.

        The remaining projected liveness terms remain separate LIV conjuncts.
        An empty INV bucket is true and still projects the invariant context.
        With simplify=False this returns the raw independently decomposed CAVE
        construction. With simplify=True it subsequently reduces obligations
        relative to context; standalone strongestness concerns the raw result.

        Args:
            context: Context used by the operation.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Tuple['GR1TermList', TacticStatistics] result.
        """
        self._require_exprs("self")
        context._require_exprs("context")
        res = _raw_relaxation_cave(self, context, vars_to_elim)
        if simplify:
            res = res.simplify(context=context)

        stats: TacticStatistics = []
        return res, stats

    def elim_vars_by_relaxing_assumptions(
        self,
        context: "GR1TermList",
        vars_to_elim: List[Var],
        simplify: bool,
        tactics_order: List[int],
    ) -> Tuple["GR1TermList", TacticStatistics]:
        """Preserve canonical buckets across redundant assumption saturation.

        Generic composition performs a final guarantee relaxation in the
        composed assumption context. If neither the target nor context still
        mentions a variable to hide, conjoining that context is redundant at
        contract level but replaces canonical GR(1) cores with saturated
        Boolean encodings. Keep the canonical cores in that case. If hiding is
        still required, use ordinary GR(1) relaxation because assumptions may
        be essential to the projection.

        Args:
            context: Context used by the operation.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Tuple['GR1TermList', TacticStatistics] result.

        Args:
            context: Context constraining the elimination.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify before elimination.
            tactics_order: Ordered tactic identifiers.

        Returns:
            The projected terms and tactic statistics.
        """
        target_needs_elimination = bool(self.get_terms_with_vars(vars_to_elim).terms)
        context_aids_elimination = bool(context.get_terms_with_vars(vars_to_elim).terms)
        if not target_needs_elimination and not context_aids_elimination:
            result = self.copy()
            if not result.init_terms():
                # At this point composition has already combined the two raw
                # CAVE guarantee projections. With an empty target INIT, the
                # paper still evaluates its existential bound against that
                # combined invariant context. Materialize this raw boundary
                # consequence before any later cross-bucket presentation pass.
                empty_init = _true_bucket_term(GR1Tag.INIT)
                projected_init = _relax_non_liv_term(
                    empty_init,
                    result,
                    z3.BoolVal(True),
                    vars_to_elim,
                )
                augmented_terms = list(cast(List[GR1Term], result.terms))
                _append_nontrivial_init(augmented_terms, projected_init)
                result = GR1TermList(augmented_terms)
            if simplify:
                result = result.simplify()
            return result, []
        return self.elim_vars_by_relaxing(
            context,
            vars_to_elim,
            simplify,
            tactics_order,
        )

    def elim_vars_by_relaxing_quotient_context(
        self,
        context: "GR1TermList",
        vars_to_elim: List[Var],
        simplify: bool,
        tactics_order: List[int],
    ) -> Tuple["GR1TermList", TacticStatistics]:
        """Project quotient assumptions with shift-closed divisor guarantees.

        Keeping ``self`` as the target and divisor guarantees as ``context``
        lets the ordinary GR(1) INV rule construct Gamma_inv^[0:h] through the
        target horizon instead of losing provenance in a prior TermList union.
        INIT and separate LIV projection use the same canonical buckets.

        Args:
            context: Context used by the operation.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Tuple['GR1TermList', TacticStatistics] result.

        Args:
            context: Context constraining the elimination.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify before elimination.
            tactics_order: Ordered tactic identifiers.

        Returns:
            The projected terms and tactic statistics.
        """
        result, stats = self.elim_vars_by_relaxing(
            context,
            vars_to_elim,
            simplify=False,
            tactics_order=tactics_order,
        )
        # Divisor guarantees aid projection but are not assumptions of the
        # quotient result. Simplifying in that context would incorrectly erase
        # projected obligations such as LIV(p) merely because context has p.
        return (result.simplify() if simplify else result), stats

    def elim_vars_by_refining_quotient_context(
        self,
        divisor_guarantees: "GR1TermList",
        system_assumptions: "GR1TermList",
        vars_to_elim: List[Var],
        simplify: bool,
        tactics_order: List[int],
    ) -> Tuple["GR1TermList", TacticStatistics]:
        """Refine canonical targets using canonical divisor guarantees.

        System assumptions are deliberately not merged into this first CAVE
        context: generic quotient processes them in its following refinement
        pass. Merging them here changes canonical cores (for example ``r=q``)
        into guarded predicates (``p -> r``) before GR(1) bucket rules run.

        Args:
            divisor_guarantees: Divisor guarantees.
            system_assumptions: System assumptions.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify the resulting formulas.
            tactics_order: Preferred quantifier-elimination tactic order.

        Returns:
            The computed Tuple['GR1TermList', TacticStatistics] result.

        Args:
            divisor_guarantees: Guarantees of the known component.
            system_assumptions: Assumptions of the target system.
            vars_to_elim: Variables to eliminate.
            simplify: Whether to simplify before elimination.
            tactics_order: Ordered tactic identifiers.

        Returns:
            The projected terms and tactic statistics.
        """
        del system_assumptions
        return self.elim_vars_by_refining(
            divisor_guarantees,
            vars_to_elim,
            simplify,
            tactics_order,
        )

    def _require_exprs(self, where: str) -> None:
        """Reject operations whose terms lack executable Z3 expressions.

        Args:
            where: Label identifying the checked expression collection.

        Raises:
            NotImplementedError: If the supplied value is invalid.
        """
        missing = []
        for i, t_any in enumerate(self.terms):
            t = cast(GR1Term, t_any)
            if t.core.expr is None:
                missing.append(f"{where}[{i}] {t.tag.value}: {t.core.text}")
        if missing:
            raise NotImplementedError(
                "Z3-based GR(1) elimination requires core.expr for every term.\n"
                + "Missing expressions in:\n- "
                + "\n- ".join(missing)
            )

__hash__()

Hash the ordered conjunction of terms.

Returns:

Type Description
int

The computed int result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __hash__(self) -> int:
    """Hash the ordered conjunction of terms.

    Returns:
        The computed int result.
    """
    return hash(tuple(self.terms))

__init__(term_list=None)

Initialize from tagged terms; an omitted list denotes true.

Parameters:

Name Type Description Default
term_list Optional[List[GR1Term]]

Term list.

None
Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def __init__(self, term_list: Optional[List[GR1Term]] = None):
    """Initialize from tagged terms; an omitted list denotes true.

    Args:
        term_list: Term list.
    """
    super().__init__(term_list=term_list or [])

contains_behavior(behavior)

Check a finite trace or ultimately-periodic lasso against this GR(1) list.

    A plain sequence is interpreted as a finite prefix and can check INIT
    and every complete INV window. LIV requires ``GR1Behavior`` with a
    ``loop_start``, because recurrence cannot be established by a finite
    prefix. On a lasso, each liveness core must occur in the repeating loop.

Parameters:

Name Type Description Default
behavior Any

Behavior or trace to check.

required

Returns:

Type Description
bool

The computed bool result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def contains_behavior(self, behavior: Any) -> bool:
    """Check a finite trace or ultimately-periodic lasso against this GR(1) list.

            A plain sequence is interpreted as a finite prefix and can check INIT
            and every complete INV window. LIV requires ``GR1Behavior`` with a
            ``loop_start``, because recurrence cannot be established by a finite
            prefix. On a lasso, each liveness core must occur in the repeating loop.

    Args:
        behavior: Behavior or trace to check.

    Returns:
        The computed bool result.

    """
    trace = _coerce_gr1_behavior(behavior)
    return (
        _contains_init_behavior(self.init_terms(), trace)
        and _contains_inv_behavior(self.inv_terms(), trace)
        and _contains_liv_behavior(self.liv_terms(), trace)
    )

copy()

Copy every term while preserving bucket order.

Returns:

Type Description
'GR1TermList'

The computed 'GR1TermList' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def copy(self) -> "GR1TermList":
    """Copy every term while preserving bucket order.

    Returns:
        The computed 'GR1TermList' result.
    """
    return GR1TermList([cast(GR1Term, t).copy() for t in self.terms])

elim_vars_by_refining(context, vars_to_elim, simplify, tactics_order)

SMT-style refinement elimination for GR(1).

INIT

forall p. [gamma_init ∧ Gamma_inv^[0:h_B] => phi_init], B={gamma_init, phi_init}

INV

forall p. [Gamma_inv^[0:h_B] => phi_inv], B={phi_inv}

Every LIV target, including elimination-free targets: construct GF(psi_i,0) from the invariant window alone, and G(psi_i,j) from the window and each context liveness core j. Synthetic horizon: d(phi_i); genuine: max(d(phi_i), d(gamma_liv,j)). Project every branch before deterministic tag-preserving selection. No relevance, viability, or mixed-wrapper dominance filtering occurs.

Context liveness terms are processed separately and are not conjoined.

Parameters:

Name Type Description Default
context 'GR1TermList'

Context used by the operation.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify the resulting formulas.

required
tactics_order List[int]

Preferred quantifier-elimination tactic order.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The computed Tuple['GR1TermList', TacticStatistics] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def elim_vars_by_refining(
    self,
    context: "GR1TermList",
    vars_to_elim: List[Var],
    simplify: bool,
    tactics_order: List[int],
) -> Tuple["GR1TermList", TacticStatistics]:
    """SMT-style refinement elimination for GR(1).

    INIT:
        forall p. [gamma_init ∧ Gamma_inv^[0:h_B] => phi_init],
        B={gamma_init, phi_init}

    INV:
        forall p. [Gamma_inv^[0:h_B] => phi_inv], B={phi_inv}

    Every LIV target, including elimination-free targets:
        construct GF(psi_i,0) from the invariant window alone, and
        G(psi_i,j) from the window and each context liveness core j.
        Synthetic horizon: d(phi_i); genuine: max(d(phi_i), d(gamma_liv,j)).
        Project every branch before deterministic tag-preserving selection.
        No relevance, viability, or mixed-wrapper dominance filtering occurs.

    Context liveness terms are processed separately and are not conjoined.

    Args:
        context: Context used by the operation.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Tuple['GR1TermList', TacticStatistics] result.
    """
    self._require_exprs("self")
    context._require_exprs("context")
    gamma_init_expr = _and_expr(context.init_terms())
    new_terms: List[GR1Term] = []
    combined_init = _conjoin_bucket_terms(GR1Tag.INIT, self.init_terms()) or _true_bucket_term(GR1Tag.INIT)
    combined_inv = _conjoin_bucket_terms(GR1Tag.INV, self.inv_terms())
    refined_init = _refine_gr1_term(combined_init, context, gamma_init_expr, vars_to_elim)
    _append_nontrivial_init(new_terms, refined_init)
    if combined_inv is not None:
        new_terms.append(_refine_gr1_term(combined_inv, context, gamma_init_expr, vars_to_elim))
    for liv_term in self.liv_terms():
        new_terms.append(_refine_gr1_term(liv_term, context, gamma_init_expr, vars_to_elim))

    res = GR1TermList(new_terms)
    if simplify:
        res = res.simplify(context=context)

    stats: TacticStatistics = []
    return res, stats

elim_vars_by_refining_quotient_context(divisor_guarantees, system_assumptions, vars_to_elim, simplify, tactics_order)

Refine canonical targets using canonical divisor guarantees.

System assumptions are deliberately not merged into this first CAVE context: generic quotient processes them in its following refinement pass. Merging them here changes canonical cores (for example r=q) into guarded predicates (p -> r) before GR(1) bucket rules run.

Parameters:

Name Type Description Default
divisor_guarantees 'GR1TermList'

Divisor guarantees.

required
system_assumptions 'GR1TermList'

System assumptions.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify the resulting formulas.

required
tactics_order List[int]

Preferred quantifier-elimination tactic order.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The computed Tuple['GR1TermList', TacticStatistics] result.

Parameters:

Name Type Description Default
divisor_guarantees 'GR1TermList'

Guarantees of the known component.

required
system_assumptions 'GR1TermList'

Assumptions of the target system.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify before elimination.

required
tactics_order List[int]

Ordered tactic identifiers.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The projected terms and tactic statistics.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def elim_vars_by_refining_quotient_context(
    self,
    divisor_guarantees: "GR1TermList",
    system_assumptions: "GR1TermList",
    vars_to_elim: List[Var],
    simplify: bool,
    tactics_order: List[int],
) -> Tuple["GR1TermList", TacticStatistics]:
    """Refine canonical targets using canonical divisor guarantees.

    System assumptions are deliberately not merged into this first CAVE
    context: generic quotient processes them in its following refinement
    pass. Merging them here changes canonical cores (for example ``r=q``)
    into guarded predicates (``p -> r``) before GR(1) bucket rules run.

    Args:
        divisor_guarantees: Divisor guarantees.
        system_assumptions: System assumptions.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Tuple['GR1TermList', TacticStatistics] result.

    Args:
        divisor_guarantees: Guarantees of the known component.
        system_assumptions: Assumptions of the target system.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify before elimination.
        tactics_order: Ordered tactic identifiers.

    Returns:
        The projected terms and tactic statistics.
    """
    del system_assumptions
    return self.elim_vars_by_refining(
        divisor_guarantees,
        vars_to_elim,
        simplify,
        tactics_order,
    )

elim_vars_by_relaxing(context, vars_to_elim, simplify, tactics_order)

SMT-style relaxation elimination for GR(1).

INIT

exists p. [gamma_init ∧ Gamma_inv^[0:h_B] ∧ phi_init], B={gamma_init, phi_init}

INV

exists p. [Gamma_inv^[0:h_B] ∧ phi_inv], B={phi_inv}, stored as INV

LIV

project every context and target liveness core separately, discard trivial projections, and remove equivalent or implied cores.

The remaining projected liveness terms remain separate LIV conjuncts. An empty INV bucket is true and still projects the invariant context. With simplify=False this returns the raw independently decomposed CAVE construction. With simplify=True it subsequently reduces obligations relative to context; standalone strongestness concerns the raw result.

Parameters:

Name Type Description Default
context 'GR1TermList'

Context used by the operation.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify the resulting formulas.

required
tactics_order List[int]

Preferred quantifier-elimination tactic order.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The computed Tuple['GR1TermList', TacticStatistics] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def elim_vars_by_relaxing(
    self,
    context: "GR1TermList",
    vars_to_elim: List[Var],
    simplify: bool,
    tactics_order: List[int],
) -> Tuple["GR1TermList", TacticStatistics]:
    """SMT-style relaxation elimination for GR(1).

    INIT:
        exists p. [gamma_init ∧ Gamma_inv^[0:h_B] ∧ phi_init],
        B={gamma_init, phi_init}

    INV:
        exists p. [Gamma_inv^[0:h_B] ∧ phi_inv], B={phi_inv}, stored as INV

    LIV:
        project every context and target liveness core separately, discard
        trivial projections, and remove equivalent or implied cores.

    The remaining projected liveness terms remain separate LIV conjuncts.
    An empty INV bucket is true and still projects the invariant context.
    With simplify=False this returns the raw independently decomposed CAVE
    construction. With simplify=True it subsequently reduces obligations
    relative to context; standalone strongestness concerns the raw result.

    Args:
        context: Context used by the operation.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Tuple['GR1TermList', TacticStatistics] result.
    """
    self._require_exprs("self")
    context._require_exprs("context")
    res = _raw_relaxation_cave(self, context, vars_to_elim)
    if simplify:
        res = res.simplify(context=context)

    stats: TacticStatistics = []
    return res, stats

elim_vars_by_relaxing_assumptions(context, vars_to_elim, simplify, tactics_order)

Preserve canonical buckets across redundant assumption saturation.

Generic composition performs a final guarantee relaxation in the composed assumption context. If neither the target nor context still mentions a variable to hide, conjoining that context is redundant at contract level but replaces canonical GR(1) cores with saturated Boolean encodings. Keep the canonical cores in that case. If hiding is still required, use ordinary GR(1) relaxation because assumptions may be essential to the projection.

Parameters:

Name Type Description Default
context 'GR1TermList'

Context used by the operation.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify the resulting formulas.

required
tactics_order List[int]

Preferred quantifier-elimination tactic order.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The computed Tuple['GR1TermList', TacticStatistics] result.

Parameters:

Name Type Description Default
context 'GR1TermList'

Context constraining the elimination.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify before elimination.

required
tactics_order List[int]

Ordered tactic identifiers.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The projected terms and tactic statistics.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def elim_vars_by_relaxing_assumptions(
    self,
    context: "GR1TermList",
    vars_to_elim: List[Var],
    simplify: bool,
    tactics_order: List[int],
) -> Tuple["GR1TermList", TacticStatistics]:
    """Preserve canonical buckets across redundant assumption saturation.

    Generic composition performs a final guarantee relaxation in the
    composed assumption context. If neither the target nor context still
    mentions a variable to hide, conjoining that context is redundant at
    contract level but replaces canonical GR(1) cores with saturated
    Boolean encodings. Keep the canonical cores in that case. If hiding is
    still required, use ordinary GR(1) relaxation because assumptions may
    be essential to the projection.

    Args:
        context: Context used by the operation.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Tuple['GR1TermList', TacticStatistics] result.

    Args:
        context: Context constraining the elimination.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify before elimination.
        tactics_order: Ordered tactic identifiers.

    Returns:
        The projected terms and tactic statistics.
    """
    target_needs_elimination = bool(self.get_terms_with_vars(vars_to_elim).terms)
    context_aids_elimination = bool(context.get_terms_with_vars(vars_to_elim).terms)
    if not target_needs_elimination and not context_aids_elimination:
        result = self.copy()
        if not result.init_terms():
            # At this point composition has already combined the two raw
            # CAVE guarantee projections. With an empty target INIT, the
            # paper still evaluates its existential bound against that
            # combined invariant context. Materialize this raw boundary
            # consequence before any later cross-bucket presentation pass.
            empty_init = _true_bucket_term(GR1Tag.INIT)
            projected_init = _relax_non_liv_term(
                empty_init,
                result,
                z3.BoolVal(True),
                vars_to_elim,
            )
            augmented_terms = list(cast(List[GR1Term], result.terms))
            _append_nontrivial_init(augmented_terms, projected_init)
            result = GR1TermList(augmented_terms)
        if simplify:
            result = result.simplify()
        return result, []
    return self.elim_vars_by_relaxing(
        context,
        vars_to_elim,
        simplify,
        tactics_order,
    )

elim_vars_by_relaxing_quotient_context(context, vars_to_elim, simplify, tactics_order)

Project quotient assumptions with shift-closed divisor guarantees.

Keeping self as the target and divisor guarantees as context lets the ordinary GR(1) INV rule construct Gamma_inv^[0:h] through the target horizon instead of losing provenance in a prior TermList union. INIT and separate LIV projection use the same canonical buckets.

Parameters:

Name Type Description Default
context 'GR1TermList'

Context used by the operation.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify the resulting formulas.

required
tactics_order List[int]

Preferred quantifier-elimination tactic order.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The computed Tuple['GR1TermList', TacticStatistics] result.

Parameters:

Name Type Description Default
context 'GR1TermList'

Context constraining the elimination.

required
vars_to_elim List[Var]

Variables to eliminate.

required
simplify bool

Whether to simplify before elimination.

required
tactics_order List[int]

Ordered tactic identifiers.

required

Returns:

Type Description
Tuple['GR1TermList', TacticStatistics]

The projected terms and tactic statistics.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def elim_vars_by_relaxing_quotient_context(
    self,
    context: "GR1TermList",
    vars_to_elim: List[Var],
    simplify: bool,
    tactics_order: List[int],
) -> Tuple["GR1TermList", TacticStatistics]:
    """Project quotient assumptions with shift-closed divisor guarantees.

    Keeping ``self`` as the target and divisor guarantees as ``context``
    lets the ordinary GR(1) INV rule construct Gamma_inv^[0:h] through the
    target horizon instead of losing provenance in a prior TermList union.
    INIT and separate LIV projection use the same canonical buckets.

    Args:
        context: Context used by the operation.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify the resulting formulas.
        tactics_order: Preferred quantifier-elimination tactic order.

    Returns:
        The computed Tuple['GR1TermList', TacticStatistics] result.

    Args:
        context: Context constraining the elimination.
        vars_to_elim: Variables to eliminate.
        simplify: Whether to simplify before elimination.
        tactics_order: Ordered tactic identifiers.

    Returns:
        The projected terms and tactic statistics.
    """
    result, stats = self.elim_vars_by_relaxing(
        context,
        vars_to_elim,
        simplify=False,
        tactics_order=tactics_order,
    )
    # Divisor guarantees aid projection but are not assumptions of the
    # quotient result. Simplifying in that context would incorrectly erase
    # projected obligations such as LIV(p) merely because context has p.
    return (result.simplify() if simplify else result), stats

from_bucket_formulas(*, init=None, inv=None, liv=None) staticmethod

Construct a GR1TermList from formulas grouped by bucket.

Multiple formulas in each bucket are conjunctive. In particular, multiple liveness formulas remain separate liveness terms: ∧_i □◇φ_i.

Parameters:

Name Type Description Default
init Optional[List[GR1CoreFormula]]

Initial-condition formulas.

None
inv Optional[List[GR1CoreFormula]]

Invariant formulas.

None
liv Optional[List[GR1CoreFormula]]

Liveness formulas.

None

Returns:

Type Description
'GR1TermList'

The computed 'GR1TermList' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def from_bucket_formulas(
    *,
    init: Optional[List[GR1CoreFormula]] = None,
    inv: Optional[List[GR1CoreFormula]] = None,
    liv: Optional[List[GR1CoreFormula]] = None,
) -> "GR1TermList":
    """Construct a GR1TermList from formulas grouped by bucket.

    Multiple formulas in each bucket are conjunctive. In particular,
    multiple liveness formulas remain separate liveness terms:
      ∧_i □◇φ_i.

    Args:
        init: Initial-condition formulas.
        inv: Invariant formulas.
        liv: Liveness formulas.

    Returns:
        The computed 'GR1TermList' result.
    """
    terms: List[GR1Term] = []
    for f in init or []:
        terms.append(GR1Term(GR1Tag.INIT, f))
    for f in inv or []:
        terms.append(GR1Term(GR1Tag.INV, f))
    for f in liv or []:
        terms.append(GR1Term(GR1Tag.LIV, f))
    return GR1TermList(terms)

from_bucket_strings(*, init=None, inv=None, liv=None, var_map=None, variable_sorts=None) staticmethod

Convenience constructor when formulas are strings.

With variable_sorts, formulas are parsed into Z3-backed bounded-next cores. Without it, var_map preserves the legacy text-only behavior.

Parameters:

Name Type Description Default
init Optional[List[str]]

Initial-condition formulas.

None
inv Optional[List[str]]

Invariant formulas.

None
liv Optional[List[str]]

Liveness formulas.

None
var_map Optional[FormulaVarMap]

Mapping from formula text to variable names.

None
variable_sorts Optional[VariableSortMap]

Declared sort for each base variable.

None

Returns:

Type Description
'GR1TermList'

The computed 'GR1TermList' result.

Raises:

Type Description
ValueError

If the supplied value is invalid.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
@staticmethod
def from_bucket_strings(
    *,
    init: Optional[List[str]] = None,
    inv: Optional[List[str]] = None,
    liv: Optional[List[str]] = None,
    var_map: Optional[FormulaVarMap] = None,
    variable_sorts: Optional[VariableSortMap] = None,
) -> "GR1TermList":
    """Convenience constructor when formulas are strings.

    With ``variable_sorts``, formulas are parsed into Z3-backed bounded-next
    cores. Without it, ``var_map`` preserves the legacy text-only behavior.

    Args:
        init: Initial-condition formulas.
        inv: Invariant formulas.
        liv: Liveness formulas.
        var_map: Mapping from formula text to variable names.
        variable_sorts: Declared sort for each base variable.

    Returns:
        The computed 'GR1TermList' result.

    Raises:
        ValueError: If the supplied value is invalid.
    """
    if variable_sorts is not None and var_map is not None:
        raise ValueError("Provide either variable_sorts or var_map, not both")

    parser = GR1CoreParser(variable_sorts) if variable_sorts is not None else None
    var_map = var_map or {}

    return GR1TermList.from_bucket_formulas(
        init=[_parse_bucket_core(text, parser, var_map) for text in (init or [])],
        inv=[_parse_bucket_core(text, parser, var_map) for text in (inv or [])],
        liv=[_parse_bucket_core(text, parser, var_map) for text in (liv or [])],
    )

get_terms_with_vars(vars_to_seek)

Return terms mentioning any sought base variable.

Parameters:

Name Type Description Default
vars_to_seek List[Var]

Vars to seek.

required

Returns:

Type Description
'GR1TermList'

The computed 'GR1TermList' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def get_terms_with_vars(self, vars_to_seek: List[Var]) -> "GR1TermList":
    """Return terms mentioning any sought base variable.

    Args:
        vars_to_seek: Vars to seek.

    Returns:
        The computed 'GR1TermList' result.
    """
    return GR1TermList(
        [
            cast(GR1Term, term)
            for term in self.terms
            if any(cast(GR1Term, term).contains_var(variable) for variable in vars_to_seek)
        ]
    )

init_terms()

Return initial-state terms in their existing order.

Returns:

Type Description
List[GR1Term]

The computed List[GR1Term] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def init_terms(self) -> List[GR1Term]:
    """Return initial-state terms in their existing order.

    Returns:
        The computed List[GR1Term] result.
    """
    return [cast(GR1Term, t) for t in self.terms if cast(GR1Term, t).tag == GR1Tag.INIT]

inv_terms()

Return invariant terms in their existing order.

Returns:

Type Description
List[GR1Term]

The computed List[GR1Term] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def inv_terms(self) -> List[GR1Term]:
    """Return invariant terms in their existing order.

    Returns:
        The computed List[GR1Term] result.
    """
    return [cast(GR1Term, t) for t in self.terms if cast(GR1Term, t).tag == GR1Tag.INV]

is_empty()

Return True when finite-window SMT checks prove no infinite behavior.

    The checks cover inconsistent initial/invariant cores and liveness cores
    that cannot occur under the invariant. False is conservative for harder
    overlap-consistency cases not decided by these finite checks.

Returns:

Type Description
bool

The computed bool result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def is_empty(self) -> bool:
    """Return True when finite-window SMT checks prove no infinite behavior.

            The checks cover inconsistent initial/invariant cores and liveness cores
            that cannot occur under the invariant. False is conservative for harder
            overlap-consistency cases not decided by these finite checks.

    Returns:
        The computed bool result.
    """
    self._require_exprs("self")

    init_expr = _and_expr(self.init_terms())
    if self.init_terms():
        init_guard = _shifted_inv_guard_for_cores(
            self.inv_terms(),
            [term.core for term in self.init_terms()],
        )
        if not _is_sat(z3.And(init_expr, init_guard)):
            return True

    if self.inv_terms() and not _is_sat(_and_expr(self.inv_terms())):
        return True

    for liv_term in self.liv_terms():
        inv_guard = _shifted_inv_guard_for_cores(self.inv_terms(), [liv_term.core])
        if not _is_sat(z3.And(inv_guard, cast(Any, liv_term.core.expr))):
            return True
    return False

liv_terms()

Return separate liveness terms in their existing order.

Returns:

Type Description
List[GR1Term]

The computed List[GR1Term] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def liv_terms(self) -> List[GR1Term]:
    """Return separate liveness terms in their existing order.

    Returns:
        The computed List[GR1Term] result.
    """
    return [cast(GR1Term, t) for t in self.terms if cast(GR1Term, t).tag == GR1Tag.LIV]

refines(other)

Sufficient GR(1) refinement check using Z3 expressions.

    INIT first uses pointwise implication, then a bounded iterative
    shift-closure of only the antecedent/source invariant terms.
    INV uses the same bounded source-closure proof strategy. An UNSAT
    finite-window certificate is sound; SAT means only that refinement
    was not proved within the budget.

    LIV is checked separately.  Every target liveness term must be
    established either by a pointwise-stronger source liveness core or by
    a bounded iterative shift-closure of the source invariant bucket.
    It also combines that closure with each source LIV core (W8).
    Closure alone proves the target globally and therefore recurrently.
    Its finite horizon is a proof-search budget, not a completeness bound.

    This remains a structured sufficient GR(1) check, not a general LTL
    implication solver.  In particular, separate source liveness terms are
    never conjoined inside one ``GF`` obligation.

Parameters:

Name Type Description Default
other 'GR1TermList'

Other term list or contract.

required

Returns:

Type Description
bool

The computed bool result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def refines(self, other: "GR1TermList") -> bool:
    """Sufficient GR(1) refinement check using Z3 expressions.

            INIT first uses pointwise implication, then a bounded iterative
            shift-closure of only the antecedent/source invariant terms.
            INV uses the same bounded source-closure proof strategy. An UNSAT
            finite-window certificate is sound; SAT means only that refinement
            was not proved within the budget.

            LIV is checked separately.  Every target liveness term must be
            established either by a pointwise-stronger source liveness core or by
            a bounded iterative shift-closure of the source invariant bucket.
            It also combines that closure with each source LIV core (W8).
            Closure alone proves the target globally and therefore recurrently.
            Its finite horizon is a proof-search budget, not a completeness bound.

            This remains a structured sufficient GR(1) check, not a general LTL
            implication solver.  In particular, separate source liveness terms are
            never conjoined inside one ``GF`` obligation.

    Args:
        other: Other term list or contract.

    Returns:
        The computed bool result.
    """
    self._require_exprs("self")
    other._require_exprs("other")

    checks = [
        _init_terms_refine(self.init_terms(), self.inv_terms(), other.init_terms()),
        _inv_terms_refine(self.inv_terms(), other.inv_terms()),
        _liv_terms_refine(self.inv_terms(), self.liv_terms(), other.liv_terms()),
    ]

    return all(checks)

simplify(context=None)

Apply post-CAVE redundancy and optional assumption-relative reduction.

Exact CAVE evaluation precedes this method. Internal reduction first removes redundancies within and across this term list's GR(1) buckets; a supplied context is then used separately for assume-guarantee redundancy. Neither stage changes the six CAVE formulas.

Parameters:

Name Type Description Default
context Optional['GR1TermList']

Context used by the operation.

None

Returns:

Type Description
'GR1TermList'

The computed 'GR1TermList' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def simplify(self, context: Optional["GR1TermList"] = None) -> "GR1TermList":
    """Apply post-CAVE redundancy and optional assumption-relative reduction.

    Exact CAVE evaluation precedes this method. Internal reduction first
    removes redundancies within and across this term list's GR(1) buckets;
    a supplied context is then used separately for assume-guarantee
    redundancy. Neither stage changes the six CAVE formulas.

    Args:
        context: Context used by the operation.

    Returns:
        The computed 'GR1TermList' result.
    """
    if any(cast(GR1Term, term).core.expr is None for term in self.terms):
        return _deduplicate_text_terms(self.terms)
    semantic_context = _usable_simplification_context(context)
    return _simplify_expression_terms(self, semantic_context)

to_bucket_dict()

Serialize readable formula text grouped by temporal bucket.

Returns:

Type Description
Dict[str, List[str]]

The computed Dict[str, List[str]] result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_bucket_dict(self) -> Dict[str, List[str]]:
    """Serialize readable formula text grouped by temporal bucket.

    Returns:
        The computed Dict[str, List[str]] result.
    """
    return {
        "init": [t.core.text for t in self.init_terms()],
        "inv": [t.core.text for t in self.inv_terms()],
        "liv": [t.core.text for t in self.liv_terms()],
    }

to_pretty_string(compact=False)

Return a read-only Unicode rendering of this GR(1) term list.

Every INIT core is listed separately, every INV core receives its own □, and every LIV core retains its own □◇ operator. Empty bucket-view sections are omitted; a completely empty list renders as true. No terms, formulas, metadata, or serialization are changed.

Parameters:

Name Type Description Default
compact bool

Return one semantic conjunction instead of bucket lines.

False

Returns:

Type Description
str

Unicode user-facing GR(1) text.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def to_pretty_string(self, compact: bool = False) -> str:
    """Return a read-only Unicode rendering of this GR(1) term list.

    Every INIT core is listed separately, every INV core receives its own
    ``□``, and every LIV core retains its own ``□◇`` operator. Empty
    bucket-view sections are omitted; a completely empty list renders as
    ``true``. No terms, formulas, metadata, or serialization are changed.

    Args:
        compact: Return one semantic conjunction instead of bucket lines.

    Returns:
        Unicode user-facing GR(1) text.
    """
    init = [_unicode_core_text(term.core) for term in self.init_terms()]
    inv = [_unicode_core_text(term.core) for term in self.inv_terms()]
    liv = [_unicode_core_text(term.core) for term in self.liv_terms()]

    if compact:
        clauses: List[str] = []
        clauses.extend(f"({core})" for core in init)
        clauses.extend(f"□({core})" for core in inv)
        # Always delimit the complete justice core.  Without these outer
        # parentheses, a conjunctive core such as ``p ∧ q`` is rendered as
        # ``□◇p ∧ q``, which misleadingly places only ``p`` in the scope
        # of the temporal operator.
        clauses.extend(f"□◇({core})" for core in liv)
        return " ∧ ".join(clauses) if clauses else "true"

    if not init and not inv and not liv:
        return "true"
    lines: List[str] = []
    if init:
        lines.append("INIT:")
        lines.extend(f"  {core}" for core in init)
    if inv:
        lines.append("INV:")
        lines.extend(f"  □({core})" for core in inv)
    if liv:
        lines.append("LIV:")
        lines.extend(f"  □◇({core})" for core in liv)
    return "\n".join(lines)

canonicalize_mixed_linear_formula(expr, max_boolean_variables=3)

Canonicalize a small Boolean-conditioned rectangular linear formula.

Boolean variables are enumerated up to max_boolean_variables. In each satisfiable valuation, exact Optimize bounds are extracted for every remaining Int/Real variable. The valuation is accepted only when the resulting conjunction of intervals is equivalent to that cofactor. Global envelope bounds are factored out and tighter per-mode bounds are rebuilt as implications. Finally, the complete candidate is equivalence-checked.

The deliberately narrow implementation handles the common QE result in which every Boolean mode selects an axis-aligned interval or box. It is not a general linear-arithmetic or Boolean minimizer. Unsupported sorts, nonlinear/non-rectangular regions, strict/open bounds, excessive Boolean variables, or inconclusive checks return the original expression unchanged.

Parameters:

Name Type Description Default
expr Any

Quantifier-free Z3 Boolean expression.

required
max_boolean_variables int

Maximum number of Boolean valuations to enumerate.

3

Returns:

Type Description
Any

A compact equivalent formula, or the original formula on fallback.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def canonicalize_mixed_linear_formula(expr: Any, max_boolean_variables: int = 3) -> Any:
    """Canonicalize a small Boolean-conditioned rectangular linear formula.

    Boolean variables are enumerated up to ``max_boolean_variables``.  In each
    satisfiable valuation, exact Optimize bounds are extracted for every
    remaining Int/Real variable.  The valuation is accepted only when the
    resulting conjunction of intervals is equivalent to that cofactor.  Global
    envelope bounds are factored out and tighter per-mode bounds are rebuilt as
    implications.  Finally, the complete candidate is equivalence-checked.

    The deliberately narrow implementation handles the common QE result in
    which every Boolean mode selects an axis-aligned interval or box.  It is not
    a general linear-arithmetic or Boolean minimizer.  Unsupported sorts,
    nonlinear/non-rectangular regions, strict/open bounds, excessive Boolean
    variables, or inconclusive checks return the original expression unchanged.

    Args:
        expr: Quantifier-free Z3 Boolean expression.
        max_boolean_variables: Maximum number of Boolean valuations to enumerate.

    Returns:
        A compact equivalent formula, or the original formula on fallback.
    """
    raw_expr = _simplify_expr(expr)
    # GETVARS-PATCH: original (disabled) ---
    # variables = sorted(get_vars(raw_expr), key=lambda variable: variable.decl().name())
    # GETVARS-PATCH: replacement ---
    variables = sorted(_z3_get_vars(raw_expr), key=lambda variable: variable.decl().name())
    # GETVARS-PATCH: end ---
    boolean_vars = [variable for variable in variables if variable.sort() == z3.BoolSort()]
    numeric_vars = [variable for variable in variables if variable.sort() in {z3.IntSort(), z3.RealSort()}]
    if len(boolean_vars) > max_boolean_variables or not numeric_vars:
        return raw_expr
    if len(boolean_vars) + len(numeric_vars) != len(variables):
        return raw_expr

    cases = _rectangular_valuation_cases(raw_expr, boolean_vars, numeric_vars)
    if cases is None:
        return raw_expr

    satisfiable_bounds = [bounds for _, bounds in cases if bounds is not None]
    if not satisfiable_bounds:
        return _equivalence_guarded_formula(raw_expr, z3.BoolVal(False))

    global_bounds, common_parts = _global_rectangular_bounds(numeric_vars, satisfiable_bounds)
    conditioned_parts = _conditioned_rectangular_parts(cases, boolean_vars, numeric_vars, global_bounds)

    candidate = z3.And(*(common_parts + conditioned_parts))
    return _equivalence_guarded_formula(raw_expr, candidate)

parse_gr1_core(formula_text, variable_sorts)

Parse a user-facing bounded-next formula into a Z3-backed GR(1) core.

Parameters:

Name Type Description Default
formula_text str

User-facing bounded-next formula.

required
variable_sorts Dict[str, Any]

Declared sort for each base variable.

required

Returns:

Type Description
'GR1CoreFormula'

The computed 'GR1CoreFormula' result.

Source code in pacti/src/pacti/iocontract/gr1_iocontract.py
def parse_gr1_core(formula_text: str, variable_sorts: Dict[str, Any]) -> "GR1CoreFormula":
    """Parse a user-facing bounded-next formula into a Z3-backed GR(1) core.

    Args:
        formula_text: User-facing bounded-next formula.
        variable_sorts: Declared sort for each base variable.

    Returns:
        The computed 'GR1CoreFormula' result.
    """
    return GR1CoreParser(variable_sorts).parse(formula_text)