From bf9e1f06640c556cf2187ae42903448b809d645b Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sat, 7 Nov 2026 02:19:50 +0100 Subject: [PATCH 01/29] Move propagator files into their own folder --- .github/copilot-instructions.md | 7 ++++++- src/constraint_handler/engine.py | 2 +- .../{ => propagator}/PropagatorConstants.py | 0 .../propagator/PropagatorUtils.py | 9 +++++++++ .../{ => propagator}/PropagatorVariables.py | 2 +- src/constraint_handler/propagator/__init__.py | 5 +++++ .../{propagator.py => propagator/handler.py} | 15 ++++++++------- .../{ => propagator}/model_builder.py | 4 ++-- .../{ => propagator}/optimization_modes.py | 4 ++-- .../{ => propagator}/reasoning_modes.py | 8 ++++++-- .../{ => propagator}/variable_loader.py | 4 ++-- tests/utils/testing.py | 2 +- 12 files changed, 43 insertions(+), 19 deletions(-) rename src/constraint_handler/{ => propagator}/PropagatorConstants.py (100%) create mode 100644 src/constraint_handler/propagator/PropagatorUtils.py rename src/constraint_handler/{ => propagator}/PropagatorVariables.py (99%) create mode 100644 src/constraint_handler/propagator/__init__.py rename src/constraint_handler/{propagator.py => propagator/handler.py} (98%) rename src/constraint_handler/{ => propagator}/model_builder.py (97%) rename src/constraint_handler/{ => propagator}/optimization_modes.py (98%) rename src/constraint_handler/{ => propagator}/reasoning_modes.py (98%) rename src/constraint_handler/{ => propagator}/variable_loader.py (99%) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c271e2870..b44be30e0 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -129,7 +129,12 @@ src/ │ │ ├── set.lp, multimap.lp # Data structures │ │ ├── execution.lp, conditionals.lp # Control flow │ │ └── propagator.lp, pythonHelper.lp # Solver integration -│ ├── propagator.py # Constraint handler propagator +│ ├── propagator/ # Constraint handler propagator subsystem +│ │ ├── handler.py # Main propagator implementation +│ │ ├── model_builder.py +│ │ ├── optimization_modes.py +│ │ ├── reasoning_modes.py +│ │ ├── variable_loader.py │ ├── evaluator.py # Expression evaluator │ ├── schemas/ # Data schemas (Clorm-based) │ └── utils/ # Utility modules diff --git a/src/constraint_handler/engine.py b/src/constraint_handler/engine.py index 8cbaed86d..ec14f34a7 100644 --- a/src/constraint_handler/engine.py +++ b/src/constraint_handler/engine.py @@ -1,6 +1,6 @@ from dataclasses import dataclass, field -from constraint_handler.PropagatorConstants import PROPAGATOR_CHECK_MODE_STR +from constraint_handler.propagator.PropagatorConstants import PROPAGATOR_CHECK_MODE_STR @dataclass(frozen=True) diff --git a/src/constraint_handler/PropagatorConstants.py b/src/constraint_handler/propagator/PropagatorConstants.py similarity index 100% rename from src/constraint_handler/PropagatorConstants.py rename to src/constraint_handler/propagator/PropagatorConstants.py diff --git a/src/constraint_handler/propagator/PropagatorUtils.py b/src/constraint_handler/propagator/PropagatorUtils.py new file mode 100644 index 000000000..6e64bdb7f --- /dev/null +++ b/src/constraint_handler/propagator/PropagatorUtils.py @@ -0,0 +1,9 @@ +from clingo.ast import Transformer + + +class ASTInspect(Transformer): + optimality_atom_found = False + + def visit_SymbolicAtom(self, node): + print(node) + return node diff --git a/src/constraint_handler/PropagatorVariables.py b/src/constraint_handler/propagator/PropagatorVariables.py similarity index 99% rename from src/constraint_handler/PropagatorVariables.py rename to src/constraint_handler/propagator/PropagatorVariables.py index 45d43ee20..eebf0a411 100644 --- a/src/constraint_handler/PropagatorVariables.py +++ b/src/constraint_handler/propagator/PropagatorVariables.py @@ -9,7 +9,7 @@ import clingo from constraint_handler import evaluator, multimap, myClorm -from constraint_handler.PropagatorConstants import ( +from constraint_handler.propagator.PropagatorConstants import ( DEFAULT_DECISION_LEVEL, EvaluationResult, ValueStatus, diff --git a/src/constraint_handler/propagator/__init__.py b/src/constraint_handler/propagator/__init__.py new file mode 100644 index 000000000..52fed2ce7 --- /dev/null +++ b/src/constraint_handler/propagator/__init__.py @@ -0,0 +1,5 @@ +"""Propagator implementation and supporting modules.""" + +from .handler import ConstraintHandlerPropagator + +__all__ = ["ConstraintHandlerPropagator"] diff --git a/src/constraint_handler/propagator.py b/src/constraint_handler/propagator/handler.py similarity index 98% rename from src/constraint_handler/propagator.py rename to src/constraint_handler/propagator/handler.py index 4a2ad5ccc..574f21581 100644 --- a/src/constraint_handler/propagator.py +++ b/src/constraint_handler/propagator/handler.py @@ -3,17 +3,18 @@ import clingo import constraint_handler.schemas.propagator_atom as prop_atom -from constraint_handler import evaluator, myClorm, variable_loader -from constraint_handler.model_builder import ModelBuilder -from constraint_handler.optimization_modes import OptimizationModeHandler -from constraint_handler.PropagatorConstants import ( +from constraint_handler import evaluator, myClorm +from constraint_handler.propagator import variable_loader +from constraint_handler.propagator.model_builder import ModelBuilder +from constraint_handler.propagator.optimization_modes import OptimizationModeHandler +from constraint_handler.propagator.PropagatorConstants import ( OTHER_ENGINE_VAR_NAME, PROPAGATOR_CHECK_MODE_ATOM, EvaluationResult, ValueStatus, propagator_warning_t, ) -from constraint_handler.PropagatorVariables import ( +from constraint_handler.propagator.PropagatorVariables import ( EvaluateVariable, Evaluations, OptimizationHandler, @@ -23,7 +24,7 @@ VariableValue, is_evaluation_possible, ) -from constraint_handler.reasoning_modes import ReasoningModeHandler +from constraint_handler.propagator.reasoning_modes import ReasoningModeHandler from constraint_handler.schemas import expression, internal, result, warning @@ -32,7 +33,7 @@ class ConstraintHandlerPropagator(clingo.Propagator): Propagator that evaluates constraint_handler variables during solving. The propagator maintains a mapping from clingo symbols and solver literals to - variable objects (see `constraint_handler.PropagatorVariables`). During + variable objects (see `constraint_handler.propagator.PropagatorVariables`). During propagation/check it evaluates affected variables, checks ensure constraints, and can add nogoods for conflicts or for pruning based on optimization or reasoning mode(brave/cautious). diff --git a/src/constraint_handler/model_builder.py b/src/constraint_handler/propagator/model_builder.py similarity index 97% rename from src/constraint_handler/model_builder.py rename to src/constraint_handler/propagator/model_builder.py index 25f51887e..fc64dc382 100644 --- a/src/constraint_handler/model_builder.py +++ b/src/constraint_handler/propagator/model_builder.py @@ -6,8 +6,8 @@ import clingo from constraint_handler import evaluator, multimap -from constraint_handler.PropagatorConstants import OTHER_ENGINE_VAR_NAME, ValueStatus -from constraint_handler.PropagatorVariables import BoolEvaluateVariable, EvaluateVariable, VariableType +from constraint_handler.propagator.PropagatorConstants import OTHER_ENGINE_VAR_NAME, ValueStatus +from constraint_handler.propagator.PropagatorVariables import BoolEvaluateVariable, EvaluateVariable, VariableType from constraint_handler.schemas import expression, result, warning diff --git a/src/constraint_handler/optimization_modes.py b/src/constraint_handler/propagator/optimization_modes.py similarity index 98% rename from src/constraint_handler/optimization_modes.py rename to src/constraint_handler/propagator/optimization_modes.py index 7680257f4..8473cacce 100644 --- a/src/constraint_handler/optimization_modes.py +++ b/src/constraint_handler/propagator/optimization_modes.py @@ -7,13 +7,13 @@ import constraint_handler.schemas.propagator_atom as prop_atom from constraint_handler import myClorm -from constraint_handler.PropagatorConstants import ( +from constraint_handler.propagator.PropagatorConstants import ( OPTIMIZATION_HELPER_PROGRAM, OPTIMIZATION_STAGE_ATOM, OptimizationStrength, propagator_warning_t, ) -from constraint_handler.PropagatorVariables import OptimizationHandler, VariableValue +from constraint_handler.propagator.PropagatorVariables import OptimizationHandler, VariableValue from constraint_handler.schemas import expression, warning diff --git a/src/constraint_handler/reasoning_modes.py b/src/constraint_handler/propagator/reasoning_modes.py similarity index 98% rename from src/constraint_handler/reasoning_modes.py rename to src/constraint_handler/propagator/reasoning_modes.py index b756ceb41..027dd99b5 100644 --- a/src/constraint_handler/reasoning_modes.py +++ b/src/constraint_handler/propagator/reasoning_modes.py @@ -6,8 +6,12 @@ import clingo from clingo import Symbol -from constraint_handler.PropagatorConstants import REASONING_MODE_PROGRAM, REASONING_STAGE_ATOM, ReasoningMode -from constraint_handler.PropagatorVariables import BoolEvaluateVariable, VariableType +from constraint_handler.propagator.PropagatorConstants import ( + REASONING_MODE_PROGRAM, + REASONING_STAGE_ATOM, + ReasoningMode, +) +from constraint_handler.propagator.PropagatorVariables import BoolEvaluateVariable, VariableType from constraint_handler.schemas import result, warning diff --git a/src/constraint_handler/variable_loader.py b/src/constraint_handler/propagator/variable_loader.py similarity index 99% rename from src/constraint_handler/variable_loader.py rename to src/constraint_handler/propagator/variable_loader.py index 6c8e3c651..4cd5fbeb1 100644 --- a/src/constraint_handler/variable_loader.py +++ b/src/constraint_handler/propagator/variable_loader.py @@ -8,8 +8,8 @@ import constraint_handler.schemas.propagator_atom as prop_atom from constraint_handler import myClorm -from constraint_handler.PropagatorConstants import OTHER_ENGINE_VAR_NAME, propagator_warning_t -from constraint_handler.PropagatorVariables import ( +from constraint_handler.propagator.PropagatorConstants import OTHER_ENGINE_VAR_NAME, propagator_warning_t +from constraint_handler.propagator.PropagatorVariables import ( BoolEvaluateVariable, DictVariable, EvaluateVariable, diff --git a/tests/utils/testing.py b/tests/utils/testing.py index 875c6a61c..574a31f6a 100644 --- a/tests/utils/testing.py +++ b/tests/utils/testing.py @@ -12,7 +12,7 @@ import constraint_handler from constraint_handler.engine import Engine, compile -from constraint_handler.PropagatorConstants import OPTIMIZATION_STAGE_ATOM +from constraint_handler.propagator.PropagatorConstants import OPTIMIZATION_STAGE_ATOM def atoms_from_file(file_name: str) -> list[clingo.Symbol]: From c91c5eb145378ebca21ede25c389b31fad2aaa71 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 8 Nov 2026 05:21:41 +0100 Subject: [PATCH 02/29] First implementation of reasoning modes propagator --- src/constraint_handler/main.py | 10 +- src/constraint_handler/post_processor.py | 16 + .../propagator/PropagatorConstants.py | 2 +- .../propagator/PropagatorUtils.py | 9 - .../propagator/reasoning_modes.py | 8 +- .../reasoning_modes_propagator.py | 303 ++++++++++++++++++ 6 files changed, 332 insertions(+), 16 deletions(-) delete mode 100644 src/constraint_handler/propagator/PropagatorUtils.py create mode 100644 src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py diff --git a/src/constraint_handler/main.py b/src/constraint_handler/main.py index 73b1484fe..60c2f92b0 100644 --- a/src/constraint_handler/main.py +++ b/src/constraint_handler/main.py @@ -17,6 +17,7 @@ import constraint_handler.solver_environment as solver_environment import flat_ch.main as flat_main from constraint_handler.engine import Engine, compile +from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningMode, ReasoningModesPropagator from constraint_handler.schemas.type_ import BaseType module_main = [ @@ -176,6 +177,7 @@ def add_to_control( environment=None, _environment_ids=dict(), engine: Engine = compile, + reasoning_mode: ReasoningMode = ReasoningMode.STANDARD, ): """Adds encoding logic to the provided Control instance. The environment argumennt specifies the locals used in the python statements and expressions.""" if engine.name == "fch": @@ -205,14 +207,17 @@ def add_to_control( _environment_ids[eid] = idx ctrl.add(f"main_solverIdentifier({idx}).") ctrl.add(engine.program()) - setup_propagator(ctrl) + setup_propagator(ctrl, reasoning_mode) -def setup_propagator(ctrl: clingo.Control): +def setup_propagator(ctrl: clingo.Control, reasoning_mode: ReasoningMode): prop = propagator.ConstraintHandlerPropagator() post_prop = post_processor.OptimizePostProcessingPropagator() + reasoning_mode_prop = ReasoningModesPropagator(reasoning_mode) + ctrl.register_propagator(prop) + ctrl.register_propagator(reasoning_mode_prop) ctrl.register_propagator(post_prop) prop.get_configuration(ctrl) original_solve = ctrl.solve @@ -222,6 +227,7 @@ def om(model): if prop.on_model(model) == False: return False post_processor.set_optimize_valuation(post_prop, model) + post_processor.extend_with_reasoning_mode_atoms(reasoning_mode_prop, model) if on_model is not None: return on_model(model) diff --git a/src/constraint_handler/post_processor.py b/src/constraint_handler/post_processor.py index 3461e1ecf..b42f513d6 100644 --- a/src/constraint_handler/post_processor.py +++ b/src/constraint_handler/post_processor.py @@ -4,11 +4,14 @@ from typing import Mapping import clingo +from mypy.server.update import propagate_changes_using_dependencies import constraint_handler.evaluator as evaluator import constraint_handler.myClorm as myClorm import constraint_handler.schemas.result as result import constraint_handler.schemas.warning as warning +from constraint_handler.propagator.model_builder import ModelBuilder +from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningModesPropagator class OptimizePostProcessingPropagator(clingo.Propagator): @@ -137,3 +140,16 @@ def set_optimize_valuation(propagator: OptimizePostProcessingPropagator, model) if model.optimality_proven: propagator._cached_optimize_value_symbols = optimize_value_symbols.copy() + + +def extend_with_reasoning_mode_atoms(propagator: ReasoningModesPropagator, model) -> None: + model_builder = ModelBuilder({}) + symbols = set() + for variable, values in propagator.reasoning_strategy.model.items(): + for value in values: + model_builder.add_value(variable, value) + + for atom in model_builder.atoms: + symbol = myClorm.pytocl(atom) + symbols.add(clingo.Function(f"{symbol.name}_rm", symbol.arguments)) + model.extend(symbols) diff --git a/src/constraint_handler/propagator/PropagatorConstants.py b/src/constraint_handler/propagator/PropagatorConstants.py index c44f39692..0c2bd32c2 100644 --- a/src/constraint_handler/propagator/PropagatorConstants.py +++ b/src/constraint_handler/propagator/PropagatorConstants.py @@ -30,7 +30,7 @@ class EvaluationResult(enum.Enum): INFER = "__infer__" -class ReasoningMode(enum.Enum): +class PropagatorReasoningMode(enum.Enum): STANDARD = "standard" BRAVE = "brave" CAUTIOUS = "cautious" diff --git a/src/constraint_handler/propagator/PropagatorUtils.py b/src/constraint_handler/propagator/PropagatorUtils.py deleted file mode 100644 index 6e64bdb7f..000000000 --- a/src/constraint_handler/propagator/PropagatorUtils.py +++ /dev/null @@ -1,9 +0,0 @@ -from clingo.ast import Transformer - - -class ASTInspect(Transformer): - optimality_atom_found = False - - def visit_SymbolicAtom(self, node): - print(node) - return node diff --git a/src/constraint_handler/propagator/reasoning_modes.py b/src/constraint_handler/propagator/reasoning_modes.py index 027dd99b5..1b0215249 100644 --- a/src/constraint_handler/propagator/reasoning_modes.py +++ b/src/constraint_handler/propagator/reasoning_modes.py @@ -9,7 +9,7 @@ from constraint_handler.propagator.PropagatorConstants import ( REASONING_MODE_PROGRAM, REASONING_STAGE_ATOM, - ReasoningMode, + PropagatorReasoningMode, ) from constraint_handler.propagator.PropagatorVariables import BoolEvaluateVariable, VariableType from constraint_handler.schemas import result, warning @@ -31,7 +31,7 @@ class _ReasoningStrategy(ABC): accumulated_model: The accumulated model across model processing. """ - mode = ReasoningMode.STANDARD + mode = PropagatorReasoningMode.STANDARD def __init__(self) -> None: self.stage_literals: dict[int, int] = {1: -1, 2: -1} @@ -205,7 +205,7 @@ class StandardReasoningStrategy(_ReasoningStrategy): class BraveReasoningStrategy(_StagedReasoningStrategy): - mode = ReasoningMode.BRAVE + mode = PropagatorReasoningMode.BRAVE def accumulate_model(self, previous_model, current_model): if previous_model is None: @@ -248,7 +248,7 @@ def _variable_result_atoms(variables): class CautiousReasoningStrategy(_StagedReasoningStrategy): - mode = ReasoningMode.CAUTIOUS + mode = PropagatorReasoningMode.CAUTIOUS def accumulate_model(self, previous_model, current_model): if previous_model is None: diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py new file mode 100644 index 000000000..c6a12f5a9 --- /dev/null +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -0,0 +1,303 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections import deque +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field +from enum import Enum +from typing import Any + +import clingo +from click.decorators import R + +from constraint_handler import multimap, myClorm +from constraint_handler.schemas import expression, internal, result + + +class ReasoningMode(Enum): + STANDARD = 1 + BRAVE = 2 + CAUTIOUS = 3 + INTERSECTION = 4 + UNION = 5 + SUPREMUM = 6 + INFIMUM = 7 + + +@dataclass +class _Candidate: + literal: int + value: Any + + +@dataclass +class _PairCandidate: + literal: int + key: Any + value: Any + + +@dataclass +class _ScalarVariable: + name: clingo.Symbol + candidates: list[_Candidate] = field(default_factory=list) + value: Any = None + has_value: bool = False + + def update(self, assignment: clingo.Assignment) -> None: + for candidate in self.candidates: + if assignment.is_true(candidate.literal): + self.value = candidate.value + self.has_value = True + return + self.has_value = False + + +@dataclass +class _SetVariable: + name: clingo.Symbol + source: expression.Expr + candidates: list[_Candidate] = field(default_factory=list) + value: frozenset[Any] = frozenset() + + def update(self, assignment: clingo.Assignment) -> None: + self.value = frozenset( + candidate.value for candidate in self.candidates if assignment.is_true(candidate.literal) + ) + + +@dataclass +class _MultimapVariable: + name: clingo.Symbol + candidates: list[_PairCandidate] = field(default_factory=list) + value: multimap.Multimap[Any, Any] = field(default_factory=lambda: multimap.Multimap.from_pairs([])) + + def update(self, assignment: clingo.Assignment) -> None: + self.value = multimap.Multimap.from_pairs( + (candidate.key, candidate.value) for candidate in self.candidates if assignment.is_true(candidate.literal) + ) + + +def _python_value(value: Any) -> Any: + if isinstance(value, (expression.Val, expression.Ref)): + return value.value + return value + + +def _variable_symbol(variable: expression.Variable) -> clingo.Symbol: + return myClorm.pytocl(variable).arguments[0] + + +class ReasoningStrategy(ABC): + """Base class for reasoning modes.""" + + def __init__(self) -> None: + super().__init__() + self.model: dict[clingo.Symbol, set[Any]] = {} + + @abstractmethod + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Update the reasoning mode based on the join with the given model.""" + raise NotImplementedError() + + def nogoods(self) -> list[Iterable[int]]: + """Return the nogoods associated with the current reasoning mode.""" + return [] + + +class StandardReasoningMode(ReasoningStrategy): + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Update the reasoning mode based on the standard join with the given model.""" + return + + +class IntersectionReasoningMode(ReasoningStrategy): + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Update the reasoning mode based on the intersection with the given model.""" + # intersect the current model with the given model + for key, value in model.items(): + if key in self.model: + self.model[key] &= {value} + else: + self.model[key] = {value} + + +class UnionReasoningMode(ReasoningStrategy): + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Update the reasoning mode based on the union with the given model.""" + for key, value in model.items(): + if key in self.model: + self.model[key] |= {value} + else: + self.model[key] = {value} + + +class SupremumReasoningMode(ReasoningStrategy): + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Update the reasoning mode based on the supremum with the given model.""" + for key, value in model.items(): + if key not in self.model: + self.model[key] = {value} + continue + current = next(iter(self.model[key])) + self.model[key] = {self._supremum(current, value)} + + @staticmethod + def _supremum(left: Any, right: Any) -> Any: + if isinstance(left, frozenset) and isinstance(right, frozenset): + return left.union(right) + if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): + return multimap.Multimap.from_pairs( + (key, value) for source in (left, right) for key, values in source.items() for value in values + ) + return max(left, right) + + +class InfimumReasoningMode(ReasoningStrategy): + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Update the reasoning mode based on the infimum with the given model.""" + for key, value in model.items(): + if key not in self.model: + self.model[key] = {value} + continue + current = next(iter(self.model[key])) + self.model[key] = {self._infimum(current, value)} + + @staticmethod + def _infimum(left: Any, right: Any) -> Any: + if isinstance(left, frozenset) and isinstance(right, frozenset): + return left.intersection(right) + if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): + return multimap.Multimap.from_pairs( + (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) + ) + return min(left, right) + + +def _supremum(left: Any, right: Any) -> Any: + if isinstance(left, frozenset) and isinstance(right, frozenset): + return left.union(right) + if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): + return multimap.Multimap.from_pairs( + (key, value) for source in (left, right) for key, values in source.items() for value in values + ) + return max(left, right) + + +def _infimum(left: Any, right: Any) -> Any: + if isinstance(left, frozenset) and isinstance(right, frozenset): + return left.intersection(right) + if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): + return multimap.Multimap.from_pairs( + (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) + ) + return min(left, right) + + +REASONING_STRATEGIES = { + ReasoningMode.STANDARD: StandardReasoningMode(), + ReasoningMode.INTERSECTION: IntersectionReasoningMode(), + ReasoningMode.UNION: UnionReasoningMode(), + ReasoningMode.SUPREMUM: SupremumReasoningMode(), + ReasoningMode.INFIMUM: InfimumReasoningMode(), +} + + +class ReasoningModesPropagator(clingo.Propagator): + """Build complete variable models and apply nogoods from a reasoning mode.""" + + def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> None: + self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode] + self._variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = {} + self._watched_literals: set[int] = set() + self._nogood_queue: deque[Iterable[int]] = deque() + + self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) + + def set_mode(self, reasoning_mode: ReasoningMode) -> None: + self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode] + self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) + + def init(self, init: clingo.PropagateInit) -> None: + """Load current-solver variable values and register their literals.""" + if self.disabled: + return + self._variables.clear() + self._watched_literals.clear() + self._nogood_queue.clear() + init.check_mode = clingo.PropagatorCheckMode.Total + + se_values = myClorm.findInPropagateInit(init, internal._se_value) + set_values = myClorm.findInPropagateInit(init, internal._set_contains) + multimap_values = myClorm.findInPropagateInit(init, result.Multimap_value) + + for (expr, value), literal in se_values.items(): + if not isinstance(expr, expression.Variable): + continue + name = _variable_symbol(expr) + if isinstance(value, internal.Ref) and str(value.type_) == "set": + self._variables.setdefault(name, _SetVariable(name, value.expr)) + elif isinstance(value, internal.Ref) and str(value.type_) == "multimap": + self._variables.setdefault(name, _MultimapVariable(name)) + else: + scalar = self._variables.setdefault(name, _ScalarVariable(name)) + if isinstance(scalar, _ScalarVariable): + scalar.candidates.append(_Candidate(literal, _python_value(value))) + + for (expr, value), literal in set_values.items(): + for variable in self._variables.values(): + if isinstance(variable, _SetVariable) and variable.source == expr: + variable.candidates.append(_Candidate(literal, _python_value(value))) + self._watched_literals.add(literal) + + for (name, key, value), literal in multimap_values.items(): + variable_name = myClorm.pytocl(expression.Variable(name)).arguments[0] + variable = self._variables.get(variable_name) + if isinstance(variable, _MultimapVariable): + variable.candidates.append(_PairCandidate(literal, _python_value(key), _python_value(value))) + self._watched_literals.add(literal) + + for variable in self._variables.values(): + if isinstance(variable, _ScalarVariable): + self._watched_literals.update(candidate.literal for candidate in variable.candidates) + for literal in self._watched_literals: + init.add_watch(literal) + + def propagate(self, control: clingo.PropagateControl, changes: Sequence[int]) -> None: + """Drain queued nogoods without updating variable values.""" + if self.disabled: + return + self._add_nogoods(control) + + def check(self, control: clingo.PropagateControl) -> None: + """Build a total model, join it into the mode, and add its nogoods.""" + if self.disabled: + return + if self._add_nogoods(control): + return + if not control.assignment.is_total: + return + + for variable in self._variables.values(): + variable.update(control.assignment) + model = {variable.name: variable.value for variable in self._variables.values() if _has_value(variable)} + self.reasoning_strategy.join(model) + self._nogood_queue.extend(self.reasoning_strategy.nogoods()) + self._add_nogoods(control) + + # print values stored + import pprint + + print("Stored values:") + pprint.pprint(self.reasoning_strategy.model) + + def _add_nogoods(self, control: clingo.PropagateControl) -> bool: + while self._nogood_queue: + nogood = self._nogood_queue.popleft() + if not control.add_nogood(nogood, lock=True): + return True + return False + + +def _has_value(variable: _ScalarVariable | _SetVariable | _MultimapVariable) -> bool: + return not isinstance(variable, _ScalarVariable) or variable.has_value From cb122723ce13cf4684ccd8322437d7babad2365b Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Mon, 9 Nov 2026 18:04:38 +0100 Subject: [PATCH 03/29] Implement nogoods for Intersection and Union modes --- src/constraint_handler/post_processor.py | 2 +- .../reasoning_modes_propagator.py | 550 +++++++++++++++--- 2 files changed, 474 insertions(+), 78 deletions(-) diff --git a/src/constraint_handler/post_processor.py b/src/constraint_handler/post_processor.py index b42f513d6..16cbb3624 100644 --- a/src/constraint_handler/post_processor.py +++ b/src/constraint_handler/post_processor.py @@ -145,7 +145,7 @@ def set_optimize_valuation(propagator: OptimizePostProcessingPropagator, model) def extend_with_reasoning_mode_atoms(propagator: ReasoningModesPropagator, model) -> None: model_builder = ModelBuilder({}) symbols = set() - for variable, values in propagator.reasoning_strategy.model.items(): + for variable, values in propagator.reasoning_strategy.rm_model.items(): for value in values: model_builder.add_value(variable, value) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index c6a12f5a9..ba1a5aa45 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -8,13 +8,18 @@ from typing import Any import clingo -from click.decorators import R from constraint_handler import multimap, myClorm from constraint_handler.schemas import expression, internal, result class ReasoningMode(Enum): + """Available strategies for combining values across solver models. + + STANDARD leaves model enumeration unchanged. The other modes accumulate, + intersect, or combine variable values according to their strategy. + """ + STANDARD = 1 BRAVE = 2 CAUTIOUS = 3 @@ -25,13 +30,28 @@ class ReasoningMode(Enum): @dataclass -class _Candidate: +class _Value: + """Associate a solver literal with a possible variable value. + + Attributes: + literal: Solver literal that is true when the value is selected. + value: Python representation of the possible value. + """ + literal: int value: Any @dataclass -class _PairCandidate: +class _PairValue: + """Associate a solver literal with a possible multimap pair. + + Attributes: + literal: Solver literal that is true when the pair is present. + key: Key in the multimap. + value: Value associated with the key. + """ + literal: int key: Any value: Any @@ -39,13 +59,27 @@ class _PairCandidate: @dataclass class _ScalarVariable: + """Track possible and currently selected values for a scalar variable. + + Attributes: + name: Clingo symbol identifying the variable. + possible_values: Values that can be selected by this variable. + value: Selected value from the latest assignment, if any. + has_value: Whether the latest assignment selected a value. + """ + name: clingo.Symbol - candidates: list[_Candidate] = field(default_factory=list) + possible_values: list[_Value] = field(default_factory=list) value: Any = None has_value: bool = False def update(self, assignment: clingo.Assignment) -> None: - for candidate in self.candidates: + """Update the selected value from a solver assignment. + + Args: + assignment: Current solver assignment used to inspect literals. + """ + for candidate in self.possible_values: if assignment.is_true(candidate.literal): self.value = candidate.value self.has_value = True @@ -55,159 +89,484 @@ def update(self, assignment: clingo.Assignment) -> None: @dataclass class _SetVariable: + """Track the possible members and current value of a set variable. + + Attributes: + name: Clingo symbol identifying the variable. + source: Expression whose member literals represent this set. + possible_values: Members that can be present in the set. + value: Set of members present in the latest assignment. + """ + name: clingo.Symbol source: expression.Expr - candidates: list[_Candidate] = field(default_factory=list) + possible_values: list[_Value] = field(default_factory=list) value: frozenset[Any] = frozenset() def update(self, assignment: clingo.Assignment) -> None: + """Rebuild the set value from true member literals. + + Args: + assignment: Current solver assignment used to inspect literals. + """ self.value = frozenset( - candidate.value for candidate in self.candidates if assignment.is_true(candidate.literal) + candidate.value for candidate in self.possible_values if assignment.is_true(candidate.literal) ) @dataclass class _MultimapVariable: + """Track the possible pairs and current value of a multimap variable. + + Attributes: + name: Clingo symbol identifying the variable. + possible_values: Key/value pairs that can be present in the multimap. + value: Multimap containing the pairs present in the latest assignment. + """ + name: clingo.Symbol - candidates: list[_PairCandidate] = field(default_factory=list) + possible_values: list[_PairValue] = field(default_factory=list) value: multimap.Multimap[Any, Any] = field(default_factory=lambda: multimap.Multimap.from_pairs([])) def update(self, assignment: clingo.Assignment) -> None: + """Rebuild the multimap value from true pair literals. + + Args: + assignment: Current solver assignment used to inspect literals. + """ self.value = multimap.Multimap.from_pairs( - (candidate.key, candidate.value) for candidate in self.candidates if assignment.is_true(candidate.literal) + (candidate.key, candidate.value) + for candidate in self.possible_values + if assignment.is_true(candidate.literal) ) def _python_value(value: Any) -> Any: + """Unwrap an expression value or reference into its Python value. + + Args: + value: Expression value, reference, or already-converted value. + + Returns: + The underlying Python value for expression values and references; + otherwise, the input unchanged. + """ if isinstance(value, (expression.Val, expression.Ref)): return value.value return value -def _variable_symbol(variable: expression.Variable) -> clingo.Symbol: +def _variable_to_symbol(variable: expression.Variable) -> clingo.Symbol: + """Convert an expression variable to its Clingo symbol. + + Args: + variable: Expression variable to convert. + + Returns: + The Clingo symbol identifying the variable. + """ return myClorm.pytocl(variable).arguments[0] class ReasoningStrategy(ABC): - """Base class for reasoning modes.""" + """Base class for strategies that combine values across solver models. + + Attributes: + rm_model: Accumulated values keyed by Clingo variable symbol. + """ def __init__(self) -> None: + """Initialize an empty accumulated model.""" super().__init__() - self.model: dict[clingo.Symbol, set[Any]] = {} + self.rm_model: dict[clingo.Symbol, set[Any]] = {} + + def init( + self, + init: clingo.PropagateInit, + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], + ) -> None: + """Reset strategy state before a solve begins. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked scalar, set, and multimap variables. + """ + self.rm_model.clear() @abstractmethod def join(self, model: dict[clingo.Symbol, object]) -> None: - """Update the reasoning mode based on the join with the given model.""" + """Combine a complete model with the strategy's accumulated state. + + Args: + model: Variable values from the current solver model. + """ raise NotImplementedError() def nogoods(self) -> list[Iterable[int]]: - """Return the nogoods associated with the current reasoning mode.""" + """Return constraints that guide enumeration for this strategy. + + Returns: + Nogoods to add to the solver; the base strategy adds none. + """ return [] class StandardReasoningMode(ReasoningStrategy): + """Use ordinary model enumeration without accumulating constraints.""" + def join(self, model: dict[clingo.Symbol, object]) -> None: - """Update the reasoning mode based on the standard join with the given model.""" + """Leave the strategy state unchanged for a model. + + Args: + model: Variable values from the current solver model. + """ return -class IntersectionReasoningMode(ReasoningStrategy): +class _LiteralReasoningMode(ReasoningStrategy): + """Share witness and value literals used to prune repeated model values.""" + + def __init__(self) -> None: + """Initialize maps for witness and semantic value literals.""" + super().__init__() + self.variable_lit: dict[clingo.Symbol, int] = {} + self.set_or_multimap_value_literals: dict[clingo.Symbol, dict[Any, int]] = {} + self.scalar_literals: dict[clingo.Symbol, dict[Any, set[int]]] = {} + + def init( + self, + init: clingo.PropagateInit, + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], + ) -> None: + """Create witnesses and group literals representing equal values. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked variables and their possible values. + """ + super().init(init, variables) + self.variable_lit.clear() + self.set_or_multimap_value_literals.clear() + self.scalar_literals.clear() + + for name, variable in variables.items(): + self.variable_lit[name] = init.add_literal(freeze=True) + # Different source atoms may encode the same member or key/value pair. + value2lits: dict[Any, set[int]] = {} + for candidate in variable.possible_values: + if isinstance(candidate, _PairValue): + value = (candidate.key, candidate.value) + else: + value = candidate.value + value2lits.setdefault(value, set()).add(candidate.literal) + + # for scalars we don't need prescence literals since only 1 if true at a time. + if isinstance(variable, _ScalarVariable): + self.scalar_literals[name] = value2lits + continue + + self.set_or_multimap_value_literals[name] = {} + for value, literals in value2lits.items(): + # With one source literal, that literal already means this value is present. + if len(literals) == 1: + self.set_or_multimap_value_literals[name][value] = next(iter(literals)) + continue + # Encode presence as the OR of all literals representing this value. + presence = init.add_literal(freeze=True) + self.set_or_multimap_value_literals[name][value] = presence + init.add_clause([-presence, *literals]) + for literal in literals: + init.add_clause([-literal, presence]) + + def _set_or_multimap_value_nogood(self, name: clingo.Symbol, value: Any, helper: int) -> tuple[int, ...]: + """Build a nogood that disables a witness for an unchanged collection. + + The returned literals describe the complete set or multimap value, + followed by the helper literal. + + Args: + name: Symbol identifying the set or multimap variable. + value: Complete set or multimap value to match. + helper: Literal representing this variable's progress witness. + + Returns: + A nogood matching the complete value and helper literal. + """ + if isinstance(value, multimap.Multimap): + retained = set() + # build the key, value pairs for the multimap + for key, items in value.items(): + for item in items: + retained.add((key, item)) + else: + retained = value + + # Exact-value matching is identical for union and intersection, so no union flag is needed. + # Their callers choose which accumulated values to block from witnessing progress. + equality = [] + for item, literal in self.set_or_multimap_value_literals[name].items(): + # Match both present and absent members so this represents the whole value. + if item in retained: + equality.append(literal) + else: + equality.append(-literal) + equality.append(helper) + return tuple(equality) + + def _set_or_multimap_member_nogood( + self, name: clingo.Symbol, value: Any, helper: int, *, union: bool = False + ) -> tuple[int, ...]: + """Build a progress nogood from collection members rather than whole values. + + Args: + name: Symbol identifying the set or multimap variable. + value: Collection containing retained or already-seen members. + helper: Literal representing this variable's progress witness. + union: Match absent unseen members instead of present retained members. + + Returns: + Member literals followed by the helper literal. + """ + if isinstance(value, multimap.Multimap): + members = {(key, item) for key, items in value.items() for item in items} + else: + members = value + + literals = self.set_or_multimap_value_literals[name] + # Memberwise progress is directional, so the union flag selects which condition to match. + if union: + # Union needs an unseen member to appear; match all unseen members being absent. + nogood = [-literal for item, literal in literals.items() if item not in members] + else: + # Intersection needs a retained member to disappear; match all retained members being present. + nogood = [literals[item] for item in members] + return (*nogood, helper) + + +class IntersectionReasoningMode(_LiteralReasoningMode): + """Retain complete variable values that agree across all models.""" + + def __init__(self) -> None: + """Initialize intersection state for a new solve.""" + super().__init__() + self._initialized = False + + def init( + self, + init: clingo.PropagateInit, + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], + ) -> None: + """Reset the accumulated intersection and initialize its literals. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked variables and their possible values. + """ + super().init(init, variables) + self._initialized = False + def join(self, model: dict[clingo.Symbol, object]) -> None: - """Update the reasoning mode based on the intersection with the given model.""" - # intersect the current model with the given model - for key, value in model.items(): - if key in self.model: - self.model[key] &= {value} + """Intersect accumulated variable values with a solver model. + + Args: + model: Variable values from the current solver model. + """ + if not self._initialized: + self.rm_model = {key: {value} for key, value in model.items()} + self._initialized = True + return + for key, values in tuple(self.rm_model.items()): + if key not in model: + del self.rm_model[key] else: - self.model[key] = {value} + values.intersection_update({model[key]}) + if not values: + del self.rm_model[key] + def nogoods(self) -> list[Iterable[int]]: + """Require progress beyond the retained complete variable values. + + Returns: + Nogoods that allow another model only when a retained value changes. + """ + nogoods: list[Iterable[int]] = [] + witnesses = [] + for name, helper in self.variable_lit.items(): + rm_values = self.rm_model.get(name, set()) + if not rm_values: + # An empty intersection cannot witness another change. + nogoods.append((helper,)) + continue + # we do this because for intersection there is always just one value in values_in_rm_model + value = next(iter(rm_values)) + if name in self.scalar_literals: + for literal in self.scalar_literals[name][value]: + # if the literal corresponds to the retained value then the helper is false + # and thus the witness nogood can still fire + nogoods.append((literal, helper)) + else: + nogoods.append(self._set_or_multimap_value_nogood(name, value, helper)) + witnesses.append(-helper) + # A nogood of negated helpers requires at least one active helper to be true. + nogoods.append(tuple(witnesses)) + return nogoods + + +class UnionReasoningMode(_LiteralReasoningMode): + """Accumulate distinct complete variable values and search for unseen values.""" + + def init( + self, + init: clingo.PropagateInit, + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], + ) -> None: + """Initialize literals and add witness and scalar selection guards once. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked variables and their possible values. + """ + super().init(init, variables) + init.add_clause(list(self.variable_lit.values())) + for name, value2lit in self.scalar_literals.items(): + literals = set() + for alternatives in value2lit.values(): + literals.update(alternatives) + init.add_clause([*literals, -self.variable_lit[name]]) -class UnionReasoningMode(ReasoningStrategy): def join(self, model: dict[clingo.Symbol, object]) -> None: - """Update the reasoning mode based on the union with the given model.""" + """Add each model value to the accumulated set of values. + + Args: + model: Variable values from the current solver model. + """ for key, value in model.items(): - if key in self.model: - self.model[key] |= {value} + if key in self.rm_model: + self.rm_model[key].add(value) + else: + self.rm_model[key] = {value} + + def nogoods(self) -> list[Iterable[int]]: + """Require progress from at least one variable's unseen value. + + Returns: + Nogoods that prevent already-seen values from witnessing progress. + """ + nogoods: list[Iterable[int]] = [] + for name, helper in self.variable_lit.items(): + rm_values = self.rm_model.get(name, set()) + if name in self.scalar_literals: + value2lit = self.scalar_literals[name] + for value in rm_values: + for literal in value2lit[value]: + nogoods.append((literal, helper)) else: - self.model[key] = {value} + nogoods.extend([self._set_or_multimap_value_nogood(name, value, helper) for value in rm_values]) + return nogoods class SupremumReasoningMode(ReasoningStrategy): + """Accumulate the supremum of each variable across solver models.""" + def join(self, model: dict[clingo.Symbol, object]) -> None: - """Update the reasoning mode based on the supremum with the given model.""" + """Accumulate the least upper bound of a model's variable values. + + Args: + model: Variable values from the current solver model. + """ for key, value in model.items(): - if key not in self.model: - self.model[key] = {value} + if key not in self.rm_model: + self.rm_model[key] = {value} continue - current = next(iter(self.model[key])) - self.model[key] = {self._supremum(current, value)} + current = next(iter(self.rm_model[key])) + self.rm_model[key] = {self._supremum(current, value)} @staticmethod def _supremum(left: Any, right: Any) -> Any: + """Compute the least upper bound of two values. + + Args: + left: First scalar or collection value. + right: Second scalar or collection value. + + Returns: + Their union for collections or their maximum for scalars. + """ if isinstance(left, frozenset) and isinstance(right, frozenset): return left.union(right) if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): return multimap.Multimap.from_pairs( (key, value) for source in (left, right) for key, values in source.items() for value in values ) + # if left or right are not a number return "TOP" + if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): + return "TOP" return max(left, right) class InfimumReasoningMode(ReasoningStrategy): + """Accumulate the infimum of each variable across solver models.""" + def join(self, model: dict[clingo.Symbol, object]) -> None: - """Update the reasoning mode based on the infimum with the given model.""" + """Accumulate the greatest lower bound of a model's variable values. + + Args: + model: Variable values from the current solver model. + """ for key, value in model.items(): - if key not in self.model: - self.model[key] = {value} + if key not in self.rm_model: + self.rm_model[key] = {value} continue - current = next(iter(self.model[key])) - self.model[key] = {self._infimum(current, value)} + current = next(iter(self.rm_model[key])) + self.rm_model[key] = {self._infimum(current, value)} @staticmethod def _infimum(left: Any, right: Any) -> Any: + """Compute the greatest lower bound of two values. + + Args: + left: First scalar or collection value. + right: Second scalar or collection value. + + Returns: + Their intersection for collections or their minimum for scalars. + """ if isinstance(left, frozenset) and isinstance(right, frozenset): return left.intersection(right) if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): return multimap.Multimap.from_pairs( (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) ) + # if left or right are not a number return "BOT" + if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): + return "BOT" return min(left, right) -def _supremum(left: Any, right: Any) -> Any: - if isinstance(left, frozenset) and isinstance(right, frozenset): - return left.union(right) - if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): - return multimap.Multimap.from_pairs( - (key, value) for source in (left, right) for key, values in source.items() for value in values - ) - return max(left, right) - - -def _infimum(left: Any, right: Any) -> Any: - if isinstance(left, frozenset) and isinstance(right, frozenset): - return left.intersection(right) - if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): - return multimap.Multimap.from_pairs( - (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) - ) - return min(left, right) - - REASONING_STRATEGIES = { - ReasoningMode.STANDARD: StandardReasoningMode(), - ReasoningMode.INTERSECTION: IntersectionReasoningMode(), - ReasoningMode.UNION: UnionReasoningMode(), - ReasoningMode.SUPREMUM: SupremumReasoningMode(), - ReasoningMode.INFIMUM: InfimumReasoningMode(), + ReasoningMode.STANDARD: StandardReasoningMode, + ReasoningMode.INTERSECTION: IntersectionReasoningMode, + ReasoningMode.UNION: UnionReasoningMode, + ReasoningMode.SUPREMUM: SupremumReasoningMode, + ReasoningMode.INFIMUM: InfimumReasoningMode, } class ReasoningModesPropagator(clingo.Propagator): - """Build complete variable models and apply nogoods from a reasoning mode.""" + """Build variable models and apply nogoods for a reasoning strategy. + + Attributes: + reasoning_strategy: Strategy used to combine successive models. + disabled: Whether standard enumeration makes propagation unnecessary. + """ def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> None: - self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode] + """Create a propagator using the selected reasoning mode. + + Args: + reasoning_mode: Strategy to use during model enumeration. + """ + self.reasoning_strategy: ReasoningStrategy = REASONING_STRATEGIES[reasoning_mode]() self._variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = {} self._watched_literals: set[int] = set() self._nogood_queue: deque[Iterable[int]] = deque() @@ -215,11 +574,20 @@ def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> No self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) def set_mode(self, reasoning_mode: ReasoningMode) -> None: - self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode] + """Replace the active reasoning strategy. + + Args: + reasoning_mode: Strategy to use during model enumeration. + """ + self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode]() self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) def init(self, init: clingo.PropagateInit) -> None: - """Load current-solver variable values and register their literals.""" + """Load variable values and register watched solver literals. + + Args: + init: Clingo initialization context for the current solve. + """ if self.disabled: return self._variables.clear() @@ -234,7 +602,7 @@ def init(self, init: clingo.PropagateInit) -> None: for (expr, value), literal in se_values.items(): if not isinstance(expr, expression.Variable): continue - name = _variable_symbol(expr) + name = _variable_to_symbol(expr) if isinstance(value, internal.Ref) and str(value.type_) == "set": self._variables.setdefault(name, _SetVariable(name, value.expr)) elif isinstance(value, internal.Ref) and str(value.type_) == "multimap": @@ -242,35 +610,45 @@ def init(self, init: clingo.PropagateInit) -> None: else: scalar = self._variables.setdefault(name, _ScalarVariable(name)) if isinstance(scalar, _ScalarVariable): - scalar.candidates.append(_Candidate(literal, _python_value(value))) + scalar.possible_values.append(_Value(literal, _python_value(value))) for (expr, value), literal in set_values.items(): for variable in self._variables.values(): if isinstance(variable, _SetVariable) and variable.source == expr: - variable.candidates.append(_Candidate(literal, _python_value(value))) + variable.possible_values.append(_Value(literal, _python_value(value))) self._watched_literals.add(literal) for (name, key, value), literal in multimap_values.items(): variable_name = myClorm.pytocl(expression.Variable(name)).arguments[0] variable = self._variables.get(variable_name) if isinstance(variable, _MultimapVariable): - variable.candidates.append(_PairCandidate(literal, _python_value(key), _python_value(value))) + variable.possible_values.append(_PairValue(literal, _python_value(key), _python_value(value))) self._watched_literals.add(literal) for variable in self._variables.values(): if isinstance(variable, _ScalarVariable): - self._watched_literals.update(candidate.literal for candidate in variable.candidates) + self._watched_literals.update(candidate.literal for candidate in variable.possible_values) for literal in self._watched_literals: init.add_watch(literal) + self.reasoning_strategy.init(init, self._variables) def propagate(self, control: clingo.PropagateControl, changes: Sequence[int]) -> None: - """Drain queued nogoods without updating variable values.""" + """Add queued nogoods without updating tracked variable values. + + Args: + control: Clingo control used to add nogoods. + changes: Watched literals whose assignments changed. + """ if self.disabled: return self._add_nogoods(control) def check(self, control: clingo.PropagateControl) -> None: - """Build a total model, join it into the mode, and add its nogoods.""" + """Process a total assignment and queue constraints for further progress. + + Args: + control: Clingo control containing the current assignment. + """ if self.disabled: return if self._add_nogoods(control): @@ -282,22 +660,40 @@ def check(self, control: clingo.PropagateControl) -> None: variable.update(control.assignment) model = {variable.name: variable.value for variable in self._variables.values() if _has_value(variable)} self.reasoning_strategy.join(model) - self._nogood_queue.extend(self.reasoning_strategy.nogoods()) - self._add_nogoods(control) + # Let this assignment finish before installing nogoods that demand further progress. + self._nogood_queue.extend(tuple(nogood) for nogood in self.reasoning_strategy.nogoods()) # print values stored import pprint print("Stored values:") - pprint.pprint(self.reasoning_strategy.model) + pprint.pprint(self.reasoning_strategy.rm_model) def _add_nogoods(self, control: clingo.PropagateControl) -> bool: + """Add queued nogoods until the queue is empty or propagation stops. + + Args: + control: Clingo control used to add nogoods. + + Returns: + Whether adding a nogood stopped propagation. + """ while self._nogood_queue: nogood = self._nogood_queue.popleft() - if not control.add_nogood(nogood, lock=True): + if not control.add_nogood(nogood, tag=True, lock=True): return True return False def _has_value(variable: _ScalarVariable | _SetVariable | _MultimapVariable) -> bool: + """Report whether a tracked variable has a selected scalar value. + + Collection variables always have a value, including when empty. + + Args: + variable: Tracked scalar, set, or multimap variable. + + Returns: + Whether the variable has a value in the current assignment. + """ return not isinstance(variable, _ScalarVariable) or variable.has_value From 247eb2101d49fc60f51c47c3072d541ac91b53ec Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Tue, 10 Nov 2026 05:35:43 +0100 Subject: [PATCH 04/29] Delete code for prescense literals --- .../reasoning_modes_propagator.py | 170 +++++++----------- 1 file changed, 66 insertions(+), 104 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index ba1a5aa45..dc744673a 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -173,12 +173,18 @@ class ReasoningStrategy(ABC): Attributes: rm_model: Accumulated values keyed by Clingo variable symbol. + variable_lit: Witness literals keyed by Clingo variable symbol. + value_literals: Value literals keyed by variable and value. + scalar_variables: Names of scalar variables. """ def __init__(self) -> None: """Initialize an empty accumulated model.""" super().__init__() self.rm_model: dict[clingo.Symbol, set[Any]] = {} + self.variable_lit: dict[clingo.Symbol, int] = {} + self.value_literals: dict[clingo.Symbol, dict[Any, int]] = {} + self.scalar_variables: set[clingo.Symbol] = set() def init( self, @@ -210,106 +216,39 @@ def nogoods(self) -> list[Iterable[int]]: """ return [] - -class StandardReasoningMode(ReasoningStrategy): - """Use ordinary model enumeration without accumulating constraints.""" - - def join(self, model: dict[clingo.Symbol, object]) -> None: - """Leave the strategy state unchanged for a model. - - Args: - model: Variable values from the current solver model. - """ - return - - -class _LiteralReasoningMode(ReasoningStrategy): - """Share witness and value literals used to prune repeated model values.""" - - def __init__(self) -> None: - """Initialize maps for witness and semantic value literals.""" - super().__init__() - self.variable_lit: dict[clingo.Symbol, int] = {} - self.set_or_multimap_value_literals: dict[clingo.Symbol, dict[Any, int]] = {} - self.scalar_literals: dict[clingo.Symbol, dict[Any, set[int]]] = {} - - def init( + def _init_literals( self, init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Create witnesses and group literals representing equal values. - - Args: - init: Clingo initialization context for the current solve. - variables: Tracked variables and their possible values. - """ - super().init(init, variables) + """Create witnesses and map collection values to their solver literals.""" self.variable_lit.clear() - self.set_or_multimap_value_literals.clear() - self.scalar_literals.clear() + self.value_literals.clear() + self.scalar_variables.clear() for name, variable in variables.items(): self.variable_lit[name] = init.add_literal(freeze=True) - # Different source atoms may encode the same member or key/value pair. - value2lits: dict[Any, set[int]] = {} + self.value_literals[name] = {} + if isinstance(variable, _ScalarVariable): + self.scalar_variables.add(name) + for candidate in variable.possible_values: if isinstance(candidate, _PairValue): value = (candidate.key, candidate.value) else: value = candidate.value - value2lits.setdefault(value, set()).add(candidate.literal) - - # for scalars we don't need prescence literals since only 1 if true at a time. - if isinstance(variable, _ScalarVariable): - self.scalar_literals[name] = value2lits - continue - - self.set_or_multimap_value_literals[name] = {} - for value, literals in value2lits.items(): - # With one source literal, that literal already means this value is present. - if len(literals) == 1: - self.set_or_multimap_value_literals[name][value] = next(iter(literals)) - continue - # Encode presence as the OR of all literals representing this value. - presence = init.add_literal(freeze=True) - self.set_or_multimap_value_literals[name][value] = presence - init.add_clause([-presence, *literals]) - for literal in literals: - init.add_clause([-literal, presence]) + self.value_literals[name][value] = candidate.literal def _set_or_multimap_value_nogood(self, name: clingo.Symbol, value: Any, helper: int) -> tuple[int, ...]: - """Build a nogood that disables a witness for an unchanged collection. - - The returned literals describe the complete set or multimap value, - followed by the helper literal. - - Args: - name: Symbol identifying the set or multimap variable. - value: Complete set or multimap value to match. - helper: Literal representing this variable's progress witness. - - Returns: - A nogood matching the complete value and helper literal. - """ + """Build a nogood that matches a complete collection value and witness.""" if isinstance(value, multimap.Multimap): - retained = set() - # build the key, value pairs for the multimap - for key, items in value.items(): - for item in items: - retained.add((key, item)) + retained = {(key, item) for key, items in value.items() for item in items} else: retained = value - # Exact-value matching is identical for union and intersection, so no union flag is needed. - # Their callers choose which accumulated values to block from witnessing progress. equality = [] - for item, literal in self.set_or_multimap_value_literals[name].items(): - # Match both present and absent members so this represents the whole value. - if item in retained: - equality.append(literal) - else: - equality.append(-literal) + for item, literal in self.value_literals[name].items(): + equality.append(literal if item in retained else -literal) equality.append(helper) return tuple(equality) @@ -328,22 +267,37 @@ def _set_or_multimap_member_nogood( Member literals followed by the helper literal. """ if isinstance(value, multimap.Multimap): - members = {(key, item) for key, items in value.items() for item in items} + members = set() + for key, items in value.items(): + for item in items: + members.add((key, item)) else: members = value - literals = self.set_or_multimap_value_literals[name] - # Memberwise progress is directional, so the union flag selects which condition to match. + literals = self.value_literals[name] if union: - # Union needs an unseen member to appear; match all unseen members being absent. - nogood = [-literal for item, literal in literals.items() if item not in members] + nogood = [] + for item, literal in literals.items(): + if item not in members: + nogood.append(-literal) else: - # Intersection needs a retained member to disappear; match all retained members being present. nogood = [literals[item] for item in members] return (*nogood, helper) -class IntersectionReasoningMode(_LiteralReasoningMode): +class StandardReasoningMode(ReasoningStrategy): + """Use ordinary model enumeration without accumulating constraints.""" + + def join(self, model: dict[clingo.Symbol, object]) -> None: + """Leave the strategy state unchanged for a model. + + Args: + model: Variable values from the current solver model. + """ + return + + +class IntersectionReasoningMode(ReasoningStrategy): """Retain complete variable values that agree across all models.""" def __init__(self) -> None: @@ -363,6 +317,7 @@ def init( variables: Tracked variables and their possible values. """ super().init(init, variables) + self._init_literals(init, variables) self._initialized = False def join(self, model: dict[clingo.Symbol, object]) -> None: @@ -399,11 +354,10 @@ def nogoods(self) -> list[Iterable[int]]: continue # we do this because for intersection there is always just one value in values_in_rm_model value = next(iter(rm_values)) - if name in self.scalar_literals: - for literal in self.scalar_literals[name][value]: - # if the literal corresponds to the retained value then the helper is false - # and thus the witness nogood can still fire - nogoods.append((literal, helper)) + if name in self.scalar_variables: + # If the literal corresponds to the retained value, the helper + # is false and the witness nogood can still fire. + nogoods.append((self.value_literals[name][value], helper)) else: nogoods.append(self._set_or_multimap_value_nogood(name, value, helper)) witnesses.append(-helper) @@ -412,7 +366,7 @@ def nogoods(self) -> list[Iterable[int]]: return nogoods -class UnionReasoningMode(_LiteralReasoningMode): +class UnionReasoningMode(ReasoningStrategy): """Accumulate distinct complete variable values and search for unseen values.""" def init( @@ -427,11 +381,10 @@ def init( variables: Tracked variables and their possible values. """ super().init(init, variables) + self._init_literals(init, variables) init.add_clause(list(self.variable_lit.values())) - for name, value2lit in self.scalar_literals.items(): - literals = set() - for alternatives in value2lit.values(): - literals.update(alternatives) + for name in self.scalar_variables: + literals = set(self.value_literals[name].values()) init.add_clause([*literals, -self.variable_lit[name]]) def join(self, model: dict[clingo.Symbol, object]) -> None: @@ -455,11 +408,9 @@ def nogoods(self) -> list[Iterable[int]]: nogoods: list[Iterable[int]] = [] for name, helper in self.variable_lit.items(): rm_values = self.rm_model.get(name, set()) - if name in self.scalar_literals: - value2lit = self.scalar_literals[name] + if name in self.scalar_variables: for value in rm_values: - for literal in value2lit[value]: - nogoods.append((literal, helper)) + nogoods.append((self.value_literals[name][value], helper)) else: nogoods.extend([self._set_or_multimap_value_nogood(name, value, helper) for value in rm_values]) return nogoods @@ -495,14 +446,25 @@ def _supremum(left: Any, right: Any) -> Any: if isinstance(left, frozenset) and isinstance(right, frozenset): return left.union(right) if isinstance(left, multimap.Multimap) and isinstance(right, multimap.Multimap): - return multimap.Multimap.from_pairs( - (key, value) for source in (left, right) for key, values in source.items() for value in values - ) + pairs = [] + for source in (left, right): + for key, values in source.items(): + for value in values: + pairs.append((key, value)) + return multimap.Multimap.from_pairs(pairs) # if left or right are not a number return "TOP" if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): return "TOP" return max(left, right) + def nogoods(self) -> list[Iterable[int]]: + """Build nogoods for the supremum reasoning mode. + + Returns: + Nogoods matching each previously seen value and the helper. + """ + return [] + class InfimumReasoningMode(ReasoningStrategy): """Accumulate the infimum of each variable across solver models.""" From fb431fe89716ea6bea39e4722bad57af5cdfd782 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Tue, 10 Nov 2026 07:36:01 +0100 Subject: [PATCH 05/29] Add nogood implementation for infumum mode --- .../reasoning_modes_propagator.py | 76 ++++++++++++++++--- 1 file changed, 67 insertions(+), 9 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index dc744673a..c833dc5f5 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -419,6 +419,19 @@ def nogoods(self) -> list[Iterable[int]]: class SupremumReasoningMode(ReasoningStrategy): """Accumulate the supremum of each variable across solver models.""" + def init( + self, + init: clingo.PropagateInit, + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], + ) -> None: + """Reset bounds and require at least one progress witness.""" + super().init(init, variables) + self._init_literals(init, variables) + init.add_clause(list(self.variable_lit.values())) + for name in self.scalar_variables: + literals = set(self.value_literals[name].values()) + init.add_clause([*literals, -self.variable_lit[name]]) + def join(self, model: dict[clingo.Symbol, object]) -> None: """Accumulate the least upper bound of a model's variable values. @@ -441,7 +454,8 @@ def _supremum(left: Any, right: Any) -> Any: right: Second scalar or collection value. Returns: - Their union for collections or their maximum for scalars. + Their union for collections, maximum for numbers, or TOP for + unequal nonnumeric values. Equal nonnumeric values are unchanged. """ if isinstance(left, frozenset) and isinstance(right, frozenset): return left.union(right) @@ -452,23 +466,47 @@ def _supremum(left: Any, right: Any) -> Any: for value in values: pairs.append((key, value)) return multimap.Multimap.from_pairs(pairs) - # if left or right are not a number return "TOP" if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): - return "TOP" + return left if left == right else "TOP" return max(left, right) def nogoods(self) -> list[Iterable[int]]: - """Build nogoods for the supremum reasoning mode. + """Require at least one variable to improve the accumulated supremum. Returns: - Nogoods matching each previously seen value and the helper. + Nogoods blocking unchanged scalar bounds and already-seen members + from witnessing progress after the current model. """ - return [] + nogoods: list[Iterable[int]] = [] + for name, helper in self.variable_lit.items(): + if name not in self.rm_model: + continue + current = next(iter(self.rm_model[name])) + if name in self.scalar_variables: + for value, literal in self.value_literals[name].items(): + if self._supremum(current, value) == current: + nogoods.append((literal, helper)) + else: + nogoods.append(self._set_or_multimap_member_nogood(name, current, helper, union=True)) + return nogoods class InfimumReasoningMode(ReasoningStrategy): """Accumulate the infimum of each variable across solver models.""" + def init( + self, + init: clingo.PropagateInit, + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], + ) -> None: + """Reset bounds and require at least one progress witness.""" + super().init(init, variables) + self._init_literals(init, variables) + init.add_clause(list(self.variable_lit.values())) + for name in self.scalar_variables: + literals = set(self.value_literals[name].values()) + init.add_clause([*literals, -self.variable_lit[name]]) + def join(self, model: dict[clingo.Symbol, object]) -> None: """Accumulate the greatest lower bound of a model's variable values. @@ -491,7 +529,8 @@ def _infimum(left: Any, right: Any) -> Any: right: Second scalar or collection value. Returns: - Their intersection for collections or their minimum for scalars. + Their intersection for collections, minimum for numbers, or BOT for + unequal nonnumeric values. Equal nonnumeric values are unchanged. """ if isinstance(left, frozenset) and isinstance(right, frozenset): return left.intersection(right) @@ -499,11 +538,30 @@ def _infimum(left: Any, right: Any) -> Any: return multimap.Multimap.from_pairs( (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) ) - # if left or right are not a number return "BOT" if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): - return "BOT" + return left if left == right else "BOT" return min(left, right) + def nogoods(self) -> list[Iterable[int]]: + """Require at least one variable to improve the accumulated infimum. + + Returns: + Nogoods blocking unchanged scalar bounds and retained members + from witnessing progress after the current model. + """ + nogoods: list[Iterable[int]] = [] + for name, helper in self.variable_lit.items(): + if name not in self.rm_model: + continue + current = next(iter(self.rm_model[name])) + if name in self.scalar_variables: + for value, literal in self.value_literals[name].items(): + if self._infimum(current, value) == current: + nogoods.append((literal, helper)) + else: + nogoods.append(self._set_or_multimap_member_nogood(name, current, helper)) + return nogoods + REASONING_STRATEGIES = { ReasoningMode.STANDARD: StandardReasoningMode, From 290d8d08be46c24f64beda80de2ad4d2d6599d03 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Wed, 11 Nov 2026 01:45:13 +0100 Subject: [PATCH 06/29] Use on model to add nogods --- src/constraint_handler/main.py | 2 + .../reasoning_modes_propagator.py | 174 ++++++++---------- 2 files changed, 76 insertions(+), 100 deletions(-) diff --git a/src/constraint_handler/main.py b/src/constraint_handler/main.py index 60c2f92b0..bd43617a7 100644 --- a/src/constraint_handler/main.py +++ b/src/constraint_handler/main.py @@ -227,6 +227,7 @@ def om(model): if prop.on_model(model) == False: return False post_processor.set_optimize_valuation(post_prop, model) + reasoning_mode_prop.on_model(model) post_processor.extend_with_reasoning_mode_atoms(reasoning_mode_prop, model) if on_model is not None: return on_model(model) @@ -235,6 +236,7 @@ def om(model): def new_solve(*args, **kwargs): post_prop.reset_optimize_value_symbols() + reasoning_mode_prop.prepare(ctrl) if len(args) > 1: args = (args[0], combine_on_model(args[1])) + args[2:] elif "on_model" in kwargs: diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index c833dc5f5..d2e8552bb 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -1,8 +1,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections import deque -from collections.abc import Iterable, Sequence +from collections.abc import Iterable from dataclasses import dataclass, field from enum import Enum from typing import Any @@ -31,10 +30,10 @@ class ReasoningMode(Enum): @dataclass class _Value: - """Associate a solver literal with a possible variable value. + """Associate a program literal with a possible variable value. Attributes: - literal: Solver literal that is true when the value is selected. + literal: Program literal that is true when the value is selected. value: Python representation of the possible value. """ @@ -44,10 +43,10 @@ class _Value: @dataclass class _PairValue: - """Associate a solver literal with a possible multimap pair. + """Associate a program literal with a possible multimap pair. Attributes: - literal: Solver literal that is true when the pair is present. + literal: Program literal that is true when the pair is present. key: Key in the multimap. value: Value associated with the key. """ @@ -73,14 +72,14 @@ class _ScalarVariable: value: Any = None has_value: bool = False - def update(self, assignment: clingo.Assignment) -> None: - """Update the selected value from a solver assignment. + def update(self, model: clingo.Model) -> None: + """Update the selected value from an accepted model. Args: - assignment: Current solver assignment used to inspect literals. + model: Current model used to inspect program literals. """ for candidate in self.possible_values: - if assignment.is_true(candidate.literal): + if model.is_true(candidate.literal): self.value = candidate.value self.has_value = True return @@ -103,14 +102,14 @@ class _SetVariable: possible_values: list[_Value] = field(default_factory=list) value: frozenset[Any] = frozenset() - def update(self, assignment: clingo.Assignment) -> None: + def update(self, model: clingo.Model) -> None: """Rebuild the set value from true member literals. Args: - assignment: Current solver assignment used to inspect literals. + model: Current model used to inspect program literals. """ self.value = frozenset( - candidate.value for candidate in self.possible_values if assignment.is_true(candidate.literal) + candidate.value for candidate in self.possible_values if model.is_true(candidate.literal) ) @@ -128,16 +127,14 @@ class _MultimapVariable: possible_values: list[_PairValue] = field(default_factory=list) value: multimap.Multimap[Any, Any] = field(default_factory=lambda: multimap.Multimap.from_pairs([])) - def update(self, assignment: clingo.Assignment) -> None: + def update(self, model: clingo.Model) -> None: """Rebuild the multimap value from true pair literals. Args: - assignment: Current solver assignment used to inspect literals. + model: Current model used to inspect program literals. """ self.value = multimap.Multimap.from_pairs( - (candidate.key, candidate.value) - for candidate in self.possible_values - if assignment.is_true(candidate.literal) + (candidate.key, candidate.value) for candidate in self.possible_values if model.is_true(candidate.literal) ) @@ -185,6 +182,7 @@ def __init__(self) -> None: self.variable_lit: dict[clingo.Symbol, int] = {} self.value_literals: dict[clingo.Symbol, dict[Any, int]] = {} self.scalar_variables: set[clingo.Symbol] = set() + self.solve_literal: int | None = None def init( self, @@ -221,13 +219,12 @@ def _init_literals( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Create witnesses and map collection values to their solver literals.""" - self.variable_lit.clear() + """Freeze prepared witnesses and map values to program literals.""" self.value_literals.clear() self.scalar_variables.clear() for name, variable in variables.items(): - self.variable_lit[name] = init.add_literal(freeze=True) + init.freeze_literal(init.solver_literal(self.variable_lit[name])) self.value_literals[name] = {} if isinstance(variable, _ScalarVariable): self.scalar_variables.add(name) @@ -239,6 +236,17 @@ def _init_literals( value = candidate.value self.value_literals[name][value] = candidate.literal + def _add_progress_guards(self, init: clingo.PropagateInit) -> None: + """Install static solver guards that become inactive on later solves.""" + assert self.solve_literal is not None + inactive = -init.solver_literal(self.solve_literal) + init.freeze_literal(-inactive) + init.add_clause([inactive, *(init.solver_literal(literal) for literal in self.variable_lit.values())]) + for name in self.scalar_variables: + literals = set(self.value_literals[name].values()) + clause = [*literals, -self.variable_lit[name]] + init.add_clause([inactive, *(init.solver_literal(literal) for literal in clause)]) + def _set_or_multimap_value_nogood(self, name: clingo.Symbol, value: Any, helper: int) -> tuple[int, ...]: """Build a nogood that matches a complete collection value and witness.""" if isinstance(value, multimap.Multimap): @@ -382,10 +390,7 @@ def init( """ super().init(init, variables) self._init_literals(init, variables) - init.add_clause(list(self.variable_lit.values())) - for name in self.scalar_variables: - literals = set(self.value_literals[name].values()) - init.add_clause([*literals, -self.variable_lit[name]]) + self._add_progress_guards(init) def join(self, model: dict[clingo.Symbol, object]) -> None: """Add each model value to the accumulated set of values. @@ -427,10 +432,7 @@ def init( """Reset bounds and require at least one progress witness.""" super().init(init, variables) self._init_literals(init, variables) - init.add_clause(list(self.variable_lit.values())) - for name in self.scalar_variables: - literals = set(self.value_literals[name].values()) - init.add_clause([*literals, -self.variable_lit[name]]) + self._add_progress_guards(init) def join(self, model: dict[clingo.Symbol, object]) -> None: """Accumulate the least upper bound of a model's variable values. @@ -502,10 +504,7 @@ def init( """Reset bounds and require at least one progress witness.""" super().init(init, variables) self._init_literals(init, variables) - init.add_clause(list(self.variable_lit.values())) - for name in self.scalar_variables: - literals = set(self.value_literals[name].values()) - init.add_clause([*literals, -self.variable_lit[name]]) + self._add_progress_guards(init) def join(self, model: dict[clingo.Symbol, object]) -> None: """Accumulate the greatest lower bound of a model's variable values. @@ -575,6 +574,9 @@ def nogoods(self) -> list[Iterable[int]]: class ReasoningModesPropagator(clingo.Propagator): """Build variable models and apply nogoods for a reasoning strategy. + Call prepare after grounding and before each solve, and pass on_model to + the solve callback. The main API wires both steps automatically. + Attributes: reasoning_strategy: Strategy used to combine successive models. disabled: Whether standard enumeration makes propagation unnecessary. @@ -588,8 +590,8 @@ def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> No """ self.reasoning_strategy: ReasoningStrategy = REASONING_STRATEGIES[reasoning_mode]() self._variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = {} - self._watched_literals: set[int] = set() - self._nogood_queue: deque[Iterable[int]] = deque() + self._witnesses: dict[clingo.Symbol, int] = {} + self._solve_literal: int | None = None self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) @@ -602,24 +604,24 @@ def set_mode(self, reasoning_mode: ReasoningMode) -> None: self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode]() self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) - def init(self, init: clingo.PropagateInit) -> None: - """Load variable values and register watched solver literals. + def prepare(self, control: clingo.Control) -> None: + """Load program literals and support progress witnesses before solving. Args: - init: Clingo initialization context for the current solve. + control: Grounded control whose next solve will use this strategy. """ + if self._solve_literal is not None: + control.release_external(self._solve_literal) + self._solve_literal = None if self.disabled: return self._variables.clear() - self._watched_literals.clear() - self._nogood_queue.clear() - init.check_mode = clingo.PropagatorCheckMode.Total - se_values = myClorm.findInPropagateInit(init, internal._se_value) - set_values = myClorm.findInPropagateInit(init, internal._set_contains) - multimap_values = myClorm.findInPropagateInit(init, result.Multimap_value) + se_values = myClorm.findInControl(control, internal._se_value) + set_values = myClorm.findInControl(control, internal._set_contains) + multimap_values = myClorm.findInControl(control, result.Multimap_value) - for (expr, value), literal in se_values.items(): + for atom, (expr, value) in se_values.items(): if not isinstance(expr, expression.Variable): continue name = _variable_to_symbol(expr) @@ -630,79 +632,51 @@ def init(self, init: clingo.PropagateInit) -> None: else: scalar = self._variables.setdefault(name, _ScalarVariable(name)) if isinstance(scalar, _ScalarVariable): - scalar.possible_values.append(_Value(literal, _python_value(value))) + scalar.possible_values.append(_Value(atom.literal, _python_value(value))) - for (expr, value), literal in set_values.items(): + for atom, (expr, value) in set_values.items(): for variable in self._variables.values(): if isinstance(variable, _SetVariable) and variable.source == expr: - variable.possible_values.append(_Value(literal, _python_value(value))) - self._watched_literals.add(literal) + variable.possible_values.append(_Value(atom.literal, _python_value(value))) - for (name, key, value), literal in multimap_values.items(): + for atom, (name, key, value) in multimap_values.items(): variable_name = myClorm.pytocl(expression.Variable(name)).arguments[0] variable = self._variables.get(variable_name) if isinstance(variable, _MultimapVariable): - variable.possible_values.append(_PairValue(literal, _python_value(key), _python_value(value))) - self._watched_literals.add(literal) - - for variable in self._variables.values(): - if isinstance(variable, _ScalarVariable): - self._watched_literals.update(candidate.literal for candidate in variable.possible_values) - for literal in self._watched_literals: - init.add_watch(literal) - self.reasoning_strategy.init(init, self._variables) + variable.possible_values.append(_PairValue(atom.literal, _python_value(key), _python_value(value))) + + with control.backend() as backend: + for name in self._variables: + if name not in self._witnesses: + helper = backend.add_atom() + backend.add_rule([helper], choice=True) + self._witnesses[name] = helper + self._solve_literal = backend.add_atom() + backend.add_external(self._solve_literal, clingo.TruthValue.True_) + self.reasoning_strategy.variable_lit = {name: self._witnesses[name] for name in self._variables} + self.reasoning_strategy.solve_literal = self._solve_literal - def propagate(self, control: clingo.PropagateControl, changes: Sequence[int]) -> None: - """Add queued nogoods without updating tracked variable values. - - Args: - control: Clingo control used to add nogoods. - changes: Watched literals whose assignments changed. - """ + def init(self, init: clingo.PropagateInit) -> None: + """Reset accumulation and initialize guards for the current solve.""" if self.disabled: return - self._add_nogoods(control) + self.reasoning_strategy.init(init, self._variables) - def check(self, control: clingo.PropagateControl) -> None: - """Process a total assignment and queue constraints for further progress. + def on_model(self, model: clingo.Model) -> None: + """Accumulate an accepted model and constrain the search for the next. Args: - control: Clingo control containing the current assignment. + model: Accepted model whose program literals determine its values. """ if self.disabled: return - if self._add_nogoods(control): - return - if not control.assignment.is_total: - return for variable in self._variables.values(): - variable.update(control.assignment) - model = {variable.name: variable.value for variable in self._variables.values() if _has_value(variable)} - self.reasoning_strategy.join(model) - # Let this assignment finish before installing nogoods that demand further progress. - self._nogood_queue.extend(tuple(nogood) for nogood in self.reasoning_strategy.nogoods()) - - # print values stored - import pprint - - print("Stored values:") - pprint.pprint(self.reasoning_strategy.rm_model) - - def _add_nogoods(self, control: clingo.PropagateControl) -> bool: - """Add queued nogoods until the queue is empty or propagation stops. - - Args: - control: Clingo control used to add nogoods. - - Returns: - Whether adding a nogood stopped propagation. - """ - while self._nogood_queue: - nogood = self._nogood_queue.popleft() - if not control.add_nogood(nogood, tag=True, lock=True): - return True - return False + variable.update(model) + values = {variable.name: variable.value for variable in self._variables.values() if _has_value(variable)} + self.reasoning_strategy.join(values) + for nogood in self.reasoning_strategy.nogoods(): + model.context.add_nogood(tuple(nogood)) def _has_value(variable: _ScalarVariable | _SetVariable | _MultimapVariable) -> bool: From 2082098a3fe16183c6ef37bf7ad2d7fe45e22c94 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Wed, 11 Nov 2026 03:38:54 +0100 Subject: [PATCH 07/29] Output for reaosning mode follow model_/2 format --- src/constraint_handler/post_processor.py | 32 +++++++++++++------ .../reasoning_modes_propagator.py | 3 ++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/constraint_handler/post_processor.py b/src/constraint_handler/post_processor.py index 16cbb3624..25368cfe5 100644 --- a/src/constraint_handler/post_processor.py +++ b/src/constraint_handler/post_processor.py @@ -1,7 +1,8 @@ from __future__ import annotations from collections import defaultdict -from typing import Mapping +from collections.abc import Mapping +from typing import Any import clingo from mypy.server.update import propagate_changes_using_dependencies @@ -10,8 +11,8 @@ import constraint_handler.myClorm as myClorm import constraint_handler.schemas.result as result import constraint_handler.schemas.warning as warning -from constraint_handler.propagator.model_builder import ModelBuilder -from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningModesPropagator +from constraint_handler import multimap +from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningMode, ReasoningModesPropagator class OptimizePostProcessingPropagator(clingo.Propagator): @@ -143,13 +144,26 @@ def set_optimize_valuation(propagator: OptimizePostProcessingPropagator, model) def extend_with_reasoning_mode_atoms(propagator: ReasoningModesPropagator, model) -> None: - model_builder = ModelBuilder({}) + if propagator.reasoning_mode is ReasoningMode.STANDARD: + return + symbols = set() for variable, values in propagator.reasoning_strategy.rm_model.items(): for value in values: - model_builder.add_value(variable, value) - - for atom in model_builder.atoms: - symbol = myClorm.pytocl(atom) - symbols.add(clingo.Function(f"{symbol.name}_rm", symbol.arguments)) + if isinstance(value, multimap.Multimap): + value_symbol = _multimap_symbol(value) + else: + reduced_value, _ = evaluator.reducedExpr(value) + value_symbol = myClorm.pytocl(reduced_value) + symbols.add(clingo.Function(f"model_{propagator.reasoning_mode.name.lower()}", [variable, value_symbol])) model.extend(symbols) + + +def _multimap_symbol(value: multimap.Multimap[Any, Any]) -> clingo.Symbol: + entries = [] + for key, values in value.items(): + reduced_key, _ = evaluator.reducedExpr(key) + reduced_values = sorted(myClorm.pytocl(evaluator.reducedExpr(item)[0]) for item in values) + entries.append(clingo.Function("", [myClorm.pytocl(reduced_key), myClorm.nest(reduced_values)])) + + return clingo.Function("multimap", [myClorm.nest(sorted(entries)), clingo.Function("", [])]) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index d2e8552bb..558ce188d 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -578,6 +578,7 @@ class ReasoningModesPropagator(clingo.Propagator): the solve callback. The main API wires both steps automatically. Attributes: + reasoning_mode: Selected mode used to name aggregate model atoms. reasoning_strategy: Strategy used to combine successive models. disabled: Whether standard enumeration makes propagation unnecessary. """ @@ -588,6 +589,7 @@ def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> No Args: reasoning_mode: Strategy to use during model enumeration. """ + self.reasoning_mode = reasoning_mode self.reasoning_strategy: ReasoningStrategy = REASONING_STRATEGIES[reasoning_mode]() self._variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = {} self._witnesses: dict[clingo.Symbol, int] = {} @@ -601,6 +603,7 @@ def set_mode(self, reasoning_mode: ReasoningMode) -> None: Args: reasoning_mode: Strategy to use during model enumeration. """ + self.reasoning_mode = reasoning_mode self.reasoning_strategy = REASONING_STRATEGIES[reasoning_mode]() self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) From 86a6609978d39dbe6a412e1b3c58d549532c1cd4 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Wed, 11 Nov 2026 10:15:20 +0100 Subject: [PATCH 08/29] Add testing for reasoning modes propagator --- tests/test_reasoning_mode_propagator.py | 1083 +++++++++++++++++++++++ 1 file changed, 1083 insertions(+) create mode 100644 tests/test_reasoning_mode_propagator.py diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py new file mode 100644 index 000000000..368adfd6f --- /dev/null +++ b/tests/test_reasoning_mode_propagator.py @@ -0,0 +1,1083 @@ +from collections.abc import Iterable +from itertools import pairwise +from pathlib import Path +from typing import cast + +import clingo +import pytest + +from constraint_handler import add_to_control, engine, multimap +from constraint_handler.post_processor import extend_with_reasoning_mode_atoms +from constraint_handler.reasoning_modes.reasoning_modes_propagator import ( + InfimumReasoningMode, + IntersectionReasoningMode, + ReasoningMode, + ReasoningModesPropagator, + ReasoningStrategy, + SupremumReasoningMode, + UnionReasoningMode, + _MultimapVariable, + _PairValue, + _ScalarVariable, + _SetVariable, + _Value, +) +from constraint_handler.schemas import expression + + +class _RecordingReasoningStrategy(ReasoningStrategy): + def __init__(self) -> None: + super().__init__() + self.models: list[dict[clingo.Symbol, object]] = [] + + def join(self, model: dict[clingo.Symbol, object]) -> None: + self.models.append(model.copy()) + + +class _NogoodContext: + def __init__(self) -> None: + self.added: list[Iterable[int]] = [] + + def add_nogood(self, nogood: Iterable[int]) -> None: + self.added.append(tuple(nogood)) + + +class _InitRecorder: + def __init__(self) -> None: + self.frozen: list[int] = [] + self.clauses: list[tuple[int, ...]] = [] + + def solver_literal(self, literal: int) -> int: + return literal + 100 if literal > 0 else literal - 100 + + def freeze_literal(self, literal: int) -> None: + self.frozen.append(literal) + + def add_clause(self, clause: Iterable[int]) -> None: + self.clauses.append(tuple(clause)) + + +class _Model: + def __init__(self) -> None: + self.symbols: set[clingo.Symbol] = set() + + def extend(self, symbols) -> None: + self.symbols.update(symbols) + + +def _extend(values: dict[clingo.Symbol, set[object]], mode: ReasoningMode = ReasoningMode.UNION) -> set[clingo.Symbol]: + propagator = ReasoningModesPropagator(mode) + propagator.reasoning_strategy.rm_model = values + model = _Model() + + extend_with_reasoning_mode_atoms(propagator, model) + + return model.symbols + + +def test_extend_reasoning_mode_atoms_emits_each_scalar_value() -> None: + variable = clingo.String("x") + + symbols = _extend({variable: {3, 5}}) + + assert {symbol.name for symbol in symbols} == {"model_union"} + assert {symbol.arguments[0] for symbol in symbols} == {variable} + assert {symbol.arguments[1] for symbol in symbols} == { + clingo.Function("val", [clingo.Function("int"), clingo.Number(3)]), + clingo.Function("val", [clingo.Function("int"), clingo.Number(5)]), + } + + +def test_extend_reasoning_mode_atoms_encodes_whole_set_values() -> None: + variable = clingo.String("items") + + symbols = _extend({variable: {frozenset({1, 2}), frozenset({3})}}) + + assert symbols == { + clingo.parse_term('model_union("items",set((val(int,1),(val(int,2),()))))'), + clingo.parse_term('model_union("items",set((val(int,3),())))'), + } + + +def test_extend_reasoning_mode_atoms_encodes_empty_set_marker() -> None: + variable = clingo.String("items") + + symbols = _extend({variable: {frozenset()}}) + + assert symbols == {clingo.parse_term('model_union("items",set(()))')} + + +def test_extend_reasoning_mode_atoms_encodes_whole_multimap_values() -> None: + variable = clingo.String("mapping") + first = multimap.Multimap.from_pairs([("key", 1), ("key", 2)]) + second = multimap.Multimap.from_pairs([("key", 3)]) + + symbols = _extend({variable: {first, second}}) + + assert symbols == { + clingo.parse_term('model_union("mapping",multimap(((val(string,"key"),(val(int,1),(val(int,2),()))),()),()))'), + clingo.parse_term('model_union("mapping",multimap(((val(string,"key"),(val(int,3),())),()),()))'), + } + + +def test_extend_reasoning_mode_atoms_preserves_standard_mode_output() -> None: + variable = clingo.String("x") + + assert _extend({variable: {3}}, ReasoningMode.STANDARD) == set() + + +def test_extend_reasoning_mode_atoms_encodes_empty_multimap() -> None: + variable = clingo.String("mapping") + value = multimap.Multimap.from_pairs([]) + + assert _extend({variable: {value}}) == {clingo.parse_term('model_union("mapping",multimap((),()))')} + + +def test_supremum_reasoning_mode_joins_values() -> None: + mode = SupremumReasoningMode() + variable = clingo.String("value") + + mode.join({variable: 3}) + mode.join({variable: 7}) + + assert mode.rm_model == {variable: {7}} + + +def test_infimum_reasoning_mode_joins_values() -> None: + mode = InfimumReasoningMode() + variable = clingo.String("value") + + mode.join({variable: 7}) + mode.join({variable: 3}) + + assert mode.rm_model == {variable: {3}} + + +def test_supremum_and_infimum_join_set_values() -> None: + variable = clingo.String("items") + supremum = SupremumReasoningMode() + infimum = InfimumReasoningMode() + + for mode in (supremum, infimum): + mode.join({variable: frozenset({1, 2})}) + mode.join({variable: frozenset({2, 3})}) + + assert supremum.rm_model == {variable: {frozenset({1, 2, 3})}} + assert infimum.rm_model == {variable: {frozenset({2})}} + + +def test_supremum_and_infimum_join_multimap_values() -> None: + variable = clingo.String("mapping") + supremum = SupremumReasoningMode() + infimum = InfimumReasoningMode() + first = multimap.Multimap.from_pairs([("shared", 1), ("left", 2)]) + second = multimap.Multimap.from_pairs([("shared", 1), ("shared", 3), ("right", 4)]) + + for mode in (supremum, infimum): + mode.join({variable: first}) + mode.join({variable: second}) + + expected_supremum = multimap.Multimap.from_pairs([("shared", 1), ("shared", 3), ("left", 2), ("right", 4)]) + assert supremum.rm_model == {variable: {expected_supremum}} + assert infimum.rm_model == {variable: {multimap.Multimap.from_pairs([("shared", 1)])}} + + +@pytest.mark.parametrize("mode_type", [UnionReasoningMode, SupremumReasoningMode, InfimumReasoningMode]) +def test_reasoning_mode_translates_program_literals_for_guards(mode_type: type[ReasoningStrategy]) -> None: + name = clingo.String("value") + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = { + name: _ScalarVariable(name, [_Value(1, 1)]) + } + mode = mode_type() + mode.variable_lit = {name: 2} + mode.solve_literal = 3 + init = _InitRecorder() + mode.init(cast(clingo.PropagateInit, init), variables) + assert init.frozen == [102, 103] + assert init.clauses == [(-103, 102), (-103, 101, -102)] + assert mode.variable_lit == {name: 2} + assert mode.value_literals == {name: {1: 1}} + + +@pytest.mark.parametrize( + "left, right, expected", + [ + ("same", "same", "same"), + ("left", "right", "TOP"), + (3, "text", "TOP"), + ("text", 3, "TOP"), + pytest.param(True, 1, "TOP", marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1")), + ("TOP", 3, "TOP"), + (3, "TOP", "TOP"), + ("TOP", "text", "TOP"), + ], +) +def test_supremum_joins_nonnumeric_values(left: object, right: object, expected: object) -> None: + mode = SupremumReasoningMode() + name = clingo.String("value") + mode.join({name: left}) + mode.join({name: right}) + assert mode.rm_model == {name: {expected}} + + +@pytest.mark.parametrize( + "current, candidates, blocked", + [ + (2, [1, 2, 3], [1, 2]), + (2.5, [1.5, 2.5, 3.5], [1.5, 2.5]), + (False, [False, True], [False]), + (True, [False, True], [False, True]), + ("same", ["same", "other", 3], ["same"]), + ("TOP", ["same", "TOP", 3], ["same", "TOP", 3]), + (3, [2, 3, "text"], [2, 3]), + ], +) +def test_supremum_scalar_nogoods_only_allow_improvement( + current: object, candidates: list[object], blocked: list[object] +) -> None: + mode = SupremumReasoningMode() + name = clingo.String("value") + mode.variable_lit = {name: 10} + mode.scalar_variables = {name} + mode.value_literals = {name: {value: literal for literal, value in enumerate(candidates, 1)}} + mode.join({name: current}) + + assert mode.nogoods() == [(mode.value_literals[name][value], 10) for value in blocked] + + +@pytest.mark.parametrize("mode_type", [SupremumReasoningMode, InfimumReasoningMode]) +def test_reasoning_mode_absent_scalar_can_witness_its_first_value(mode_type: type[ReasoningStrategy]) -> None: + mode = mode_type() + name = clingo.String("value") + mode.variable_lit = {name: 10} + mode.scalar_variables = {name} + mode.value_literals = {name: {None: 1, 3: 2}} + mode.join({}) + + assert mode.nogoods() == [] + + mode.join({name: None}) + mode.join({}) + assert mode.rm_model == {name: {None}} + assert mode.nogoods() == [(1, 10)] + + +@pytest.mark.parametrize("members", [frozenset(), frozenset({1}), frozenset({1, 2})]) +def test_supremum_collection_nogoods_require_unseen_members(members: frozenset[int]) -> None: + mode = SupremumReasoningMode() + items = clingo.String("items") + mapping = clingo.String("mapping") + mode.variable_lit = {items: 10, mapping: 11} + mode.value_literals = {items: {1: 2, 2: 3}, mapping: {("key", 1): 4, ("key", 2): 5}} + mode.join({items: members, mapping: multimap.Multimap.from_pairs(("key", value) for value in members)}) + + assert mode.nogoods() == [ + (*(-literal for value, literal in mode.value_literals[items].items() if value not in members), 10), + (*(-literal for (_, value), literal in mode.value_literals[mapping].items() if value not in members), 11), + ] + + +@pytest.mark.parametrize( + "left, right, expected", + [ + ("same", "same", "same"), + ("left", "right", "BOT"), + (3, "text", "BOT"), + ("text", 3, "BOT"), + pytest.param(True, 1, "BOT", marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1")), + ("BOT", 3, "BOT"), + (3, "BOT", "BOT"), + ("BOT", "text", "BOT"), + ], +) +def test_infimum_joins_nonnumeric_values(left: object, right: object, expected: object) -> None: + mode = InfimumReasoningMode() + name = clingo.String("value") + mode.join({name: left}) + mode.join({name: right}) + assert mode.rm_model == {name: {expected}} + + +@pytest.mark.parametrize( + "current, candidates, blocked", + [ + (2, [1, 2, 3], [2, 3]), + (2.5, [1.5, 2.5, 3.5], [2.5, 3.5]), + (False, [False, True], [False, True]), + (True, [False, True], [True]), + ("same", ["same", "other", 3], ["same"]), + ("BOT", ["same", "BOT", 3], ["same", "BOT", 3]), + (3, [2, 3, "text"], [3]), + ], +) +def test_infimum_scalar_nogoods_only_allow_improvement( + current: object, candidates: list[object], blocked: list[object] +) -> None: + mode = InfimumReasoningMode() + name = clingo.String("value") + mode.variable_lit = {name: 10} + mode.scalar_variables = {name} + mode.value_literals = {name: {value: literal for literal, value in enumerate(candidates, 1)}} + mode.join({name: current}) + + assert mode.nogoods() == [(mode.value_literals[name][value], 10) for value in blocked] + + +@pytest.mark.parametrize("members", [frozenset(), frozenset({1}), frozenset({1, 2})]) +def test_infimum_collection_nogoods_require_removing_retained_members(members: frozenset[int]) -> None: + mode = InfimumReasoningMode() + items = clingo.String("items") + mapping = clingo.String("mapping") + mode.variable_lit = {items: 10, mapping: 11} + mode.value_literals = {items: {1: 2, 2: 3}, mapping: {("key", 1): 4, ("key", 2): 5}} + mode.join({items: members, mapping: multimap.Multimap.from_pairs(("key", value) for value in members)}) + + assert [frozenset(nogood) for nogood in mode.nogoods()] == [ + frozenset([*(literal for value, literal in mode.value_literals[items].items() if value in members), 10]), + frozenset([*(literal for (_, value), literal in mode.value_literals[mapping].items() if value in members), 11]), + ] + + +def test_collection_values_reuse_candidate_literals_without_presence_helpers() -> None: + items = clingo.String("items") + mapping = clingo.String("mapping") + scalar = clingo.String("scalar") + variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = { + scalar: _ScalarVariable(scalar, [_Value(1, 4), _Value(2, 5)]), + items: _SetVariable(items, expression.Variable("items"), [_Value(1, 1), _Value(2, 2)]), + mapping: _MultimapVariable(mapping, [_PairValue(3, "key", 1)]), + } + mode = UnionReasoningMode() + mode.variable_lit = {scalar: 10, items: 11, mapping: 12} + init = _InitRecorder() + + mode._init_literals(cast(clingo.PropagateInit, init), variables) + + assert init.frozen == [110, 111, 112] + assert init.clauses == [] + assert mode.scalar_variables == {scalar} + assert mode.value_literals == { + scalar: {4: 1, 5: 2}, + items: {1: 1, 2: 2}, + mapping: {("key", 1): 3}, + } + + +@pytest.mark.xfail(reason="Python set equality currently conflates True and 1") +def test_set_variable_update_preserves_python_equal_members() -> None: + class Model: + def is_true(self, literal: int) -> bool: + return literal in {1, 2} + + variable = _SetVariable( + clingo.String("items"), + expression.Variable("items"), + [_Value(1, 1), _Value(2, True)], + ) + + variable.update(cast(clingo.Model, Model())) + + assert len(variable.value) == 2 + + +@pytest.mark.xfail(reason="Python equality currently conflates bool and int candidates") +def test_scalar_and_multimap_values_preserve_bool_and_int_identity() -> None: + class Model: + def __init__(self, true_literals: set[int]) -> None: + self.true_literals = true_literals + + def is_true(self, literal: int) -> bool: + return literal in self.true_literals + + scalar = clingo.String("scalar") + mapping = clingo.String("mapping") + scalar_variable = _ScalarVariable(scalar, [_Value(1, 1), _Value(2, True)]) + mapping_variable = _MultimapVariable( + mapping, + [_PairValue(3, "key", 1), _PairValue(4, "key", True)], + ) + mode = UnionReasoningMode() + mode.variable_lit = {scalar: 10, mapping: 11} + init = _InitRecorder() + + mode._init_literals( + cast(clingo.PropagateInit, init), + {scalar: scalar_variable, mapping: mapping_variable}, + ) + + assert len(mode.value_literals[scalar]) == 2 + assert set(mode.value_literals[scalar].values()) == {1, 2} + assert len(mode.value_literals[mapping]) == 2 + assert set(mode.value_literals[mapping].values()) == {3, 4} + + scalar_values = [] + for literal in (1, 2): + scalar_variable.update(cast(clingo.Model, Model({literal}))) + scalar_values.append(scalar_variable.value) + mode.join({scalar: scalar_variable.value}) + mapping_variable.update(cast(clingo.Model, Model({3, 4}))) + mode.join({mapping: mapping_variable.value}) + + assert {(type(value), value) for value in scalar_values} == {(int, 1), (bool, True)} + assert len(mode.rm_model[scalar]) == 2 + assert len(mapping_variable.value["key"]) == 2 + assert {(type(value), value) for value in mapping_variable.value["key"]} == {(int, 1), (bool, True)} + assert len(mode.rm_model[mapping]) == 1 + + +def test_reasoning_strategy_member_nogoods_handle_sets_and_multimaps() -> None: + mode = UnionReasoningMode() + items = clingo.String("items") + mapping = clingo.String("mapping") + mode.value_literals = { + items: {1: 2, 2: 3}, + mapping: {("key", 1): 4, ("key", 2): 5}, + } + set_value = frozenset({1}) + map_value = multimap.Multimap.from_pairs([("key", 1)]) + + assert mode._set_or_multimap_member_nogood(items, set_value, 10) == (2, 10) + assert mode._set_or_multimap_member_nogood(mapping, map_value, 11) == (4, 11) + assert mode._set_or_multimap_member_nogood(items, set_value, 10, union=True) == (-3, 10) + assert mode._set_or_multimap_member_nogood(mapping, map_value, 11, union=True) == (-5, 11) + + +def test_reasoning_mode_propagator_builds_model_from_accepted_values() -> None: + control = clingo.Control(["0"]) + mode = _RecordingReasoningStrategy() + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + propagator.reasoning_strategy = mode + control.register_propagator(propagator) + control.add( + "base", + [], + """ + 1 { _se_value(variable("scalar"), val(int, 3)); + _se_value(variable("scalar"), val(int, 4)) } 1. + _se_value(variable("items"), ref(set, variable("items"))). + _set_contains(variable("items"), val(int, 7)). + _set_contains(variable("items"), val(int, 8)). + _se_value(variable("mapping"), ref(multimap, variable("mapping"))). + multimap_value("mapping", val(string, "key"), val(int, 9)). + """, + ) + control.ground([("base", [])]) + propagator.prepare(control) + control.solve() + assert mode.models == [] + control.solve(on_model=propagator.on_model) + + scalar = clingo.String("scalar") + items = clingo.String("items") + mapping = clingo.String("mapping") + assert {model[scalar] for model in mode.models} == {3, 4} + assert all(model[items] == frozenset({7, 8}) for model in mode.models) + expected_mapping = multimap.Multimap.from_pairs([("key", 9)]) + assert all(model[mapping] == expected_mapping for model in mode.models) + + +def test_intersection_propagator_callback_pruning_reports_progress_models() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.INTERSECTION) + control.register_propagator(propagator) + control.add( + "base", + [], + """ + 1 { _se_value(variable("scalar"), val(int, 3)); + _se_value(variable("scalar"), val(int, 4)) } 1. + { auxiliary(1..5) }. + """, + ) + control.ground([("base", [])]) + reported = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + reported.append(set(model.symbols(atoms=True))) + + propagator.prepare(control) + solved = control.solve(on_model=on_model) + assert solved.satisfiable + assert len(reported) == 2 + assert propagator.reasoning_strategy.rm_model == {} + + reported.clear() + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable + assert len(reported) == 2 + + +def test_intersection_propagator_whole_value_join_never_revives_values() -> None: + mode = IntersectionReasoningMode() + scalar = clingo.String("scalar") + items = clingo.String("items") + mapping = clingo.String("mapping") + mode.join({scalar: 1, items: frozenset({1, 2}), mapping: multimap.Multimap.from_pairs([("key", 1), ("key", 2)])}) + mode.join({scalar: 2, items: frozenset({2, 3}), mapping: multimap.Multimap.from_pairs([("key", 2), ("key", 3)])}) + mode.join({scalar: 1, items: frozenset({1, 2, 3}), mapping: multimap.Multimap.from_pairs([("key", 1), ("key", 2)])}) + assert mode.rm_model == {} + + +def test_intersection_propagator_drops_scalar_absent_from_a_model() -> None: + mode = IntersectionReasoningMode() + scalar = clingo.String("scalar") + + mode.join({scalar: 1}) + mode.join({}) + + assert mode.rm_model == {} + + +def test_intersection_propagator_optional_scalar_has_empty_intersection() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.INTERSECTION) + control.register_propagator(propagator) + control.add("base", [], '{ _se_value(variable("scalar"), val(int, 1)) }.') + control.ground([("base", [])]) + reported: list[dict[clingo.Symbol, set[object]]] = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + reported.append({name: values.copy() for name, values in propagator.reasoning_strategy.rm_model.items()}) + + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable + assert reported[-1] == {} + + +def test_intersection_propagator_instances_are_independent() -> None: + first = ReasoningModesPropagator(ReasoningMode.INTERSECTION) + second = ReasoningModesPropagator(ReasoningMode.INTERSECTION) + assert first.reasoning_strategy is not second.reasoning_strategy + + +def test_intersection_propagator_empty_collection_is_a_complete_value() -> None: + mode = IntersectionReasoningMode() + items = clingo.String("items") + mode.variable_lit = {items: 10} + mode.value_literals = {items: {1: 2, 2: 3}} + mode.join({items: frozenset()}) + mode.join({items: frozenset()}) + + assert mode.rm_model == {items: {frozenset()}} + assert {tuple(nogood) for nogood in mode.nogoods()} == {(-2, -3, 10), (-10,)} + + mode.join({items: frozenset({1})}) + mode.join({items: frozenset()}) + assert mode.rm_model == {} + assert {tuple(nogood) for nogood in mode.nogoods()} == {(10,), ()} + + +def test_intersection_propagator_nogoods_require_one_retained_value_to_change() -> None: + mode = IntersectionReasoningMode() + scalar = clingo.String("scalar") + items = clingo.String("items") + mapping = clingo.String("mapping") + mode.variable_lit = {scalar: 10, items: 11, mapping: 12} + mode.scalar_variables = {scalar} + mode.value_literals = { + scalar: {7: 2}, + items: {1: 4, 2: 5, 3: 7}, + mapping: {("key", 1): 6, ("key", 2): 8}, + } + mode.join({scalar: 7, items: frozenset({1, 2}), mapping: multimap.Multimap.from_pairs([("key", 1)])}) + + nogoods = {tuple(nogood) for nogood in mode.nogoods()} + assert nogoods == {(2, 10), (4, 5, -7, 11), (6, -8, 12), (-10, -11, -12)} + + mode.join({scalar: 8, items: frozenset(), mapping: multimap.Multimap.from_pairs([])}) + assert {tuple(nogood) for nogood in mode.nogoods()} == {(10,), (11,), (12,), ()} + + +def test_intersection_propagator_prunes_nonshrinking_collection_models() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.INTERSECTION) + control.register_propagator(propagator) + control.add( + "base", + [], + """ + _se_value(variable("items"), ref(set, variable("items"))). + _set_contains(variable("items"), val(int, 1)). + { _set_contains(variable("items"), val(int, 2)) }. + _se_value(variable("mapping"), ref(multimap, variable("mapping"))). + multimap_value("mapping", val(string, "key"), val(int, 1)). + { multimap_value("mapping", val(string, "key"), val(int, 2)) }. + { auxiliary(1..5) }. + """, + ) + control.ground([("base", [])]) + accumulated: list[dict[clingo.Symbol, set[object]]] = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + accumulated.append({name: values.copy() for name, values in propagator.reasoning_strategy.rm_model.items()}) + + propagator.prepare(control) + solved = control.solve(on_model=on_model) + assert solved.satisfiable + assert 2 <= len(accumulated) <= 3 + assert all(previous != current for previous, current in pairwise(accumulated)) + assert propagator.reasoning_strategy.rm_model == {} + + +def test_intersection_propagator_reasoning_modes_fixture_keeps_only_constant_c() -> None: + control = clingo.Control(["0"]) + add_to_control(control, engine=engine.compile, reasoning_mode=ReasoningMode.INTERSECTION) + control.load(str(Path(__file__).parent / "correctness" / "core" / "reasoning_modes.lp")) + control.ground() + reported: list[set[clingo.Symbol]] = [] + + def on_model(model: clingo.Model) -> None: + reported.append({atom for atom in model.symbols(theory=True) if atom.name == "model_intersection"}) + + solved = control.solve(on_model=on_model) + assert solved.satisfiable + assert reported + assert reported[-1] == {clingo.parse_term("model_intersection(c,val(bool,true))")} + + +def test_reasoning_mode_propagator_callback_joins_before_adding_all_nogoods() -> None: + class CallbackStrategy(_RecordingReasoningStrategy): + def nogoods(self) -> list[Iterable[int]]: + assert self.models == [{}] + return [(42,), (43,), ()] + + class Model: + context = _NogoodContext() + + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + strategy = CallbackStrategy() + propagator.reasoning_strategy = strategy + model = Model() + propagator.on_model(cast(clingo.Model, model)) + assert strategy.models == [{}] + assert model.context.added == [(42,), (43,), ()] + + +def test_union_propagator_accumulates_whole_values() -> None: + scalar = clingo.String("scalar") + items = clingo.String("items") + mapping = clingo.String("mapping") + first = multimap.Multimap.from_pairs([("key", 1)]) + second = multimap.Multimap.from_pairs([("key", 2)]) + whole = UnionReasoningMode() + whole.join({scalar: 1, items: frozenset(), mapping: first}) + whole.join({scalar: 2, items: frozenset({2}), mapping: second}) + whole.join({scalar: 1, items: frozenset(), mapping: first}) + assert whole.rm_model == {scalar: {1, 2}, items: {frozenset(), frozenset({2})}, mapping: {first, second}} + + +def test_union_propagator_nogoods_block_seen_complete_values() -> None: + mode = UnionReasoningMode() + scalar = clingo.String("scalar") + items = clingo.String("items") + mode.variable_lit = {scalar: 10, items: 11} + mode.scalar_variables = {scalar} + mode.value_literals = {scalar: {1: 2, 2: 4}, items: {1: 5, 2: 6}} + mode.join({scalar: 1, items: frozenset()}) + mode.join({scalar: 1, items: frozenset({1})}) + nogoods = {frozenset(nogood) for nogood in mode.nogoods()} + assert nogoods == { + frozenset({2, 10}), + frozenset({-5, -6, 11}), + frozenset({5, -6, 11}), + } + + +def test_union_propagator_callback_pruning_reports_strict_growth() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + control.register_propagator(propagator) + control.add( + "base", + [], + """ + 1 { _se_value(variable("scalar"), val(int, 1)); + _se_value(variable("scalar"), val(int, 2)) } 1. + _se_value(variable("items"), ref(set, variable("items"))). + { _set_contains(variable("items"), val(int, 1)) }. + _se_value(variable("mapping"), ref(multimap, variable("mapping"))). + { multimap_value("mapping", val(string, "key"), val(int, 1)) }. + { auxiliary(1..5) }. + """, + ) + control.ground([("base", [])]) + accumulated: list[dict[clingo.Symbol, set[object]]] = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + accumulated.append({name: values.copy() for name, values in propagator.reasoning_strategy.rm_model.items()}) + + expected: dict[clingo.Symbol, set[object]] = { + clingo.String("scalar"): {1, 2}, + clingo.String("items"): {frozenset({1})}, + clingo.String("mapping"): {multimap.Multimap.from_pairs([("key", 1)])}, + } + expected[clingo.String("items")].add(frozenset()) + expected[clingo.String("mapping")].add(multimap.Multimap.from_pairs([])) + for _ in range(2): + accumulated.clear() + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable + assert 2 <= len(accumulated) <= 4 + assert all(previous != current for previous, current in pairwise(accumulated)) + assert propagator.reasoning_strategy.rm_model == expected + + +@pytest.mark.parametrize( + "reasoning_mode, scalar_bound, members", + [ + (ReasoningMode.SUPREMUM, 3, frozenset({0, 1, 2})), + (ReasoningMode.INFIMUM, 1, frozenset({0})), + ], +) +def test_extremum_propagator_callback_pruning_reports_strict_progress( + reasoning_mode: ReasoningMode, scalar_bound: int, members: frozenset[int] +) -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(reasoning_mode) + control.register_propagator(propagator) + control.add( + "base", + [], + """ + 1 { _se_value(variable("scalar"), val(int, 1..3)) } 1. + _se_value(variable("items"), ref(set, variable("items"))). + _set_contains(variable("items"), val(int, 0)). + 1 { _set_contains(variable("items"), val(int, 1..2)) } 1. + _se_value(variable("mapping"), ref(multimap, variable("mapping"))). + multimap_value("mapping", val(string, "key"), val(int, 0)). + 1 { multimap_value("mapping", val(string, "key"), val(int, 1..2)) } 1. + { auxiliary(1..5) }. + """, + ) + control.ground([("base", [])]) + accumulated: list[dict[clingo.Symbol, set[object]]] = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + accumulated.append({name: values.copy() for name, values in propagator.reasoning_strategy.rm_model.items()}) + + expected: dict[clingo.Symbol, set[object]] = { + clingo.String("scalar"): {scalar_bound}, + clingo.String("items"): {members}, + clingo.String("mapping"): {multimap.Multimap.from_pairs(("key", value) for value in members)}, + } + combine = ( + SupremumReasoningMode._supremum if reasoning_mode == ReasoningMode.SUPREMUM else InfimumReasoningMode._infimum + ) + for _ in range(2): + accumulated.clear() + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable + assert 2 <= len(accumulated) <= 5 + for previous, current in pairwise(accumulated): + assert previous != current + for name in previous: + assert combine(next(iter(previous[name])), next(iter(current[name]))) == next(iter(current[name])) + assert propagator.reasoning_strategy.rm_model == expected + + +@pytest.mark.parametrize("reasoning_mode", [ReasoningMode.SUPREMUM, ReasoningMode.INFIMUM]) +@pytest.mark.parametrize( + "program, expected_supremum, expected_infimum, max_models", + [ + ('_se_value(variable("value"), val(string, "same")).', {"same"}, {"same"}, 1), + ( + ( + '1 { _se_value(variable("value"), val(string, "left")); ' + '_se_value(variable("value"), val(string, "right")) } 1.' + ), + {"TOP"}, + {"BOT"}, + 2, + ), + ( + ('1 { _se_value(variable("value"), val(int, 3)); _se_value(variable("value"), val(string, "text")) } 1.'), + {"TOP"}, + {"BOT"}, + 2, + ), + ('{ _se_value(variable("value"), val(int, 1..3)) } 1.', {3}, {1}, 4), + ( + ('{ _se_value(variable("value"), val(int, 1)) }. :- _se_value(variable("value"), val(int, 1)).'), + None, + None, + 0, + ), + ('_se_value(variable("value"), ref(set, variable("value"))).', {frozenset()}, {frozenset()}, 1), + ( + '_se_value(variable("value"), ref(multimap, variable("value"))).', + {multimap.Multimap.from_pairs([])}, + {multimap.Multimap.from_pairs([])}, + 1, + ), + pytest.param( + "", + set(), + set(), + 32, + marks=pytest.mark.xfail( + reason="Progress guards currently make aggregate modes UNSAT with no tracked variables" + ), + ), + ], +) +def test_extremum_propagator_scalar_and_empty_domains( + reasoning_mode: ReasoningMode, + program: str, + expected_supremum: set[object] | None, + expected_infimum: set[object] | None, + max_models: int, +) -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(reasoning_mode) + control.register_propagator(propagator) + control.add("base", [], program + " { auxiliary(1..5) }.") + control.ground([("base", [])]) + accumulated: list[dict[clingo.Symbol, set[object]]] = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + accumulated.append({name: values.copy() for name, values in propagator.reasoning_strategy.rm_model.items()}) + + expected = expected_supremum if reasoning_mode == ReasoningMode.SUPREMUM else expected_infimum + for _ in range(2): + accumulated.clear() + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable == (expected is not None) + assert bool(accumulated) == (expected is not None) + assert len(accumulated) <= max_models + if expected: + assert all(previous != current for previous, current in pairwise(accumulated)) + expected_model = {} if not expected else {clingo.String("value"): expected} + assert propagator.reasoning_strategy.rm_model == expected_model + + +def test_reasoning_mode_ignores_total_assignments_rejected_by_another_propagator() -> None: + class RejectFirstValue(clingo.Propagator): + def __init__(self) -> None: + self.literal = 0 + self.rejected = 0 + + def init(self, init: clingo.PropagateInit) -> None: + atom = init.symbolic_atoms[clingo.parse_term('_se_value(variable("scalar"),val(int,1))')] + assert atom is not None + self.literal = init.solver_literal(atom.literal) + init.check_mode = clingo.PropagatorCheckMode.Total + + def check(self, control: clingo.PropagateControl) -> None: + if control.assignment.is_true(self.literal): + self.rejected += 1 + control.add_nogood([self.literal]) + + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + rejector = RejectFirstValue() + control.register_propagator(propagator) + control.register_propagator(rejector) + control.add('1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.') + control.ground() + propagator.prepare(control) + + assert control.solve(on_model=propagator.on_model).satisfiable + assert rejector.rejected > 0 + assert propagator.reasoning_strategy.rm_model == {clingo.String("scalar"): {2}} + + +@pytest.mark.parametrize( + "reasoning_mode, scalar_values, other_values", + [ + (ReasoningMode.INTERSECTION, None, None), + (ReasoningMode.UNION, {1, 2}, {4, 5}), + (ReasoningMode.SUPREMUM, {2}, {5}), + (ReasoningMode.INFIMUM, {1}, {4}), + ], +) +def test_reasoning_mode_reuses_witnesses_after_cleanup_and_additional_grounding( + reasoning_mode: ReasoningMode, scalar_values: set[int] | None, other_values: set[int] | None +) -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(reasoning_mode) + control.register_propagator(propagator) + control.add('1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.') + control.ground() + scalar = clingo.String("scalar") + other = clingo.String("other") + propagator.prepare(control) + witnesses = propagator._witnesses.copy() + assert len(witnesses) == 1 + + for _ in range(2): + propagator.prepare(control) + assert propagator._witnesses == witnesses + assert control.solve(on_model=propagator.on_model).satisfiable + expected = {} if scalar_values is None else {scalar: scalar_values} + assert propagator.reasoning_strategy.rm_model == expected + control.cleanup() + + control.add("extra", [], '1 { _se_value(variable("other"), val(int, 4..5)) } 1.') + control.ground([("extra", [])]) + propagator.prepare(control) + assert len(propagator._witnesses) == 2 + assert propagator._witnesses[scalar] == witnesses[scalar] + assert control.solve(on_model=propagator.on_model).satisfiable + expected = {} if scalar_values is None else {scalar: scalar_values, other: other_values} + assert propagator.reasoning_strategy.rm_model == expected + + +@pytest.mark.xfail(reason="Standard mode currently leaves aggregate witness choices unconstrained") +def test_reasoning_mode_propagator_switches_modes_between_solves() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + control.register_propagator(propagator) + control.add("base", [], '1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.') + control.ground([("base", [])]) + + def solve_in_mode(mode: ReasoningMode) -> list[dict[clingo.Symbol, set[object]]]: + propagator.set_mode(mode) + reported: list[dict[clingo.Symbol, set[object]]] = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + reported.append({name: values.copy() for name, values in propagator.reasoning_strategy.rm_model.items()}) + + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable + return reported + + scalar = clingo.String("scalar") + union_models = solve_in_mode(ReasoningMode.UNION) + assert len(union_models) == 2 + assert union_models[-1] == {scalar: {1, 2}} + + intersection_models = solve_in_mode(ReasoningMode.INTERSECTION) + assert len(intersection_models) == 2 + assert intersection_models[-1] == {} + + standard_models = solve_in_mode(ReasoningMode.STANDARD) + assert len(standard_models) == 2 + assert standard_models[-1] == {} + + union_models = solve_in_mode(ReasoningMode.UNION) + assert len(union_models) == 2 + assert union_models[-1] == {scalar: {1, 2}} + + +@pytest.mark.parametrize("callback_style", ["keyword", "positional", "yield", "none", "limit"]) +@pytest.mark.parametrize("early_stop", [False, True]) +def test_reasoning_mode_wrapper_updates_output_before_user_callback(callback_style: str, early_stop: bool) -> None: + control = clingo.Control(["1" if callback_style == "limit" else "0"]) + add_to_control(control, engine=engine.compile, reasoning_mode=ReasoningMode.UNION) + control.add("variable_declare(a,fromFacts). variable_domain(a,val(int,1..2)).") + control.ground() + seen: set[int] = set() + reported: list[set[int]] = [] + + def on_model(model: clingo.Model) -> bool: + current = { + atom.arguments[1].arguments[1].number + for atom in model.symbols(atoms=True, theory=True) + if atom.name == "value" and str(atom.arguments[0]) == "a" + } + accumulated = { + atom.arguments[1].arguments[1].number + for atom in model.symbols(theory=True) + if atom.name == "model_union" and str(atom.arguments[0]) == "a" + } + assert len(current) == 1 + seen.update(current) + assert accumulated == seen + reported.append(accumulated) + return not early_stop + + for _ in range(2): + seen.clear() + reported.clear() + if callback_style in {"keyword", "limit"}: + solved = control.solve(on_model=on_model) + elif callback_style == "positional": + solved = control.solve([], on_model) + elif callback_style == "yield": + with control.solve(yield_=True) as handle: + for model in handle: + if not on_model(model): + handle.cancel() + break + solved = handle.get() + else: + solved = control.solve() + assert control.statistics["summary"]["models"]["enumerated"] == 2 + assert solved.satisfiable + if callback_style != "none": + assert len(reported) == (1 if early_stop or callback_style == "limit" else 2) + if not early_stop and callback_style != "limit": + assert seen == {1, 2} + + +@pytest.mark.parametrize( + "reasoning_mode, output_name, expected_value", + [ + (ReasoningMode.SUPREMUM, "model_supremum", 2), + (ReasoningMode.INFIMUM, "model_infimum", 1), + ], +) +def test_reasoning_mode_wrapper_emits_extremum_atoms_before_user_callback( + reasoning_mode: ReasoningMode, output_name: str, expected_value: int +) -> None: + control = clingo.Control(["0"]) + add_to_control(control, engine=engine.compile, reasoning_mode=reasoning_mode) + control.add("base", [], "variable_declare(a,fromFacts). variable_domain(a,val(int,1..2)).") + control.ground() + reported: list[set[clingo.Symbol]] = [] + + def on_model(model: clingo.Model) -> None: + reported.append({atom for atom in model.symbols(theory=True) if atom.name == output_name}) + + assert control.solve(on_model=on_model).satisfiable + assert reported + assert reported[-1] == {clingo.parse_term(f"{output_name}(a,val(int,{expected_value}))")} + + +def test_standard_reasoning_mode_keeps_ordinary_enumeration() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator() + control.register_propagator(propagator) + control.add("{ auxiliary(1..3) }.") + control.ground() + propagator.prepare(control) + reported = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + reported.append(set(model.symbols(atoms=True))) + + assert control.solve(on_model=on_model).satisfiable + assert len(reported) == 8 + assert propagator._witnesses == {} + assert propagator.reasoning_strategy.rm_model == {} + + +@pytest.mark.xfail(reason="Progress guards currently prevent ordinary solving when there are no tracked variables") +@pytest.mark.parametrize( + "reasoning_mode", + [ReasoningMode.INTERSECTION, ReasoningMode.UNION, ReasoningMode.SUPREMUM, ReasoningMode.INFIMUM], +) +def test_aggregate_reasoning_modes_keep_models_without_tracked_variables(reasoning_mode: ReasoningMode) -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(reasoning_mode) + control.register_propagator(propagator) + control.add("base", [], "{ auxiliary(1..3) }.") + control.ground([("base", [])]) + reported = [] + + def on_model(model: clingo.Model) -> None: + propagator.on_model(model) + reported.append(set(model.symbols(atoms=True))) + + propagator.prepare(control) + assert control.solve(on_model=on_model).satisfiable + assert len(reported) == 8 + assert propagator.reasoning_strategy.rm_model == {} From 5f49e1dfb7e581e23eeaaa111dc5f6cfcaf3904c Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Wed, 11 Nov 2026 10:35:21 +0100 Subject: [PATCH 09/29] Fix issue when there were no tracked variables --- .../reasoning_modes/reasoning_modes_propagator.py | 6 +++++- tests/test_reasoning_mode_propagator.py | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index 558ce188d..f11162531 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -241,7 +241,8 @@ def _add_progress_guards(self, init: clingo.PropagateInit) -> None: assert self.solve_literal is not None inactive = -init.solver_literal(self.solve_literal) init.freeze_literal(-inactive) - init.add_clause([inactive, *(init.solver_literal(literal) for literal in self.variable_lit.values())]) + if self.variable_lit: + init.add_clause([inactive, *(init.solver_literal(literal) for literal in self.variable_lit.values())]) for name in self.scalar_variables: literals = set(self.value_literals[name].values()) clause = [*literals, -self.variable_lit[name]] @@ -352,6 +353,9 @@ def nogoods(self) -> list[Iterable[int]]: Returns: Nogoods that allow another model only when a retained value changes. """ + if not self.variable_lit: + return [] + nogoods: list[Iterable[int]] = [] witnesses = [] for name, helper in self.variable_lit.items(): diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index 368adfd6f..4215b54e0 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -1060,7 +1060,6 @@ def on_model(model: clingo.Model) -> None: assert propagator.reasoning_strategy.rm_model == {} -@pytest.mark.xfail(reason="Progress guards currently prevent ordinary solving when there are no tracked variables") @pytest.mark.parametrize( "reasoning_mode", [ReasoningMode.INTERSECTION, ReasoningMode.UNION, ReasoningMode.SUPREMUM, ReasoningMode.INFIMUM], From b8d6c83de1a3e43c2d4526cdb037fb946b7daf6b Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sat, 14 Nov 2026 21:37:00 +0100 Subject: [PATCH 10/29] Fix bug when no variables could get values --- .../reasoning_modes_propagator.py | 43 +++++--------- tests/test_reasoning_mode_propagator.py | 58 +++++++++++-------- 2 files changed, 51 insertions(+), 50 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index f11162531..f59588705 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -182,7 +182,6 @@ def __init__(self) -> None: self.variable_lit: dict[clingo.Symbol, int] = {} self.value_literals: dict[clingo.Symbol, dict[Any, int]] = {} self.scalar_variables: set[clingo.Symbol] = set() - self.solve_literal: int | None = None def init( self, @@ -236,18 +235,6 @@ def _init_literals( value = candidate.value self.value_literals[name][value] = candidate.literal - def _add_progress_guards(self, init: clingo.PropagateInit) -> None: - """Install static solver guards that become inactive on later solves.""" - assert self.solve_literal is not None - inactive = -init.solver_literal(self.solve_literal) - init.freeze_literal(-inactive) - if self.variable_lit: - init.add_clause([inactive, *(init.solver_literal(literal) for literal in self.variable_lit.values())]) - for name in self.scalar_variables: - literals = set(self.value_literals[name].values()) - clause = [*literals, -self.variable_lit[name]] - init.add_clause([inactive, *(init.solver_literal(literal) for literal in clause)]) - def _set_or_multimap_value_nogood(self, name: clingo.Symbol, value: Any, helper: int) -> tuple[int, ...]: """Build a nogood that matches a complete collection value and witness.""" if isinstance(value, multimap.Multimap): @@ -386,7 +373,7 @@ def init( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Initialize literals and add witness and scalar selection guards once. + """Initialize literals used to track candidate values. Args: init: Clingo initialization context for the current solve. @@ -394,7 +381,6 @@ def init( """ super().init(init, variables) self._init_literals(init, variables) - self._add_progress_guards(init) def join(self, model: dict[clingo.Symbol, object]) -> None: """Add each model value to the accumulated set of values. @@ -433,10 +419,9 @@ def init( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Reset bounds and require at least one progress witness.""" + """Reset accumulated bounds and initialize candidate literals.""" super().init(init, variables) self._init_literals(init, variables) - self._add_progress_guards(init) def join(self, model: dict[clingo.Symbol, object]) -> None: """Accumulate the least upper bound of a model's variable values. @@ -505,10 +490,9 @@ def init( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Reset bounds and require at least one progress witness.""" + """Reset accumulated bounds and initialize candidate literals.""" super().init(init, variables) self._init_literals(init, variables) - self._add_progress_guards(init) def join(self, model: dict[clingo.Symbol, object]) -> None: """Accumulate the greatest lower bound of a model's variable values. @@ -597,7 +581,6 @@ def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> No self.reasoning_strategy: ReasoningStrategy = REASONING_STRATEGIES[reasoning_mode]() self._variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = {} self._witnesses: dict[clingo.Symbol, int] = {} - self._solve_literal: int | None = None self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) @@ -617,9 +600,6 @@ def prepare(self, control: clingo.Control) -> None: Args: control: Grounded control whose next solve will use this strategy. """ - if self._solve_literal is not None: - control.release_external(self._solve_literal) - self._solve_literal = None if self.disabled: return self._variables.clear() @@ -658,10 +638,7 @@ def prepare(self, control: clingo.Control) -> None: helper = backend.add_atom() backend.add_rule([helper], choice=True) self._witnesses[name] = helper - self._solve_literal = backend.add_atom() - backend.add_external(self._solve_literal, clingo.TruthValue.True_) self.reasoning_strategy.variable_lit = {name: self._witnesses[name] for name in self._variables} - self.reasoning_strategy.solve_literal = self._solve_literal def init(self, init: clingo.PropagateInit) -> None: """Reset accumulation and initialize guards for the current solve.""" @@ -682,7 +659,19 @@ def on_model(self, model: clingo.Model) -> None: variable.update(model) values = {variable.name: variable.value for variable in self._variables.values() if _has_value(variable)} self.reasoning_strategy.join(values) - for nogood in self.reasoning_strategy.nogoods(): + nogoods = self.reasoning_strategy.nogoods() + for name, variable in self._variables.items(): + if isinstance(variable, _ScalarVariable): + candidate_literals = (candidate.literal for candidate in variable.possible_values) + nogoods.append( + ( + self.reasoning_strategy.variable_lit[name], + *(-literal for literal in candidate_literals), + ) + ) + if self._variables: + nogoods.append(tuple(-helper for helper in self.reasoning_strategy.variable_lit.values())) + for nogood in nogoods: model.context.add_nogood(tuple(nogood)) diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index 4215b54e0..b3506d80e 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -183,18 +183,17 @@ def test_supremum_and_infimum_join_multimap_values() -> None: @pytest.mark.parametrize("mode_type", [UnionReasoningMode, SupremumReasoningMode, InfimumReasoningMode]) -def test_reasoning_mode_translates_program_literals_for_guards(mode_type: type[ReasoningStrategy]) -> None: +def test_reasoning_mode_initializes_progress_witness(mode_type: type[ReasoningStrategy]) -> None: name = clingo.String("value") variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = { name: _ScalarVariable(name, [_Value(1, 1)]) } mode = mode_type() mode.variable_lit = {name: 2} - mode.solve_literal = 3 init = _InitRecorder() mode.init(cast(clingo.PropagateInit, init), variables) - assert init.frozen == [102, 103] - assert init.clauses == [(-103, 102), (-103, 101, -102)] + assert init.frozen == [102] + assert init.clauses == [] assert mode.variable_lit == {name: 2} assert mode.value_literals == {name: {1: 1}} @@ -782,9 +781,9 @@ def on_model(model: clingo.Model) -> None: @pytest.mark.parametrize("reasoning_mode", [ReasoningMode.SUPREMUM, ReasoningMode.INFIMUM]) @pytest.mark.parametrize( - "program, expected_supremum, expected_infimum, max_models", + "program, expected_supremum, expected_infimum, expected_satisfiable, max_models, expected_model_count", [ - ('_se_value(variable("value"), val(string, "same")).', {"same"}, {"same"}, 1), + ('_se_value(variable("value"), val(string, "same")).', {"same"}, {"same"}, True, 1, None), ( ( '1 { _se_value(variable("value"), val(string, "left")); ' @@ -792,45 +791,54 @@ def on_model(model: clingo.Model) -> None: ), {"TOP"}, {"BOT"}, + True, 2, + None, ), ( ('1 { _se_value(variable("value"), val(int, 3)); _se_value(variable("value"), val(string, "text")) } 1.'), {"TOP"}, {"BOT"}, + True, 2, + None, ), - ('{ _se_value(variable("value"), val(int, 1..3)) } 1.', {3}, {1}, 4), + ('{ _se_value(variable("value"), val(int, 1..3)) } 1.', {3}, {1}, True, 4, None), ( ('{ _se_value(variable("value"), val(int, 1)) }. :- _se_value(variable("value"), val(int, 1)).'), + set(), + set(), + True, + 1, + 1, + ), + ( + '_se_value(variable("value"), ref(set, variable("value"))).', + {frozenset()}, + {frozenset()}, + True, + 1, None, - None, - 0, ), - ('_se_value(variable("value"), ref(set, variable("value"))).', {frozenset()}, {frozenset()}, 1), ( '_se_value(variable("value"), ref(multimap, variable("value"))).', {multimap.Multimap.from_pairs([])}, {multimap.Multimap.from_pairs([])}, + True, 1, + None, ), - pytest.param( - "", - set(), - set(), - 32, - marks=pytest.mark.xfail( - reason="Progress guards currently make aggregate modes UNSAT with no tracked variables" - ), - ), + ("", set(), set(), True, 32, 32), ], ) def test_extremum_propagator_scalar_and_empty_domains( reasoning_mode: ReasoningMode, program: str, - expected_supremum: set[object] | None, - expected_infimum: set[object] | None, + expected_supremum: set[object], + expected_infimum: set[object], + expected_satisfiable: bool, max_models: int, + expected_model_count: int | None, ) -> None: control = clingo.Control(["0"]) propagator = ReasoningModesPropagator(reasoning_mode) @@ -847,12 +855,16 @@ def on_model(model: clingo.Model) -> None: for _ in range(2): accumulated.clear() propagator.prepare(control) - assert control.solve(on_model=on_model).satisfiable == (expected is not None) - assert bool(accumulated) == (expected is not None) + assert control.solve(on_model=on_model).satisfiable is expected_satisfiable + assert bool(accumulated) is expected_satisfiable assert len(accumulated) <= max_models + if expected_model_count is not None: + assert len(accumulated) == expected_model_count if expected: assert all(previous != current for previous, current in pairwise(accumulated)) expected_model = {} if not expected else {clingo.String("value"): expected} + if not expected: + assert all(not model for model in accumulated) assert propagator.reasoning_strategy.rm_model == expected_model From 360c24a6b7860ceab3b10e15ec304cb2c4a3b3da Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 19:18:06 +0100 Subject: [PATCH 11/29] Add testing framework for new reasoning modes --- DEVELOPMENT.md | 4 +- .../core/reasoning_modes.expected.infimum | 6 +++ .../reasoning_modes.expected.intersection | 1 + .../core/reasoning_modes.expected.supremum | 6 +++ .../core/reasoning_modes.expected.union | 15 +++++++ .../reasoning_modes_sets.expected.infimum | 1 + ...reasoning_modes_sets.expected.intersection | 1 + .../reasoning_modes_sets.expected.supremum | 1 + .../core/reasoning_modes_sets.expected.union | 4 ++ ...reasoning_modes_with_show.expected.infimum | 6 +++ ...ning_modes_with_show.expected.intersection | 1 + ...easoning_modes_with_show.expected.supremum | 6 +++ .../reasoning_modes_with_show.expected.union | 15 +++++++ tests/flat_ch/test_correctness.py | 4 +- tests/test_encoding.py | 8 ++-- tests/utils/testing.py | 39 +++++++++++++------ 16 files changed, 99 insertions(+), 19 deletions(-) create mode 100644 tests/correctness/core/reasoning_modes.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes.expected.intersection create mode 100644 tests/correctness/core/reasoning_modes.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes.expected.union create mode 100644 tests/correctness/core/reasoning_modes_sets.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_sets.expected.intersection create mode 100644 tests/correctness/core/reasoning_modes_sets.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_sets.expected.union create mode 100644 tests/correctness/core/reasoning_modes_with_show.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_with_show.expected.intersection create mode 100644 tests/correctness/core/reasoning_modes_with_show.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_with_show.expected.union diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 1256d709d..98478b6de 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -97,8 +97,8 @@ The supported suffixes are: last model respectively. - `none`: atom must occur in no model; it does not assert that the program is unsatisfiable. -- `brave` and `cautious`: atom must occur in the final model with the matching - enumeration mode. +- `brave` `cautious`, `union`, `intersection`, `supremum`, and `infimum`: atom + must occur in the final model with the matching enumeration mode. - `optall`, `optany`, and `optnone`: atom must occur in every, any, or no optimal model respectively. - `stats`: one `key=value` entry per line. `models=` asserts the exact diff --git a/tests/correctness/core/reasoning_modes.expected.infimum b/tests/correctness/core/reasoning_modes.expected.infimum new file mode 100644 index 000000000..9fedd7b1a --- /dev/null +++ b/tests/correctness/core/reasoning_modes.expected.infimum @@ -0,0 +1,6 @@ +model_infimum(a,val(int,1)) +model_infimum(b,val(int,1)) +model_infimum(c,val(bool,true)) +model_infimum(s1,set(())) +model_infimum(s2,set((val(int,1),()))) +model_infimum(m1,multimap(((val(int,2),(val(int,1),())),()),())) diff --git a/tests/correctness/core/reasoning_modes.expected.intersection b/tests/correctness/core/reasoning_modes.expected.intersection new file mode 100644 index 000000000..92087a4a3 --- /dev/null +++ b/tests/correctness/core/reasoning_modes.expected.intersection @@ -0,0 +1 @@ +model_intersection(c,val(bool,true)) diff --git a/tests/correctness/core/reasoning_modes.expected.supremum b/tests/correctness/core/reasoning_modes.expected.supremum new file mode 100644 index 000000000..7caac966b --- /dev/null +++ b/tests/correctness/core/reasoning_modes.expected.supremum @@ -0,0 +1,6 @@ +model_supremum(a,val(int,2)) +model_supremum(b,val(int,2)) +model_supremum(c,val(bool,true)) +model_supremum(s1,set((val(int,1),(val(int,2),())))) +model_supremum(s2,set((val(int,1),(val(int,2),())))) +model_supremum(m1,multimap(((val(int,1),(val(int,1),(val(int,2),()))),((val(int,2),(val(int,1),())),())),())) diff --git a/tests/correctness/core/reasoning_modes.expected.union b/tests/correctness/core/reasoning_modes.expected.union new file mode 100644 index 000000000..ed130b009 --- /dev/null +++ b/tests/correctness/core/reasoning_modes.expected.union @@ -0,0 +1,15 @@ +model_union(a,val(int,1)) +model_union(a,val(int,2)) +model_union(b,val(int,1)) +model_union(b,val(int,2)) +model_union(c,val(bool,true)) +model_union(s1,set(())) +model_union(s1,set((val(int,1),()))) +model_union(s1,set((val(int,2),()))) +model_union(s1,set((val(int,1),(val(int,2),())))) +model_union(s2,set((val(int,1),()))) +model_union(s2,set((val(int,1),(val(int,2),())))) +model_union(m1,multimap(((val(int,2),(val(int,1),())),()),())) +model_union(m1,multimap(((val(int,1),(val(int,1),())),((val(int,2),(val(int,1),())),())),())) +model_union(m1,multimap(((val(int,1),(val(int,2),())),((val(int,2),(val(int,1),())),())),())) +model_union(m1,multimap(((val(int,1),(val(int,1),(val(int,2),()))),((val(int,2),(val(int,1),())),())),())) diff --git a/tests/correctness/core/reasoning_modes_sets.expected.infimum b/tests/correctness/core/reasoning_modes_sets.expected.infimum new file mode 100644 index 000000000..b368a68ca --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets.expected.infimum @@ -0,0 +1 @@ +model_infimum(s,set((val(int,1),()))) diff --git a/tests/correctness/core/reasoning_modes_sets.expected.intersection b/tests/correctness/core/reasoning_modes_sets.expected.intersection new file mode 100644 index 000000000..31abac5df --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets.expected.intersection @@ -0,0 +1 @@ +model_supremum(s,set()) diff --git a/tests/correctness/core/reasoning_modes_sets.expected.supremum b/tests/correctness/core/reasoning_modes_sets.expected.supremum new file mode 100644 index 000000000..d98aaf331 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets.expected.supremum @@ -0,0 +1 @@ +model_supremum(s,set((val(int,1),(val(int,2),(val(int,3),()))))) diff --git a/tests/correctness/core/reasoning_modes_sets.expected.union b/tests/correctness/core/reasoning_modes_sets.expected.union new file mode 100644 index 000000000..9460de2c0 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets.expected.union @@ -0,0 +1,4 @@ +model_union(s,set((val(int,1),()))) +model_union(s,set((val(int,1),(val(int,2),())))) +model_union(s,set((val(int,1),(val(int,3),())))) +model_union(s,set((val(int,1),(val(int,2),(val(int,3),()))))) diff --git a/tests/correctness/core/reasoning_modes_with_show.expected.infimum b/tests/correctness/core/reasoning_modes_with_show.expected.infimum new file mode 100644 index 000000000..9fedd7b1a --- /dev/null +++ b/tests/correctness/core/reasoning_modes_with_show.expected.infimum @@ -0,0 +1,6 @@ +model_infimum(a,val(int,1)) +model_infimum(b,val(int,1)) +model_infimum(c,val(bool,true)) +model_infimum(s1,set(())) +model_infimum(s2,set((val(int,1),()))) +model_infimum(m1,multimap(((val(int,2),(val(int,1),())),()),())) diff --git a/tests/correctness/core/reasoning_modes_with_show.expected.intersection b/tests/correctness/core/reasoning_modes_with_show.expected.intersection new file mode 100644 index 000000000..92087a4a3 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_with_show.expected.intersection @@ -0,0 +1 @@ +model_intersection(c,val(bool,true)) diff --git a/tests/correctness/core/reasoning_modes_with_show.expected.supremum b/tests/correctness/core/reasoning_modes_with_show.expected.supremum new file mode 100644 index 000000000..7caac966b --- /dev/null +++ b/tests/correctness/core/reasoning_modes_with_show.expected.supremum @@ -0,0 +1,6 @@ +model_supremum(a,val(int,2)) +model_supremum(b,val(int,2)) +model_supremum(c,val(bool,true)) +model_supremum(s1,set((val(int,1),(val(int,2),())))) +model_supremum(s2,set((val(int,1),(val(int,2),())))) +model_supremum(m1,multimap(((val(int,1),(val(int,1),(val(int,2),()))),((val(int,2),(val(int,1),())),())),())) diff --git a/tests/correctness/core/reasoning_modes_with_show.expected.union b/tests/correctness/core/reasoning_modes_with_show.expected.union new file mode 100644 index 000000000..ed130b009 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_with_show.expected.union @@ -0,0 +1,15 @@ +model_union(a,val(int,1)) +model_union(a,val(int,2)) +model_union(b,val(int,1)) +model_union(b,val(int,2)) +model_union(c,val(bool,true)) +model_union(s1,set(())) +model_union(s1,set((val(int,1),()))) +model_union(s1,set((val(int,2),()))) +model_union(s1,set((val(int,1),(val(int,2),())))) +model_union(s2,set((val(int,1),()))) +model_union(s2,set((val(int,1),(val(int,2),())))) +model_union(m1,multimap(((val(int,2),(val(int,1),())),()),())) +model_union(m1,multimap(((val(int,1),(val(int,1),())),((val(int,2),(val(int,1),())),())),())) +model_union(m1,multimap(((val(int,1),(val(int,2),())),((val(int,2),(val(int,1),())),())),())) +model_union(m1,multimap(((val(int,1),(val(int,1),(val(int,2),()))),((val(int,2),(val(int,1),())),())),())) diff --git a/tests/flat_ch/test_correctness.py b/tests/flat_ch/test_correctness.py index 1cabe8ce3..daf4bacd5 100644 --- a/tests/flat_ch/test_correctness.py +++ b/tests/flat_ch/test_correctness.py @@ -300,8 +300,8 @@ def solve_with_flat_ch(name: str, test, extra_args: list[str]): def run_test(name: str): file_name = "tests/correctness/" + name - for test, extra_args in chut.build_expectations(file_name): - solve_with_flat_ch(file_name, test, extra_args) + for test, extra_options in chut.build_expectations(file_name): + solve_with_flat_ch(file_name, test, extra_options.clingo_options) test.assert_() diff --git a/tests/test_encoding.py b/tests/test_encoding.py index 25eccbb2c..d9c212afe 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -26,9 +26,11 @@ def run_test(name: str, selected_engine: engine.Engine): name = "tests/correctness/" + name expectations = chut.build_expectations(name) assert expectations, f"Missing expectations: {name}" - for test, extra_args in expectations: - options = ctrl_options + extra_args - solver = chut.Solver(options, files=[name + ".lp"], engine=selected_engine) + for test, extra_options in expectations: + options = ctrl_options + extra_options.clingo_options + solver = chut.Solver( + options, files=[name + ".lp"], engine=selected_engine, add_to_ctl_options=extra_options.add_to_ctl_options + ) solver.solve(test) test.assert_() diff --git a/tests/utils/testing.py b/tests/utils/testing.py index 574a31f6a..4333abb87 100644 --- a/tests/utils/testing.py +++ b/tests/utils/testing.py @@ -1,5 +1,5 @@ import os -from typing import Optional, Sequence, Union +from dataclasses import dataclass, field import clingo import clintest.assertion @@ -13,6 +13,13 @@ import constraint_handler from constraint_handler.engine import Engine, compile from constraint_handler.propagator.PropagatorConstants import OPTIMIZATION_STAGE_ATOM +from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningMode + + +@dataclass +class TestingOptions: + clingo_options: list[str] = field(default_factory=list) + add_to_ctl_options: dict[str, ReasoningMode] = field(default_factory=dict) def atoms_from_file(file_name: str) -> list[clingo.Symbol]: @@ -44,7 +51,7 @@ def absent(atom): return clintest.assertion.Not(clintest.assertion.Or(clintest.assertion.Contains(atom), TheoryContains(atom))) -def build_expectations(name) -> list[tuple[clintest.test.Test, list[str]]]: +def build_expectations(name) -> list[tuple[clintest.test.Test, TestingOptions]]: name = name + ".expected." tests = [] @@ -75,15 +82,20 @@ def build_expectations(name) -> list[tuple[clintest.test.Test, list[str]]]: test_noargs.append(satisfiable) if test_noargs: - tests.append((clintest.test.And(*test_noargs), [])) + tests.append((clintest.test.And(*test_noargs), TestingOptions())) test_brave = [clintest.test.Assert(Last(), contains(atom)) for atom in atoms_from_file(name + "brave")] if test_brave: - tests.append((clintest.test.And(*test_brave), ["--enum-mode=brave"])) + tests.append((clintest.test.And(*test_brave), TestingOptions(clingo_options=["--enum-mode=brave"]))) test_cautious = [clintest.test.Assert(Last(), contains(atom)) for atom in atoms_from_file(name + "cautious")] if test_cautious: - tests.append((clintest.test.And(*test_cautious), ["--enum-mode=cautious"])) + tests.append((clintest.test.And(*test_cautious), TestingOptions(clingo_options=["--enum-mode=cautious"]))) + + for mode in (ReasoningMode.UNION, ReasoningMode.INTERSECTION, ReasoningMode.SUPREMUM, ReasoningMode.INFIMUM): + test_mode = [clintest.test.Assert(Last(), contains(atom)) for atom in atoms_from_file(name + mode.name.lower())] + if test_mode: + tests.append((clintest.test.And(*test_mode), TestingOptions(add_to_ctl_options={"reasoning_mode": mode}))) test_optimize = [] for atom in atoms_from_file(name + "optall"): @@ -93,13 +105,13 @@ def build_expectations(name) -> list[tuple[clintest.test.Test, list[str]]]: for atom in atoms_from_file(name + "optnone"): test_optimize.append(AssertOptimal(All(), absent(atom))) if test_optimize: - tests.append((clintest.test.And(*test_optimize), ["--opt-mode=optN"])) + tests.append((clintest.test.And(*test_optimize), TestingOptions(clingo_options=["--opt-mode=optN"]))) return tests class TheoryContains(clintest.assertion.Assertion): - def __init__(self, symbol: Union[clingo.Symbol, str]) -> None: + def __init__(self, symbol: clingo.Symbol | str) -> None: self.__symbol = symbol def __repr__(self): @@ -150,15 +162,17 @@ def outcome(self) -> Outcome: class Solver(clintest.solver.Solver): def __init__( self, - arguments: Optional[Sequence[str]] = None, - program: Optional[str] = None, - files: Optional[Sequence[str]] = None, + arguments: Sequence[str] | None = None, + program: str | None = None, + files: Sequence[str] | None = None, engine: Engine = compile, + add_to_ctl_options: dict[str, ReasoningMode] | None = None, ) -> None: self.__arguments = [] if arguments is None else arguments self.__program = "" if program is None else program self.__files = [] if files is None else files self.__engine = engine + self.__add_to_ctl_options = {} if add_to_ctl_options is None else add_to_ctl_options def solve(self, test: clintest.test.Test) -> None: if test.outcome().is_certain(): @@ -166,7 +180,7 @@ def solve(self, test: clintest.test.Test) -> None: ctl = clingo.Control(self.__arguments) - constraint_handler.add_to_control(ctl, engine=self.__engine) + constraint_handler.add_to_control(ctl, engine=self.__engine, **self.__add_to_ctl_options) ctl.add(self.__program) for file_name in self.__files: @@ -188,4 +202,5 @@ def __repr__(self): program = repr(self.__program) files = repr(self.__files) engine = repr(self.__engine) - return f"{name}({arguments}, {program}, {files}, {engine})" + add_to_ctl_options = repr(self.__add_to_ctl_options) + return f"{name}({arguments}, {program}, {files}, {engine}, {add_to_ctl_options})" From 51e4266b77c3b5b9e2cf1ec6c6283e8893d9db4e Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 19:42:10 +0100 Subject: [PATCH 12/29] Fix bug and typo --- .../correctness/core/reasoning_modes_sets.expected.intersection | 2 +- tests/utils/testing.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/correctness/core/reasoning_modes_sets.expected.intersection b/tests/correctness/core/reasoning_modes_sets.expected.intersection index 31abac5df..beb16314f 100644 --- a/tests/correctness/core/reasoning_modes_sets.expected.intersection +++ b/tests/correctness/core/reasoning_modes_sets.expected.intersection @@ -1 +1 @@ -model_supremum(s,set()) +model_infimum(s,set()) diff --git a/tests/utils/testing.py b/tests/utils/testing.py index 4333abb87..6f2dacce5 100644 --- a/tests/utils/testing.py +++ b/tests/utils/testing.py @@ -1,4 +1,5 @@ import os +from collections.abc import Sequence from dataclasses import dataclass, field import clingo From 02a7654d18021c415941aa83110af415ec2f335b Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 19:45:34 +0100 Subject: [PATCH 13/29] delete test since file should contain nothing --- .../correctness/core/reasoning_modes_sets.expected.intersection | 1 - 1 file changed, 1 deletion(-) delete mode 100644 tests/correctness/core/reasoning_modes_sets.expected.intersection diff --git a/tests/correctness/core/reasoning_modes_sets.expected.intersection b/tests/correctness/core/reasoning_modes_sets.expected.intersection deleted file mode 100644 index beb16314f..000000000 --- a/tests/correctness/core/reasoning_modes_sets.expected.intersection +++ /dev/null @@ -1 +0,0 @@ -model_infimum(s,set()) From 648c59f199b9541e750bca66a3225c62937ead9e Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 19:50:11 +0100 Subject: [PATCH 14/29] Add xfails for propagator and compile2 --- tests/test_encoding.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_encoding.py b/tests/test_encoding.py index d9c212afe..0a7c2a6e6 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -575,6 +575,7 @@ def run_test(name: str, selected_engine: engine.Engine): "core/empty_set_execution", "core/reasoning_modes", # multimap "core/reasoning_modes_with_show", + "core/reasoning_modes_sets", # new modes "datatype/bool/conj_disj_mixed", "datatype/float/mult/recovery", "datatype/float/pow/mixed", @@ -661,6 +662,8 @@ def run_test(name: str, selected_engine: engine.Engine): "core/conditional_declare_definition", "core/conditional_declare_set_multiple", "core/reasoning_modes_with_show", + "core/reasoning_modes_sets", # new modes + "core/reasoning_modes", # new modes "datatype/bool/conj_disj_mixed", "datatype/float/mult/recovery", "default/basic_true", From eb369c8ab93be1d8c4c15e2a0ea3aa162c50f513 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 20:00:21 +0100 Subject: [PATCH 15/29] delete rogue import --- src/constraint_handler/post_processor.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/constraint_handler/post_processor.py b/src/constraint_handler/post_processor.py index 25368cfe5..9290716b4 100644 --- a/src/constraint_handler/post_processor.py +++ b/src/constraint_handler/post_processor.py @@ -5,7 +5,6 @@ from typing import Any import clingo -from mypy.server.update import propagate_changes_using_dependencies import constraint_handler.evaluator as evaluator import constraint_handler.myClorm as myClorm From 61235b91d6c732e6d34f39fc827941f6143a999c Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 23:11:04 +0100 Subject: [PATCH 16/29] top and bot are in an enum --- src/constraint_handler/post_processor.py | 8 +- .../reasoning_modes_propagator.py | 9 ++- tests/test_reasoning_mode_propagator.py | 77 ++++++++++++++----- 3 files changed, 71 insertions(+), 23 deletions(-) diff --git a/src/constraint_handler/post_processor.py b/src/constraint_handler/post_processor.py index 9290716b4..485dd94d6 100644 --- a/src/constraint_handler/post_processor.py +++ b/src/constraint_handler/post_processor.py @@ -11,7 +11,11 @@ import constraint_handler.schemas.result as result import constraint_handler.schemas.warning as warning from constraint_handler import multimap -from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningMode, ReasoningModesPropagator +from constraint_handler.reasoning_modes.reasoning_modes_propagator import ( + ReasoningMode, + ReasoningModesPropagator, + _LatticeBound, +) class OptimizePostProcessingPropagator(clingo.Propagator): @@ -152,6 +156,8 @@ def extend_with_reasoning_mode_atoms(propagator: ReasoningModesPropagator, model if isinstance(value, multimap.Multimap): value_symbol = _multimap_symbol(value) else: + if isinstance(value, _LatticeBound): + value = value.value reduced_value, _ = evaluator.reducedExpr(value) value_symbol = myClorm.pytocl(reduced_value) symbols.add(clingo.Function(f"model_{propagator.reasoning_mode.name.lower()}", [variable, value_symbol])) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index f59588705..6b01f9486 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -28,6 +28,11 @@ class ReasoningMode(Enum): INFIMUM = 7 +class _LatticeBound(Enum): + TOP = "TOP" + BOT = "BOT" + + @dataclass class _Value: """Associate a program literal with a possible variable value. @@ -458,7 +463,7 @@ def _supremum(left: Any, right: Any) -> Any: pairs.append((key, value)) return multimap.Multimap.from_pairs(pairs) if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): - return left if left == right else "TOP" + return left if left == right else _LatticeBound.TOP return max(left, right) def nogoods(self) -> list[Iterable[int]]: @@ -526,7 +531,7 @@ def _infimum(left: Any, right: Any) -> Any: (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) ) if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): - return left if left == right else "BOT" + return left if left == right else _LatticeBound.BOT return min(left, right) def nogoods(self) -> list[Iterable[int]]: diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index b3506d80e..b77bbdbe0 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -16,6 +16,7 @@ ReasoningStrategy, SupremumReasoningMode, UnionReasoningMode, + _LatticeBound, _MultimapVariable, _PairValue, _ScalarVariable, @@ -88,6 +89,28 @@ def test_extend_reasoning_mode_atoms_emits_each_scalar_value() -> None: } +@pytest.mark.parametrize( + "strategy_type, reasoning_mode, expected_value", + [ + (SupremumReasoningMode, ReasoningMode.SUPREMUM, "TOP"), + (InfimumReasoningMode, ReasoningMode.INFIMUM, "BOT"), + ], +) +def test_extend_reasoning_mode_atoms_serializes_lattice_bounds_as_strings( + strategy_type: type[ReasoningStrategy], reasoning_mode: ReasoningMode, expected_value: str +) -> None: + variable = clingo.String("value") + strategy = strategy_type() + strategy.join({variable: "left"}) + strategy.join({variable: "right"}) + + symbols = _extend(strategy.rm_model, reasoning_mode) + + assert symbols == { + clingo.parse_term(f'model_{reasoning_mode.name.lower()}("value",val(string,"{expected_value}"))') + } + + def test_extend_reasoning_mode_atoms_encodes_whole_set_values() -> None: variable = clingo.String("items") @@ -202,13 +225,19 @@ def test_reasoning_mode_initializes_progress_witness(mode_type: type[ReasoningSt "left, right, expected", [ ("same", "same", "same"), - ("left", "right", "TOP"), - (3, "text", "TOP"), - ("text", 3, "TOP"), - pytest.param(True, 1, "TOP", marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1")), - ("TOP", 3, "TOP"), - (3, "TOP", "TOP"), - ("TOP", "text", "TOP"), + ("TOP", "TOP", "TOP"), + ("left", "right", _LatticeBound.TOP), + (3, "text", _LatticeBound.TOP), + ("text", 3, _LatticeBound.TOP), + pytest.param( + True, + 1, + _LatticeBound.TOP, + marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1"), + ), + ("TOP", 3, _LatticeBound.TOP), + (3, "TOP", _LatticeBound.TOP), + ("TOP", "text", _LatticeBound.TOP), ], ) def test_supremum_joins_nonnumeric_values(left: object, right: object, expected: object) -> None: @@ -227,7 +256,8 @@ def test_supremum_joins_nonnumeric_values(left: object, right: object, expected: (False, [False, True], [False]), (True, [False, True], [False, True]), ("same", ["same", "other", 3], ["same"]), - ("TOP", ["same", "TOP", 3], ["same", "TOP", 3]), + (_LatticeBound.TOP, ["same", "TOP", 3], ["same", "TOP", 3]), + ("TOP", ["same", "TOP", 3], ["TOP"]), (3, [2, 3, "text"], [2, 3]), ], ) @@ -280,13 +310,19 @@ def test_supremum_collection_nogoods_require_unseen_members(members: frozenset[i "left, right, expected", [ ("same", "same", "same"), - ("left", "right", "BOT"), - (3, "text", "BOT"), - ("text", 3, "BOT"), - pytest.param(True, 1, "BOT", marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1")), - ("BOT", 3, "BOT"), - (3, "BOT", "BOT"), - ("BOT", "text", "BOT"), + ("BOT", "BOT", "BOT"), + ("left", "right", _LatticeBound.BOT), + (3, "text", _LatticeBound.BOT), + ("text", 3, _LatticeBound.BOT), + pytest.param( + True, + 1, + _LatticeBound.BOT, + marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1"), + ), + ("BOT", 3, _LatticeBound.BOT), + (3, "BOT", _LatticeBound.BOT), + ("BOT", "text", _LatticeBound.BOT), ], ) def test_infimum_joins_nonnumeric_values(left: object, right: object, expected: object) -> None: @@ -305,7 +341,8 @@ def test_infimum_joins_nonnumeric_values(left: object, right: object, expected: (False, [False, True], [False, True]), (True, [False, True], [True]), ("same", ["same", "other", 3], ["same"]), - ("BOT", ["same", "BOT", 3], ["same", "BOT", 3]), + (_LatticeBound.BOT, ["same", "BOT", 3], ["same", "BOT", 3]), + ("BOT", ["same", "BOT", 3], ["BOT"]), (3, [2, 3, "text"], [3]), ], ) @@ -789,16 +826,16 @@ def on_model(model: clingo.Model) -> None: '1 { _se_value(variable("value"), val(string, "left")); ' '_se_value(variable("value"), val(string, "right")) } 1.' ), - {"TOP"}, - {"BOT"}, + {_LatticeBound.TOP}, + {_LatticeBound.BOT}, True, 2, None, ), ( ('1 { _se_value(variable("value"), val(int, 3)); _se_value(variable("value"), val(string, "text")) } 1.'), - {"TOP"}, - {"BOT"}, + {_LatticeBound.TOP}, + {_LatticeBound.BOT}, True, 2, None, From 44a71db24d4e0da4380f2109dd8cc34ae669e45e Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 23:24:25 +0100 Subject: [PATCH 17/29] use logical OR and AND for supremum and infimum when both values are boolean --- .../reasoning_modes_propagator.py | 8 +++ tests/test_reasoning_mode_propagator.py | 53 ++++++++++++++----- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index 6b01f9486..1d64632fc 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -462,6 +462,10 @@ def _supremum(left: Any, right: Any) -> Any: for value in values: pairs.append((key, value)) return multimap.Multimap.from_pairs(pairs) + if isinstance(left, bool) and isinstance(right, bool): + return left or right + if isinstance(left, bool) or isinstance(right, bool): + return _LatticeBound.TOP if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): return left if left == right else _LatticeBound.TOP return max(left, right) @@ -530,6 +534,10 @@ def _infimum(left: Any, right: Any) -> Any: return multimap.Multimap.from_pairs( (key, value) for key, values in left.items() for value in values & right.get(key, frozenset()) ) + if isinstance(left, bool) and isinstance(right, bool): + return left and right + if isinstance(left, bool) or isinstance(right, bool): + return _LatticeBound.BOT if not isinstance(left, (int, float)) or not isinstance(right, (int, float)): return left if left == right else _LatticeBound.BOT return min(left, right) diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index b77bbdbe0..03f9cd8a1 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -176,6 +176,34 @@ def test_infimum_reasoning_mode_joins_values() -> None: assert mode.rm_model == {variable: {3}} +@pytest.mark.parametrize( + "left, right, expected", + [(False, False, False), (False, True, True), (True, False, True), (True, True, True)], +) +def test_supremum_reasoning_mode_joins_boolean_values(left: bool, right: bool, expected: bool) -> None: + mode = SupremumReasoningMode() + variable = clingo.String("value") + + mode.join({variable: left}) + mode.join({variable: right}) + + assert mode.rm_model == {variable: {expected}} + + +@pytest.mark.parametrize( + "left, right, expected", + [(False, False, False), (False, True, False), (True, False, False), (True, True, True)], +) +def test_infimum_reasoning_mode_joins_boolean_values(left: bool, right: bool, expected: bool) -> None: + mode = InfimumReasoningMode() + variable = clingo.String("value") + + mode.join({variable: left}) + mode.join({variable: right}) + + assert mode.rm_model == {variable: {expected}} + + def test_supremum_and_infimum_join_set_values() -> None: variable = clingo.String("items") supremum = SupremumReasoningMode() @@ -229,12 +257,7 @@ def test_reasoning_mode_initializes_progress_witness(mode_type: type[ReasoningSt ("left", "right", _LatticeBound.TOP), (3, "text", _LatticeBound.TOP), ("text", 3, _LatticeBound.TOP), - pytest.param( - True, - 1, - _LatticeBound.TOP, - marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1"), - ), + (True, 1, _LatticeBound.TOP), ("TOP", 3, _LatticeBound.TOP), (3, "TOP", _LatticeBound.TOP), ("TOP", "text", _LatticeBound.TOP), @@ -314,12 +337,7 @@ def test_supremum_collection_nogoods_require_unseen_members(members: frozenset[i ("left", "right", _LatticeBound.BOT), (3, "text", _LatticeBound.BOT), ("text", 3, _LatticeBound.BOT), - pytest.param( - True, - 1, - _LatticeBound.BOT, - marks=pytest.mark.xfail(reason="Python equality currently conflates True and 1"), - ), + (True, 1, _LatticeBound.BOT), ("BOT", 3, _LatticeBound.BOT), (3, "BOT", _LatticeBound.BOT), ("BOT", "text", _LatticeBound.BOT), @@ -840,6 +858,17 @@ def on_model(model: clingo.Model) -> None: 2, None, ), + ( + ( + '1 { _se_value(variable("value"), val(bool, false)); ' + '_se_value(variable("value"), val(bool, true)) } 1.' + ), + {True}, + {False}, + True, + 2, + None, + ), ('{ _se_value(variable("value"), val(int, 1..3)) } 1.', {3}, {1}, True, 4, None), ( ('{ _se_value(variable("value"), val(int, 1)) }. :- _se_value(variable("value"), val(int, 1)).'), From 923e273be4d6feab1aff2985dac208221d8d1026 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Sun, 15 Nov 2026 23:50:49 +0100 Subject: [PATCH 18/29] add more tests for new modes --- .../reasoning_modes_new_bool_int.expected.infimum | 1 + ...reasoning_modes_new_bool_int.expected.supremum | 1 + .../reasoning_modes_new_bool_int.expected.union | 2 ++ .../core/reasoning_modes_new_bool_int.lp | 3 +++ ...asoning_modes_new_nested_sets.expected.infimum | 1 + ...soning_modes_new_nested_sets.expected.supremum | 1 + ...reasoning_modes_new_nested_sets.expected.union | 3 +++ .../core/reasoning_modes_new_nested_sets.lp | 3 +++ .../reasoning_modes_new_strings.expected.infimum | 1 + .../reasoning_modes_new_strings.expected.supremum | 1 + .../reasoning_modes_new_strings.expected.union | 3 +++ .../core/reasoning_modes_new_strings.lp | 4 ++++ tests/test_encoding.py | 15 +++++++++++++++ 13 files changed, 39 insertions(+) create mode 100644 tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_new_bool_int.expected.union create mode 100644 tests/correctness/core/reasoning_modes_new_bool_int.lp create mode 100644 tests/correctness/core/reasoning_modes_new_nested_sets.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_new_nested_sets.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_new_nested_sets.expected.union create mode 100644 tests/correctness/core/reasoning_modes_new_nested_sets.lp create mode 100644 tests/correctness/core/reasoning_modes_new_strings.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_new_strings.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_new_strings.expected.union create mode 100644 tests/correctness/core/reasoning_modes_new_strings.lp diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum b/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum new file mode 100644 index 000000000..ecf7ef260 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum @@ -0,0 +1 @@ +model_infimum(value,val(string,"BOT")) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum b/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum new file mode 100644 index 000000000..a3dc4192a --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum @@ -0,0 +1 @@ +model_supremum(value,val(string,"TOP")) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.expected.union b/tests/correctness/core/reasoning_modes_new_bool_int.expected.union new file mode 100644 index 000000000..4c84899ab --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_bool_int.expected.union @@ -0,0 +1,2 @@ +model_union(value,val(bool,true)) +model_union(value,val(int,1)) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.lp b/tests/correctness/core/reasoning_modes_new_bool_int.lp new file mode 100644 index 000000000..5570deb0f --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_bool_int.lp @@ -0,0 +1,3 @@ +variable_declare(value,fromFacts). +variable_domain(value,val(bool,true)). +variable_domain(value,val(int,1)). diff --git a/tests/correctness/core/reasoning_modes_new_nested_sets.expected.infimum b/tests/correctness/core/reasoning_modes_new_nested_sets.expected.infimum new file mode 100644 index 000000000..9f660820e --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_nested_sets.expected.infimum @@ -0,0 +1 @@ +model_infimum(value,set(())) diff --git a/tests/correctness/core/reasoning_modes_new_nested_sets.expected.supremum b/tests/correctness/core/reasoning_modes_new_nested_sets.expected.supremum new file mode 100644 index 000000000..aef4ee595 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_nested_sets.expected.supremum @@ -0,0 +1 @@ +model_supremum(value,set((set((val(int,1),())),(set((val(int,2),())),(set((val(int,3),())),()))))) diff --git a/tests/correctness/core/reasoning_modes_new_nested_sets.expected.union b/tests/correctness/core/reasoning_modes_new_nested_sets.expected.union new file mode 100644 index 000000000..a37820a33 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_nested_sets.expected.union @@ -0,0 +1,3 @@ +model_union(value,set((set((val(int,1),())),()))) +model_union(value,set((set((val(int,2),())),()))) +model_union(value,set((set((val(int,3),())),()))) diff --git a/tests/correctness/core/reasoning_modes_new_nested_sets.lp b/tests/correctness/core/reasoning_modes_new_nested_sets.lp new file mode 100644 index 000000000..f92c5e141 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_nested_sets.lp @@ -0,0 +1,3 @@ +variable_declare(value,set). +set_baseDomain(value,operation(set_make,(val(int,1..3),()))). +ensure(operation(eq,(operation(cardinality,(variable(value),())),(val(int,1),())))). diff --git a/tests/correctness/core/reasoning_modes_new_strings.expected.infimum b/tests/correctness/core/reasoning_modes_new_strings.expected.infimum new file mode 100644 index 000000000..ecf7ef260 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_strings.expected.infimum @@ -0,0 +1 @@ +model_infimum(value,val(string,"BOT")) diff --git a/tests/correctness/core/reasoning_modes_new_strings.expected.supremum b/tests/correctness/core/reasoning_modes_new_strings.expected.supremum new file mode 100644 index 000000000..a3dc4192a --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_strings.expected.supremum @@ -0,0 +1 @@ +model_supremum(value,val(string,"TOP")) diff --git a/tests/correctness/core/reasoning_modes_new_strings.expected.union b/tests/correctness/core/reasoning_modes_new_strings.expected.union new file mode 100644 index 000000000..d572e0e03 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_strings.expected.union @@ -0,0 +1,3 @@ +model_union(value,val(string,"red")) +model_union(value,val(string,"blue")) +model_union(value,val(string,"green")) diff --git a/tests/correctness/core/reasoning_modes_new_strings.lp b/tests/correctness/core/reasoning_modes_new_strings.lp new file mode 100644 index 000000000..a9d2cab01 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_strings.lp @@ -0,0 +1,4 @@ +variable_declare(value,fromFacts). +variable_domain(value,val(string,"red")). +variable_domain(value,val(string,"blue")). +variable_domain(value,val(string,"green")). diff --git a/tests/test_encoding.py b/tests/test_encoding.py index 0a7c2a6e6..abf4d357c 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -67,6 +67,9 @@ def run_test(name: str, selected_engine: engine.Engine): "core/optional_absent_string_comparison_evaluation", "core/python_set_bool_brave", "core/reasoning_modes", + "core/reasoning_modes_new_strings", + "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_bool_int", "core/reasoning_modes_sets", "core/reasoning_modes_with_show", "core/set_execution_input_alias", @@ -543,6 +546,8 @@ def run_test(name: str, selected_engine: engine.Engine): compile_skip: set[str] = set() compile_xfail: set[str] = { + "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_nested_sets", "datatype/bool/conj_disj/mixed", "datatype/bool/conj_disj/none", "datatype/float/mult/recovery", @@ -574,6 +579,8 @@ def run_test(name: str, selected_engine: engine.Engine): { "core/empty_set_execution", "core/reasoning_modes", # multimap + "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_nested_sets", "core/reasoning_modes_with_show", "core/reasoning_modes_sets", # new modes "datatype/bool/conj_disj_mixed", @@ -622,6 +629,8 @@ def run_test(name: str, selected_engine: engine.Engine): ground_xfail: set[str] = ( { "core/reasoning_modes", + "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_nested_sets", "core/reasoning_modes_with_show", "core/set_execution_input_alias", "datatype/bool/conj_disj_mixed", @@ -661,6 +670,9 @@ def run_test(name: str, selected_engine: engine.Engine): propagator_xfail: set[str] = { "core/conditional_declare_definition", "core/conditional_declare_set_multiple", + "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_strings", "core/reasoning_modes_with_show", "core/reasoning_modes_sets", # new modes "core/reasoning_modes", # new modes @@ -934,6 +946,9 @@ def test_engine(name: str, selected_engine: engine.Engine): "core/conditional_assign", "core/integrity", "core/reasoning_modes", + "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_strings", "core/reasoning_modes_sets", "core/reasoning_modes_with_show", "datatype/bool/derived_relations", From df3ac15a20b8424a9ea5243004789c6432f62f5b Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Mon, 16 Nov 2026 10:02:25 +0100 Subject: [PATCH 19/29] extend bool int example --- .../core/reasoning_modes_new_bool_int.expected.infimum | 1 + .../core/reasoning_modes_new_bool_int.expected.supremum | 1 + .../core/reasoning_modes_new_bool_int.expected.union | 2 ++ tests/correctness/core/reasoning_modes_new_bool_int.lp | 4 ++++ 4 files changed, 8 insertions(+) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum b/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum index ecf7ef260..ae70ed814 100644 --- a/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum +++ b/tests/correctness/core/reasoning_modes_new_bool_int.expected.infimum @@ -1 +1,2 @@ model_infimum(value,val(string,"BOT")) +model_infimum(zero,val(string,"BOT")) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum b/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum index a3dc4192a..ea6da3c5f 100644 --- a/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum +++ b/tests/correctness/core/reasoning_modes_new_bool_int.expected.supremum @@ -1 +1,2 @@ model_supremum(value,val(string,"TOP")) +model_supremum(zero,val(string,"TOP")) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.expected.union b/tests/correctness/core/reasoning_modes_new_bool_int.expected.union index 4c84899ab..f340da56b 100644 --- a/tests/correctness/core/reasoning_modes_new_bool_int.expected.union +++ b/tests/correctness/core/reasoning_modes_new_bool_int.expected.union @@ -1,2 +1,4 @@ model_union(value,val(bool,true)) model_union(value,val(int,1)) +model_union(zero,val(bool,false)) +model_union(zero,val(int,0)) diff --git a/tests/correctness/core/reasoning_modes_new_bool_int.lp b/tests/correctness/core/reasoning_modes_new_bool_int.lp index 5570deb0f..a9772d8e4 100644 --- a/tests/correctness/core/reasoning_modes_new_bool_int.lp +++ b/tests/correctness/core/reasoning_modes_new_bool_int.lp @@ -1,3 +1,7 @@ variable_declare(value,fromFacts). variable_domain(value,val(bool,true)). variable_domain(value,val(int,1)). + +variable_declare(zero,fromFacts). +variable_domain(zero,val(bool,false)). +variable_domain(zero,val(int,0)). From 513bc2a984c3653ada109abfb5288a2ddc01476c Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Mon, 16 Nov 2026 10:43:53 +0100 Subject: [PATCH 20/29] only track user variables in new reasoning modes --- .../reasoning_modes_propagator.py | 10 +++- tests/test_reasoning_mode_propagator.py | 57 +++++++++++++++---- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index 1d64632fc..aec06fc6b 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -9,7 +9,7 @@ import clingo from constraint_handler import multimap, myClorm -from constraint_handler.schemas import expression, internal, result +from constraint_handler.schemas import expression, internal, post, result class ReasoningMode(Enum): @@ -620,11 +620,19 @@ def prepare(self, control: clingo.Control) -> None: se_values = myClorm.findInControl(control, internal._se_value) set_values = myClorm.findInControl(control, internal._set_contains) multimap_values = myClorm.findInControl(control, result.Multimap_value) + user_variables: set[clingo.Symbol] = set() + for ch_post_atom in myClorm.findInControl(control, post.Ch_post).values(): + interface = ch_post_atom.declaration + if isinstance(interface, post.Variable_interface): + variable = expression.Variable(interface.variable) + user_variables.add(_variable_to_symbol(variable)) for atom, (expr, value) in se_values.items(): if not isinstance(expr, expression.Variable): continue name = _variable_to_symbol(expr) + if name not in user_variables: + continue if isinstance(value, internal.Ref) and str(value.type_) == "set": self._variables.setdefault(name, _SetVariable(name, value.expr)) elif isinstance(value, internal.Ref) and str(value.type_) == "multimap": diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index 03f9cd8a1..883d940de 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -26,6 +26,10 @@ from constraint_handler.schemas import expression +def _user_variable_interfaces(*names: str) -> str: + return "\n".join(f'ch_post(variable_interface("{name}"), "test").' for name in names) + + class _RecordingReasoningStrategy(ReasoningStrategy): def __init__(self) -> None: super().__init__() @@ -505,7 +509,7 @@ def test_reasoning_mode_propagator_builds_model_from_accepted_values() -> None: control.add( "base", [], - """ + _user_variable_interfaces("scalar", "items", "mapping") + """ 1 { _se_value(variable("scalar"), val(int, 3)); _se_value(variable("scalar"), val(int, 4)) } 1. _se_value(variable("items"), ref(set, variable("items"))). @@ -530,6 +534,27 @@ def test_reasoning_mode_propagator_builds_model_from_accepted_values() -> None: assert all(model[mapping] == expected_mapping for model in mode.models) +def test_reasoning_mode_propagator_tracks_only_interface_variables() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + control.register_propagator(propagator) + control.add( + "base", + [], + _user_variable_interfaces("public") + """ + _se_value(variable("public"), val(int, 1)). + _se_value(variable("internal"), val(int, 2)). + """, + ) + control.ground([("base", [])]) + + propagator.prepare(control) + + public = clingo.String("public") + assert set(propagator._variables) == {public} + assert propagator._variables[public].possible_values[0].value == 1 + + def test_intersection_propagator_callback_pruning_reports_progress_models() -> None: control = clingo.Control(["0"]) propagator = ReasoningModesPropagator(ReasoningMode.INTERSECTION) @@ -537,7 +562,7 @@ def test_intersection_propagator_callback_pruning_reports_progress_models() -> N control.add( "base", [], - """ + _user_variable_interfaces("scalar") + """ 1 { _se_value(variable("scalar"), val(int, 3)); _se_value(variable("scalar"), val(int, 4)) } 1. { auxiliary(1..5) }. @@ -587,7 +612,11 @@ def test_intersection_propagator_optional_scalar_has_empty_intersection() -> Non control = clingo.Control(["0"]) propagator = ReasoningModesPropagator(ReasoningMode.INTERSECTION) control.register_propagator(propagator) - control.add("base", [], '{ _se_value(variable("scalar"), val(int, 1)) }.') + control.add( + "base", + [], + _user_variable_interfaces("scalar") + '{ _se_value(variable("scalar"), val(int, 1)) }.', + ) control.ground([("base", [])]) reported: list[dict[clingo.Symbol, set[object]]] = [] @@ -651,7 +680,7 @@ def test_intersection_propagator_prunes_nonshrinking_collection_models() -> None control.add( "base", [], - """ + _user_variable_interfaces("items", "mapping") + """ _se_value(variable("items"), ref(set, variable("items"))). _set_contains(variable("items"), val(int, 1)). { _set_contains(variable("items"), val(int, 2)) }. @@ -747,7 +776,7 @@ def test_union_propagator_callback_pruning_reports_strict_growth() -> None: control.add( "base", [], - """ + _user_variable_interfaces("scalar", "items", "mapping") + """ 1 { _se_value(variable("scalar"), val(int, 1)); _se_value(variable("scalar"), val(int, 2)) } 1. _se_value(variable("items"), ref(set, variable("items"))). @@ -796,7 +825,7 @@ def test_extremum_propagator_callback_pruning_reports_strict_progress( control.add( "base", [], - """ + _user_variable_interfaces("scalar", "items", "mapping") + """ 1 { _se_value(variable("scalar"), val(int, 1..3)) } 1. _se_value(variable("items"), ref(set, variable("items"))). _set_contains(variable("items"), val(int, 0)). @@ -909,7 +938,7 @@ def test_extremum_propagator_scalar_and_empty_domains( control = clingo.Control(["0"]) propagator = ReasoningModesPropagator(reasoning_mode) control.register_propagator(propagator) - control.add("base", [], program + " { auxiliary(1..5) }.") + control.add("base", [], _user_variable_interfaces("value") + program + " { auxiliary(1..5) }.") control.ground([("base", [])]) accumulated: list[dict[clingo.Symbol, set[object]]] = [] @@ -956,7 +985,9 @@ def check(self, control: clingo.PropagateControl) -> None: rejector = RejectFirstValue() control.register_propagator(propagator) control.register_propagator(rejector) - control.add('1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.') + control.add( + "base", [], _user_variable_interfaces("scalar") + '1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.' + ) control.ground() propagator.prepare(control) @@ -980,7 +1011,9 @@ def test_reasoning_mode_reuses_witnesses_after_cleanup_and_additional_grounding( control = clingo.Control(["0"]) propagator = ReasoningModesPropagator(reasoning_mode) control.register_propagator(propagator) - control.add('1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.') + control.add( + "base", [], _user_variable_interfaces("scalar") + '1 { _se_value(variable("scalar"), val(int, 1..2)) } 1.' + ) control.ground() scalar = clingo.String("scalar") other = clingo.String("other") @@ -996,7 +1029,11 @@ def test_reasoning_mode_reuses_witnesses_after_cleanup_and_additional_grounding( assert propagator.reasoning_strategy.rm_model == expected control.cleanup() - control.add("extra", [], '1 { _se_value(variable("other"), val(int, 4..5)) } 1.') + control.add( + "extra", + [], + _user_variable_interfaces("other") + '1 { _se_value(variable("other"), val(int, 4..5)) } 1.', + ) control.ground([("extra", [])]) propagator.prepare(control) assert len(propagator._witnesses) == 2 From 6a904bc3b093d649b3da90b4acb803d325771963 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Mon, 16 Nov 2026 23:36:10 +0100 Subject: [PATCH 21/29] initial fix to sets within sets for new reasoning modes --- .../reasoning_modes_propagator.py | 9 ++++- tests/test_encoding.py | 2 -- tests/test_reasoning_mode_propagator.py | 33 +++++++++++++++---- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index aec06fc6b..d2721127a 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -8,7 +8,7 @@ import clingo -from constraint_handler import multimap, myClorm +from constraint_handler import evaluator, multimap, myClorm from constraint_handler.schemas import expression, internal, post, result @@ -153,6 +153,13 @@ def _python_value(value: Any) -> Any: The underlying Python value for expression values and references; otherwise, the input unchanged. """ + if isinstance(value, internal.Ref): + evaluated_value, errors = evaluator.evaluate_expr(value.expr) + if errors or evaluated_value is expression.Bad.bad: + return expression.Bad.bad + if str(value.type_) == "set" and isinstance(evaluated_value, (set, frozenset)): + return frozenset(evaluated_value) + return expression.Bad.bad if isinstance(value, (expression.Val, expression.Ref)): return value.value return value diff --git a/tests/test_encoding.py b/tests/test_encoding.py index abf4d357c..f721cc569 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -547,7 +547,6 @@ def run_test(name: str, selected_engine: engine.Engine): compile_skip: set[str] = set() compile_xfail: set[str] = { "core/reasoning_modes_new_bool_int", - "core/reasoning_modes_new_nested_sets", "datatype/bool/conj_disj/mixed", "datatype/bool/conj_disj/none", "datatype/float/mult/recovery", @@ -630,7 +629,6 @@ def run_test(name: str, selected_engine: engine.Engine): { "core/reasoning_modes", "core/reasoning_modes_new_bool_int", - "core/reasoning_modes_new_nested_sets", "core/reasoning_modes_with_show", "core/set_execution_input_alias", "datatype/bool/conj_disj_mixed", diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index 883d940de..a5e6b6ba1 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -6,7 +6,7 @@ import clingo import pytest -from constraint_handler import add_to_control, engine, multimap +from constraint_handler import add_to_control, engine, multimap, myClorm from constraint_handler.post_processor import extend_with_reasoning_mode_atoms from constraint_handler.reasoning_modes.reasoning_modes_propagator import ( InfimumReasoningMode, @@ -19,11 +19,12 @@ _LatticeBound, _MultimapVariable, _PairValue, + _python_value, _ScalarVariable, _SetVariable, _Value, ) -from constraint_handler.schemas import expression +from constraint_handler.schemas import expression, internal def _user_variable_interfaces(*names: str) -> str: @@ -126,6 +127,29 @@ def test_extend_reasoning_mode_atoms_encodes_whole_set_values() -> None: } +def test_extend_reasoning_mode_atoms_encodes_set_of_singleton_sets() -> None: + variable = clingo.String("value") + + symbols = _extend({variable: {frozenset({frozenset({1})})}}) + + assert symbols == {clingo.parse_term('model_union("value",set((set((val(int,1),())),())))')} + + +def test_python_value_evaluates_internal_set_reference() -> None: + reference = myClorm.cltopy( + clingo.parse_term("ref(set,operation(set_make,(val(int,1),())))"), + internal.Ref, + ) + + assert _python_value(reference) == frozenset({1}) + + +def test_python_value_returns_bad_for_unresolved_internal_set_reference() -> None: + reference = myClorm.cltopy(clingo.parse_term('ref(set,variable("missing"))'), internal.Ref) + + assert _python_value(reference) is expression.Bad.bad + + def test_extend_reasoning_mode_atoms_encodes_empty_set_marker() -> None: variable = clingo.String("items") @@ -888,10 +912,7 @@ def on_model(model: clingo.Model) -> None: None, ), ( - ( - '1 { _se_value(variable("value"), val(bool, false)); ' - '_se_value(variable("value"), val(bool, true)) } 1.' - ), + ('1 { _se_value(variable("value"), val(bool, false)); _se_value(variable("value"), val(bool, true)) } 1.'), {True}, {False}, True, From 9da0eb5e97200c9f8578d416b681782ae6d57fe2 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Tue, 17 Nov 2026 00:40:45 +0100 Subject: [PATCH 22/29] flat ch xfails reasoning mode tests due to new modes --- tests/flat_ch/test_correctness.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/flat_ch/test_correctness.py b/tests/flat_ch/test_correctness.py index daf4bacd5..3f8f25907 100644 --- a/tests/flat_ch/test_correctness.py +++ b/tests/flat_ch/test_correctness.py @@ -246,6 +246,10 @@ def generate_flat_ch_files() -> None: flat_ch_unsupported_tests = { "core/custom_globals", "core/python_set_bool_brave", + "core/reasoning_modes_new_strings", + "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_sets", "execution/python_integrity_should_be_ignored", "execution/python_set_empty_equality", "expression/python_extract/bad", From 5799eab204d4dcbee610e97b2b6408b764076cad Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Tue, 17 Nov 2026 11:05:16 +0100 Subject: [PATCH 23/29] improve docstrings --- .../reasoning_modes_propagator.py | 40 ++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index d2721127a..a1d50dae2 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -29,6 +29,8 @@ class ReasoningMode(Enum): class _LatticeBound(Enum): + """Top and bottom values used for incomparable scalar values.""" + TOP = "TOP" BOT = "BOT" @@ -230,7 +232,12 @@ def _init_literals( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Freeze prepared witnesses and map values to program literals.""" + """Freeze prepared witnesses and map values to program literals. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked variables and their possible values. + """ self.value_literals.clear() self.scalar_variables.clear() @@ -248,7 +255,16 @@ def _init_literals( self.value_literals[name][value] = candidate.literal def _set_or_multimap_value_nogood(self, name: clingo.Symbol, value: Any, helper: int) -> tuple[int, ...]: - """Build a nogood that matches a complete collection value and witness.""" + """Build a nogood that matches a complete collection value and witness. + + Args: + name: Symbol identifying the collection variable. + value: Complete set or multimap value to match. + helper: Literal representing this variable's progress witness. + + Returns: + Literals matching the complete value followed by the helper. + """ if isinstance(value, multimap.Multimap): retained = {(key, item) for key, items in value.items() for item in items} else: @@ -431,7 +447,12 @@ def init( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Reset accumulated bounds and initialize candidate literals.""" + """Reset accumulated bounds and initialize candidate literals. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked variables and their possible values. + """ super().init(init, variables) self._init_literals(init, variables) @@ -506,7 +527,12 @@ def init( init: clingo.PropagateInit, variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable], ) -> None: - """Reset accumulated bounds and initialize candidate literals.""" + """Reset accumulated bounds and initialize candidate literals. + + Args: + init: Clingo initialization context for the current solve. + variables: Tracked variables and their possible values. + """ super().init(init, variables) self._init_literals(init, variables) @@ -669,7 +695,11 @@ def prepare(self, control: clingo.Control) -> None: self.reasoning_strategy.variable_lit = {name: self._witnesses[name] for name in self._variables} def init(self, init: clingo.PropagateInit) -> None: - """Reset accumulation and initialize guards for the current solve.""" + """Reset accumulation and initialize guards for the current solve. + + Args: + init: Clingo initialization context for the current solve. + """ if self.disabled: return self.reasoning_strategy.init(init, self._variables) From 660bbc76a253e62e7c1a073feba6d1061649911f Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Thu, 19 Nov 2026 23:37:30 +0100 Subject: [PATCH 24/29] Can now use select_rm/2 to select regular atoms for the reasoning mode propagator --- src/constraint_handler/post_processor.py | 4 +++ .../reasoning_modes_propagator.py | 23 ++++++++++++++ ...ng_modes_new_normal_atoms.expected.infimum | 2 ++ ...des_new_normal_atoms.expected.intersection | 2 ++ ...g_modes_new_normal_atoms.expected.supremum | 3 ++ ...ning_modes_new_normal_atoms.expected.union | 3 ++ .../core/reasoning_modes_new_normal_atoms.lp | 6 ++++ tests/test_encoding.py | 3 ++ tests/test_reasoning_mode_propagator.py | 30 +++++++++++++++++++ 9 files changed, 76 insertions(+) create mode 100644 tests/correctness/core/reasoning_modes_new_normal_atoms.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_new_normal_atoms.expected.intersection create mode 100644 tests/correctness/core/reasoning_modes_new_normal_atoms.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_new_normal_atoms.expected.union create mode 100644 tests/correctness/core/reasoning_modes_new_normal_atoms.lp diff --git a/src/constraint_handler/post_processor.py b/src/constraint_handler/post_processor.py index 485dd94d6..8f1c180af 100644 --- a/src/constraint_handler/post_processor.py +++ b/src/constraint_handler/post_processor.py @@ -152,6 +152,10 @@ def extend_with_reasoning_mode_atoms(propagator: ReasoningModesPropagator, model symbols = set() for variable, values in propagator.reasoning_strategy.rm_model.items(): + if propagator.is_non_constraint_handler_variable(variable): + if any(value is True for value in values): + symbols.add(clingo.Function(f"model_{propagator.reasoning_mode.name.lower()}", [variable])) + continue for value in values: if isinstance(value, multimap.Multimap): value_symbol = _multimap_symbol(value) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index a1d50dae2..3a3cdf29f 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -626,10 +626,15 @@ def __init__(self, reasoning_mode: ReasoningMode = ReasoningMode.STANDARD) -> No self.reasoning_mode = reasoning_mode self.reasoning_strategy: ReasoningStrategy = REASONING_STRATEGIES[reasoning_mode]() self._variables: dict[clingo.Symbol, _ScalarVariable | _SetVariable | _MultimapVariable] = {} + self._non_constraint_handler_variables: set[clingo.Symbol] = set() self._witnesses: dict[clingo.Symbol, int] = {} self.disabled = isinstance(self.reasoning_strategy, StandardReasoningMode) + def is_non_constraint_handler_variable(self, name: clingo.Symbol) -> bool: + """Return whether a tracked name is a selected regular atom.""" + return name in self._non_constraint_handler_variables + def set_mode(self, reasoning_mode: ReasoningMode) -> None: """Replace the active reasoning strategy. @@ -649,6 +654,24 @@ def prepare(self, control: clingo.Control) -> None: if self.disabled: return self._variables.clear() + self._non_constraint_handler_variables.clear() + + for selector in control.symbolic_atoms.by_signature("select_rm", 2): + name, arity = selector.symbol.arguments + if name.type == clingo.SymbolType.String: + predicate_name = name.string + elif name.type == clingo.SymbolType.Function and not name.arguments: + predicate_name = name.name + else: + continue + if arity.type != clingo.SymbolType.Number or arity.number < 0: + continue + for atom in control.symbolic_atoms.by_signature(predicate_name, arity.number): + self._non_constraint_handler_variables.add(atom.symbol) + self._variables[atom.symbol] = _ScalarVariable( + atom.symbol, + [_Value(atom.literal, True), _Value(-atom.literal, False)], + ) se_values = myClorm.findInControl(control, internal._se_value) set_values = myClorm.findInControl(control, internal._set_contains) diff --git a/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.infimum b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.infimum new file mode 100644 index 000000000..0b1a63cac --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.infimum @@ -0,0 +1,2 @@ +model_infimum(fixed,val(int,7)) +model_infimum(candidate(b)) diff --git a/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.intersection b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.intersection new file mode 100644 index 000000000..1706aa5c2 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.intersection @@ -0,0 +1,2 @@ +model_intersection(fixed,val(int,7)) +model_intersection(candidate(b)) diff --git a/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.supremum b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.supremum new file mode 100644 index 000000000..e5ca082e6 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.supremum @@ -0,0 +1,3 @@ +model_supremum(fixed,val(int,7)) +model_supremum(candidate(a)) +model_supremum(candidate(b)) diff --git a/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.union b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.union new file mode 100644 index 000000000..612ebacfa --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_normal_atoms.expected.union @@ -0,0 +1,3 @@ +model_union(fixed,val(int,7)) +model_union(candidate(a)) +model_union(candidate(b)) diff --git a/tests/correctness/core/reasoning_modes_new_normal_atoms.lp b/tests/correctness/core/reasoning_modes_new_normal_atoms.lp new file mode 100644 index 000000000..9bcbe039d --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_normal_atoms.lp @@ -0,0 +1,6 @@ +select_rm(candidate, 1). +{ candidate(a) }. +candidate(b). + +variable_declare(fixed,fromFacts). +variable_domain(fixed,val(int,7)). diff --git a/tests/test_encoding.py b/tests/test_encoding.py index f721cc569..9246b30ca 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -70,6 +70,7 @@ def run_test(name: str, selected_engine: engine.Engine): "core/reasoning_modes_new_strings", "core/reasoning_modes_new_nested_sets", "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_sets", "core/reasoning_modes_with_show", "core/set_execution_input_alias", @@ -669,6 +670,7 @@ def run_test(name: str, selected_engine: engine.Engine): "core/conditional_declare_definition", "core/conditional_declare_set_multiple", "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_new_nested_sets", "core/reasoning_modes_new_strings", "core/reasoning_modes_with_show", @@ -944,6 +946,7 @@ def test_engine(name: str, selected_engine: engine.Engine): "core/conditional_assign", "core/integrity", "core/reasoning_modes", + "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_new_bool_int", "core/reasoning_modes_new_nested_sets", "core/reasoning_modes_new_strings", diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index a5e6b6ba1..813eb249b 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -94,6 +94,36 @@ def test_extend_reasoning_mode_atoms_emits_each_scalar_value() -> None: } +def test_regular_atoms_are_selected_as_boolean_reasoning_variables() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + control.register_propagator(propagator) + control.add("base", [], 'select_rm(feature, 1). { feature("a"); feature("b") }.') + control.ground([("base", [])]) + + propagator.prepare(control) + assert control.solve(on_model=propagator.on_model).satisfiable + + feature_a = clingo.Function("feature", [clingo.String("a")]) + feature_b = clingo.Function("feature", [clingo.String("b")]) + assert propagator.reasoning_strategy.rm_model == { + feature_a: {False, True}, + feature_b: {False, True}, + } + + model = _Model() + extend_with_reasoning_mode_atoms(propagator, model) + assert model.symbols == { + clingo.Function("model_union", [feature_a]), + clingo.Function("model_union", [feature_b]), + } + + propagator.reasoning_strategy.rm_model = {feature_a: {False}} + model = _Model() + extend_with_reasoning_mode_atoms(propagator, model) + assert model.symbols == set() + + @pytest.mark.parametrize( "strategy_type, reasoning_mode, expected_value", [ From 47a6eae67f46e82885bc9eb3117984d54c5f7e17 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Thu, 19 Nov 2026 23:50:43 +0100 Subject: [PATCH 25/29] small fix --- .../reasoning_modes/reasoning_modes_propagator.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index 3a3cdf29f..19a865532 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -664,12 +664,15 @@ def prepare(self, control: clingo.Control) -> None: predicate_name = name.name else: continue + if arity.type != clingo.SymbolType.Number or arity.number < 0: continue + for atom in control.symbolic_atoms.by_signature(predicate_name, arity.number): - self._non_constraint_handler_variables.add(atom.symbol) - self._variables[atom.symbol] = _ScalarVariable( - atom.symbol, + atom_symbol = atom.symbol + self._non_constraint_handler_variables.add(atom_symbol) + self._variables[atom_symbol] = _ScalarVariable( + atom_symbol, [_Value(atom.literal, True), _Value(-atom.literal, False)], ) From e9c34434c78a28e6a105e87ddfd948fbbd85c87a Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Fri, 20 Nov 2026 00:02:30 +0100 Subject: [PATCH 26/29] ignore regular atom if name matches a ch variable's name --- .../reasoning_modes_propagator.py | 15 +++++++++------ tests/test_reasoning_mode_propagator.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py index 19a865532..60ae60be5 100644 --- a/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py +++ b/src/constraint_handler/reasoning_modes/reasoning_modes_propagator.py @@ -656,6 +656,13 @@ def prepare(self, control: clingo.Control) -> None: self._variables.clear() self._non_constraint_handler_variables.clear() + user_variables: set[clingo.Symbol] = set() + for ch_post_atom in myClorm.findInControl(control, post.Ch_post).values(): + interface = ch_post_atom.declaration + if isinstance(interface, post.Variable_interface): + variable = expression.Variable(interface.variable) + user_variables.add(_variable_to_symbol(variable)) + for selector in control.symbolic_atoms.by_signature("select_rm", 2): name, arity = selector.symbol.arguments if name.type == clingo.SymbolType.String: @@ -670,6 +677,8 @@ def prepare(self, control: clingo.Control) -> None: for atom in control.symbolic_atoms.by_signature(predicate_name, arity.number): atom_symbol = atom.symbol + if atom_symbol in user_variables: + continue self._non_constraint_handler_variables.add(atom_symbol) self._variables[atom_symbol] = _ScalarVariable( atom_symbol, @@ -679,12 +688,6 @@ def prepare(self, control: clingo.Control) -> None: se_values = myClorm.findInControl(control, internal._se_value) set_values = myClorm.findInControl(control, internal._set_contains) multimap_values = myClorm.findInControl(control, result.Multimap_value) - user_variables: set[clingo.Symbol] = set() - for ch_post_atom in myClorm.findInControl(control, post.Ch_post).values(): - interface = ch_post_atom.declaration - if isinstance(interface, post.Variable_interface): - variable = expression.Variable(interface.variable) - user_variables.add(_variable_to_symbol(variable)) for atom, (expr, value) in se_values.items(): if not isinstance(expr, expression.Variable): diff --git a/tests/test_reasoning_mode_propagator.py b/tests/test_reasoning_mode_propagator.py index 813eb249b..dd1679726 100644 --- a/tests/test_reasoning_mode_propagator.py +++ b/tests/test_reasoning_mode_propagator.py @@ -124,6 +124,23 @@ def test_regular_atoms_are_selected_as_boolean_reasoning_variables() -> None: assert model.symbols == set() +def test_regular_atoms_matching_constraint_handler_variables_are_not_selected() -> None: + control = clingo.Control(["0"]) + propagator = ReasoningModesPropagator(ReasoningMode.UNION) + control.register_propagator(propagator) + control.add( + "base", + [], + 'select_rm(feature, 1). { feature("a") }. ch_post(variable_interface(feature("a")), "test").', + ) + control.ground([("base", [])]) + + propagator.prepare(control) + + feature_a = clingo.Function("feature", [clingo.String("a")]) + assert not propagator.is_non_constraint_handler_variable(feature_a) + + @pytest.mark.parametrize( "strategy_type, reasoning_mode, expected_value", [ From 005c3c0af8ddca513f395216f7d0a55c91ed3c69 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Fri, 20 Nov 2026 00:22:43 +0100 Subject: [PATCH 27/29] add deeply nested sets test --- .../reasoning_modes_new_deeply_nested_sets.expected.infimum | 1 + .../reasoning_modes_new_deeply_nested_sets.expected.supremum | 1 + .../reasoning_modes_new_deeply_nested_sets.expected.union | 3 +++ .../core/reasoning_modes_new_deeply_nested_sets.lp | 3 +++ tests/test_encoding.py | 4 ++++ 5 files changed, 12 insertions(+) create mode 100644 tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.infimum create mode 100644 tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.union create mode 100644 tests/correctness/core/reasoning_modes_new_deeply_nested_sets.lp diff --git a/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.infimum b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.infimum new file mode 100644 index 000000000..9f660820e --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.infimum @@ -0,0 +1 @@ +model_infimum(value,set(())) diff --git a/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.supremum b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.supremum new file mode 100644 index 000000000..7c744d497 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.supremum @@ -0,0 +1 @@ +model_supremum(value,set((set((set((val(int,1),())),())),(set((set((val(int,2),())),())),(set((set((val(int,3),())),())),()))))) diff --git a/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.union b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.union new file mode 100644 index 000000000..c27e59be5 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.expected.union @@ -0,0 +1,3 @@ +model_union(value,set((set((set((val(int,1),())),())),()))) +model_union(value,set((set((set((val(int,2),())),())),()))) +model_union(value,set((set((set((val(int,3),())),())),()))) diff --git a/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.lp b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.lp new file mode 100644 index 000000000..2fa655cb2 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_new_deeply_nested_sets.lp @@ -0,0 +1,3 @@ +variable_declare(value,set). +set_baseDomain(value,operation(set_make,(operation(set_make,(val(int,1..3),())),()))). +ensure(operation(eq,(operation(cardinality,(variable(value),())),(val(int,1),())))). diff --git a/tests/test_encoding.py b/tests/test_encoding.py index 9246b30ca..ad9b5b621 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -69,6 +69,7 @@ def run_test(name: str, selected_engine: engine.Engine): "core/reasoning_modes", "core/reasoning_modes_new_strings", "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_deeply_nested_sets", "core/reasoning_modes_new_bool_int", "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_sets", @@ -581,6 +582,7 @@ def run_test(name: str, selected_engine: engine.Engine): "core/reasoning_modes", # multimap "core/reasoning_modes_new_bool_int", "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_deeply_nested_sets", "core/reasoning_modes_with_show", "core/reasoning_modes_sets", # new modes "datatype/bool/conj_disj_mixed", @@ -672,6 +674,7 @@ def run_test(name: str, selected_engine: engine.Engine): "core/reasoning_modes_new_bool_int", "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_deeply_nested_sets", "core/reasoning_modes_new_strings", "core/reasoning_modes_with_show", "core/reasoning_modes_sets", # new modes @@ -949,6 +952,7 @@ def test_engine(name: str, selected_engine: engine.Engine): "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_new_bool_int", "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_deeply_nested_sets", "core/reasoning_modes_new_strings", "core/reasoning_modes_sets", "core/reasoning_modes_with_show", From 6bb5e7088226a205c40fecb9917a7b65f9acfa82 Mon Sep 17 00:00:00 2001 From: Klaus Strauch Date: Fri, 20 Nov 2026 01:47:26 +0100 Subject: [PATCH 28/29] add new reasoning mode tests to unsupported --- tests/flat_ch/test_correctness.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/flat_ch/test_correctness.py b/tests/flat_ch/test_correctness.py index 3f8f25907..ad3ed53a8 100644 --- a/tests/flat_ch/test_correctness.py +++ b/tests/flat_ch/test_correctness.py @@ -248,6 +248,8 @@ def generate_flat_ch_files() -> None: "core/python_set_bool_brave", "core/reasoning_modes_new_strings", "core/reasoning_modes_new_nested_sets", + "core/reasoning_modes_new_deeply_nested_sets", + "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_new_bool_int", "core/reasoning_modes_sets", "execution/python_integrity_should_be_ignored", From 838709cb82472b04de41ea6d30de2aa1b206625d Mon Sep 17 00:00:00 2001 From: Abdallah Saffidine Date: Sun, 22 Nov 2026 19:51:56 +1100 Subject: [PATCH 29/29] Add some failing tests for reasoning modes --- DEVELOPMENT.md | 2 ++ ...reasoning_modes_optional_scalar.expected.intersection.none | 1 + tests/correctness/core/reasoning_modes_optional_scalar.lp | 3 +++ ...reasoning_modes_sets_alternative_sources.expected.supremum | 1 + .../reasoning_modes_sets_alternative_sources.expected.union | 2 ++ .../core/reasoning_modes_sets_alternative_sources.lp | 3 +++ tests/flat_ch/test_correctness.py | 2 ++ tests/test_encoding.py | 4 ++++ tests/utils/testing.py | 3 +++ 9 files changed, 21 insertions(+) create mode 100644 tests/correctness/core/reasoning_modes_optional_scalar.expected.intersection.none create mode 100644 tests/correctness/core/reasoning_modes_optional_scalar.lp create mode 100644 tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.supremum create mode 100644 tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.union create mode 100644 tests/correctness/core/reasoning_modes_sets_alternative_sources.lp diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 98478b6de..0566a34b9 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -99,6 +99,8 @@ The supported suffixes are: unsatisfiable. - `brave` `cautious`, `union`, `intersection`, `supremum`, and `infimum`: atom must occur in the final model with the matching enumeration mode. +- `union.none`, `intersection.none`, `supremum.none`, and `infimum.none`: atom + must be absent from the final model with the matching reasoning mode. - `optall`, `optany`, and `optnone`: atom must occur in every, any, or no optimal model respectively. - `stats`: one `key=value` entry per line. `models=` asserts the exact diff --git a/tests/correctness/core/reasoning_modes_optional_scalar.expected.intersection.none b/tests/correctness/core/reasoning_modes_optional_scalar.expected.intersection.none new file mode 100644 index 000000000..0dde9c6eb --- /dev/null +++ b/tests/correctness/core/reasoning_modes_optional_scalar.expected.intersection.none @@ -0,0 +1 @@ +model_intersection(x,val(int,1)) diff --git a/tests/correctness/core/reasoning_modes_optional_scalar.lp b/tests/correctness/core/reasoning_modes_optional_scalar.lp new file mode 100644 index 000000000..14bb66d90 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_optional_scalar.lp @@ -0,0 +1,3 @@ +{ inactive }. +active :- not inactive. +variable_define(x,val(int,1)) :- active. diff --git a/tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.supremum b/tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.supremum new file mode 100644 index 000000000..fa952beb9 --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.supremum @@ -0,0 +1 @@ +model_supremum(s,set((val(int,1),(val(int,2),())))) diff --git a/tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.union b/tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.union new file mode 100644 index 000000000..4971b8aaa --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets_alternative_sources.expected.union @@ -0,0 +1,2 @@ +model_union(s,set((val(int,1),()))) +model_union(s,set((val(int,2),()))) diff --git a/tests/correctness/core/reasoning_modes_sets_alternative_sources.lp b/tests/correctness/core/reasoning_modes_sets_alternative_sources.lp new file mode 100644 index 000000000..26512c42c --- /dev/null +++ b/tests/correctness/core/reasoning_modes_sets_alternative_sources.lp @@ -0,0 +1,3 @@ +{ choose }. +variable_define(s,operation(set_make,(val(int,1),()))) :- choose. +variable_define(s,operation(set_make,(val(int,2),()))) :- not choose. diff --git a/tests/flat_ch/test_correctness.py b/tests/flat_ch/test_correctness.py index ad3ed53a8..435880b2f 100644 --- a/tests/flat_ch/test_correctness.py +++ b/tests/flat_ch/test_correctness.py @@ -251,7 +251,9 @@ def generate_flat_ch_files() -> None: "core/reasoning_modes_new_deeply_nested_sets", "core/reasoning_modes_new_normal_atoms", "core/reasoning_modes_new_bool_int", + "core/reasoning_modes_optional_scalar", "core/reasoning_modes_sets", + "core/reasoning_modes_sets_alternative_sources", "execution/python_integrity_should_be_ignored", "execution/python_set_empty_equality", "expression/python_extract/bad", diff --git a/tests/test_encoding.py b/tests/test_encoding.py index ad9b5b621..f466e20fe 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -72,7 +72,9 @@ def run_test(name: str, selected_engine: engine.Engine): "core/reasoning_modes_new_deeply_nested_sets", "core/reasoning_modes_new_bool_int", "core/reasoning_modes_new_normal_atoms", + "core/reasoning_modes_optional_scalar", "core/reasoning_modes_sets", + "core/reasoning_modes_sets_alternative_sources", "core/reasoning_modes_with_show", "core/set_execution_input_alias", "core/set_interface_value_marker", @@ -810,6 +812,8 @@ def test_engine(name: str, selected_engine: engine.Engine): "core/evaluate_dynamic", "core/optional_set_empty_execution", "core/python_set_bool_brave", + "core/reasoning_modes_optional_scalar", + "core/reasoning_modes_sets_alternative_sources", "core/set_interface_value_marker", "core/shared_optional_output_domains", "core/unprojected_optional_equality", diff --git a/tests/utils/testing.py b/tests/utils/testing.py index 6f2dacce5..135637701 100644 --- a/tests/utils/testing.py +++ b/tests/utils/testing.py @@ -95,6 +95,9 @@ def build_expectations(name) -> list[tuple[clintest.test.Test, TestingOptions]]: for mode in (ReasoningMode.UNION, ReasoningMode.INTERSECTION, ReasoningMode.SUPREMUM, ReasoningMode.INFIMUM): test_mode = [clintest.test.Assert(Last(), contains(atom)) for atom in atoms_from_file(name + mode.name.lower())] + test_mode.extend( + clintest.test.Assert(Last(), absent(atom)) for atom in atoms_from_file(name + mode.name.lower() + ".none") + ) if test_mode: tests.append((clintest.test.And(*test_mode), TestingOptions(add_to_ctl_options={"reasoning_mode": mode})))