Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Ongoing

## v0.0.12

- - Use dataclasses as the basis for the python schemas
- - Change pythonExtract and python operators to be consistently
non-recoverable
- add an optional argument to `add_to_control` to dump readable programs after
grounding
- introduce `join` and `meet` variable declarations

## v0.0.11
Expand Down
1 change: 1 addition & 0 deletions src/constraint_handler/data/6_module/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ _bool_evaluate/2.
### Output predicates

_bool_evaluated/2.
_propagator_bool_evaluated/2.
_warning/3.
_se_value/2.
ch_solve(set_assign/3,LBL).
Expand Down
3 changes: 2 additions & 1 deletion src/constraint_handler/data/6_module/bool_evaluate.lp
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
%%%%%%%%%%%%%%%%% bool_evaluate
ch_solve(share_value(E),LBL) :- _bool_evaluate(E,LBL), E != val(bool,true).
propagator_bool_evaluate(E,LBL) :- _bool_evaluate(E,LBL), _engine_propagator(LBL), E != val(bool,true).
1 { _bool_evaluated(E,(bad;val(bool,(true;false)))) } 1 :- _bool_evaluate(E,LBL), _engine_propagator(LBL), E != val(bool,true).
1 { _propagator_bool_evaluated(E,(bad;val(bool,(true;false)))) } 1 :- propagator_bool_evaluate(E,LBL).
_bool_evaluated(E,V) :- _propagator_bool_evaluated(E,V).
_bool_evaluated(E,V) :- _bool_evaluate(E,LBL), _shared_value(E,V), V=(bad;val(bool,(true;false))), E != val(bool,true).
_bool_evaluated(val(bool,true),val(bool,true)).

Expand Down
13 changes: 8 additions & 5 deletions src/constraint_handler/data/6_solve/compile/direct.lp
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,17 @@ _expression_dynamicTainted(EXPR) :- _expression(compile,EXPR), _expression_safeQ
_se_value(EXPR,bad) :- _expression(compile,EXPR), _expression_safeQuery(EXPR), _expression_operationOperator(sugar,EXPR,OP), _expression_dynamicTainted(OP).
_se_value(EXPR,bad) :- _expression(compile,EXPR), _expression_safeQuery(EXPR), _expression_operationIndex(sugar,EXPR,IDX,F), _expression_dynamicTainted(F), _expression_operationOperator(sugar,EXPR,OP), not _operator_recoverable(OP).


_argument_value(operation(OP,ARGS),V) :- _expression(compile,operation(OP,ARGS)), _expression_operationIndex(compile,operation(OP,ARGS),IDX,ARG), _se_value(ARG,V).
_se_value(operation(OP,ARGS),bad) :- _argument_value(operation(OP,ARGS),bad), not _operator_recoverable(OP), not _expression_safe(operation(OP,ARGS)).
_expression_contains_bad(EXPR) :- _se_value(EXPR,bad).
_expression_contains_bad(EXPR) :- _expression_tupleIndex(compile,EXPR,IDX,F), _expression_contains_bad(F).
_se_value(operation(OP,ARGS),bad) :-
_expression(compile,operation(OP,ARGS)), _expression_operationIndex(compile,operation(OP,ARGS),IDX,ARG),
_expression_contains_bad(ARG), not _operator_recoverable(OP), not _expression_safe(operation(OP,ARGS)).

%%%%%%%%%%%%%%%%% _computedIdx operators
_direct_queryOperation(operation(OP,ARGS)) :- direct_query(operation(OP,ARGS)), _expression_safe(operation(OP,ARGS)).
_direct_queryOperation(operation(OP,ARGS)) :- direct_query(operation(OP,ARGS)), _operator_recoverable(OP).
_direct_queryOperation(operation(OP,ARGS)) :- direct_query(operation(OP,ARGS)), not _operator_recoverable(OP), not _argument_value(operation(OP,ARGS),bad).
_direct_queryOperation(operation(OP,ARGS)) :- direct_query(operation(OP,ARGS)), not _operator_recoverable(OP),
#false : _expression_operationIndex(compile,operation(OP,ARGS),IDX,ARG), _expression_contains_bad(ARG).
%_direct_queryOperation(operation(OP,ARGS)) :- direct_query(operation(OP,ARGS)), not _expression_safe(operation(OP,ARGS)), not _operator_recoverable(OP), not _direct_bad_operation(OP,ARGS).
%_direct_queryOperation(operation(OP,ARGS)) :- direct_query(operation(OP,ARGS)), not _operator_recoverable(OP), not _safe_bad(operation(OP,ARGS)). %% TODO: use static tainted instead
%_se_value(E,bad) :- _expression_dynamicTainted(E).
Expand All @@ -64,7 +67,7 @@ _computedIdx(E,VO) :- _lambda_aux(E,RED), _se_value(RED,VO).
_direct_implode(V) :- _computeIdx(E,python(STR)), _computeIdx(E,IDX,V).
_direct_imploded_args_aux(E,IDX,()) :- _computeIdx(E,python(STR)), _expression_operationLength(compile,E,IDX).
_direct_imploded_args_aux(E,IDX,(IMP,L)) :- _direct_imploded_args_aux(E,IDX+1,L), _computeIdx(E,IDX,V),
_direct_imploded(V,IMP).
_direct_imploded(V,IMP), IMP != bad, #false : IMP=(BINDING,bad).

_python_request(E,operation(python(S),L)) :- _computeIdx(E,python(S)), _direct_imploded_args_aux(E,0,L).

Expand Down
2 changes: 1 addition & 1 deletion src/constraint_handler/data/main.lp
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ _parameter_value(PARAM,VAL) :- _parameter_default(PARAM,VAL), not _parameter_use
_parameter_value(PARAM,VAL) :- parameter_request(PARAM,VAL).

%%%%%%%%%%%%%%%%% version
version("0.0.11").
version("0.0.12").
113 changes: 113 additions & 0 deletions src/constraint_handler/ground_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Readable ground program output for Clingo controls."""

import json
import typing
from functools import partialmethod
from tempfile import TemporaryFile

import clingo
from clingo.backend import Observer


class GroundProgramObserver(Observer):
"""Spool grounding events to disk until Clingo's atom names are available."""

def __init__(self, ctrl: clingo.Control, output: typing.TextIO) -> None:
self._ctrl = ctrl
self._ground = ctrl.ground
self._output = output
self._spool: typing.TextIO | None = None
self._objective = 0

def ground(self, *args: typing.Any, **kwargs: typing.Any) -> None:
with TemporaryFile(mode="w+t", encoding="utf-8") as spool:
self._spool = spool
try:
self._ground(*args, **kwargs)
finally:
self._spool = None

names = {atom.literal: str(atom.symbol) for atom in self._ctrl.symbolic_atoms}
spool.seek(0)
for line in spool:
callback, arguments = json.loads(line)
self._emit(callback, *arguments, names=names)

def _capture(self, callback: str, *args: typing.Any) -> None:
match callback, args:
case "begin_step" | "end_step", _:
return
case "output_atom" | "output_term", (symbol, value):
args = (str(symbol), value)
case "external", (atom, value):
args = (atom, value.name.rstrip("_").lower())
case "heuristic", (atom, kind, bias, priority, values):
args = (atom, kind.name.rstrip("_").lower(), bias, priority, values)

if self._spool is None:
self._emit(callback, *args)
else:
self._spool.write(json.dumps((callback, args), separators=(",", ":")) + "\n")

def _emit(self, callback: str, *args: typing.Any, names: dict[int, str] | None = None) -> None:
def literal(value: int) -> str:
atom = abs(value)
name = names.get(atom) if names is not None else None
if name is None:
name = f"_ch_ground_atom({atom})"
return f"not {name}" if value < 0 else name

def condition(values: typing.Sequence[int], separator: str) -> str:
return separator + ", ".join(map(literal, values)) if values else ""

if callback in ("rule", "weight_rule"):
choice, head, *body = args
lhs = "; ".join(map(literal, head))
if choice:
lhs = f"{{{lhs}}}"
if callback == "weight_rule":
bound, weights = body
elements = "; ".join(
f"{weight},{index} : {literal(value)}" for index, (value, weight) in enumerate(weights)
)
rhs = f"#sum {{ {elements} }} >= {bound}"
else:
rhs = ", ".join(map(literal, body[0]))
self._output.write(f"{lhs}{' ' if lhs else ''}:- {rhs}.\n" if rhs else f"{lhs or ':-'}.\n")
return

match callback, args:
case "init_program", _:
self._output.write("#show.\n")
case "minimize", (priority, weights):
self._objective += 1
elements = "; ".join(
f"{weight}@{priority},{self._objective},{index} : {literal(value)}"
for index, (value, weight) in enumerate(weights)
)
self._output.write(f"#minimize {{ {elements} }}.\n")
case "output_atom", (symbol, atom):
self._output.write(f"#show {symbol}{condition((atom,) if atom else (), ' : ')}.\n")
case "output_term", (symbol, values):
self._output.write(f"#show {symbol}{condition(values, ' : ')}.\n")
case "external", (atom, value):
self._output.write(f"#external {literal(atom)}. [{value}]\n")
case "heuristic", (atom, modifier, bias, priority, values):
body = condition(values, " : ")
self._output.write(f"#heuristic {literal(atom)}{body}. [{bias}@{priority},{modifier}]\n")
case "project", (atoms,):
for atom in atoms:
self._output.write(f"#project {literal(atom)}.\n")
if not atoms:
self._output.write("#project _ch_ground_atom(0) : #false.\n")
case "acyc_edge", (source, target, values):
self._output.write(f"#edge ({source},{target}){condition(values, ' : ')}.\n")
case "assume", (values,) if values:
self._output.write(f"% assume {', '.join(map(literal, values))}\n")
case _ if callback.startswith("theory_"):
self._output.write(f"% {callback}{args!r}\n")

for _name, _callback in vars(Observer).items():
if not _name.startswith("_") and callable(_callback):
vars()[_name] = partialmethod(_capture, _name)
del _name, _callback
14 changes: 13 additions & 1 deletion src/constraint_handler/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.ground_output import GroundProgramObserver
from constraint_handler.reasoning_modes.reasoning_modes_propagator import ReasoningMode, ReasoningModesPropagator
from constraint_handler.schemas.type_ import BaseType

Expand Down Expand Up @@ -181,12 +182,23 @@ def add_to_control(
_environment_ids=dict(),
engine: Engine = compile,
reasoning_mode: ReasoningMode = ReasoningMode.STANDARD,
ground_output: typing.TextIO | None = None,
):
"""Adds encoding logic to the provided Control instance. The environment argumennt specifies the locals used in the python statements and expressions."""
"""Add encoding logic to the provided Control instance.

The environment supplies locals for Python statements and expressions.
Pass an open text stream as ``ground_output`` to dump ground statements
at the end of each ``ground()`` call.
"""
if engine.name == "fch":
flat_main.add_to_control(ctrl, _build_fch_environment(environment), api="ch")
return

if ground_output is not None:
observer = GroundProgramObserver(ctrl, ground_output)
ctrl.register_observer(observer)
ctrl.ground = observer.ground

global python_enabled
if not python_enabled:
clingo.script.enable_python()
Expand Down
33 changes: 30 additions & 3 deletions src/constraint_handler/myClorm.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import enum
import types
import typing
from functools import cache
from functools import cache, lru_cache

import clingo

Expand Down Expand Up @@ -64,6 +64,7 @@ def cltopy(cls, func, target_args=()):
return cls(un)


_HASHABLE_CONTAINERS = {list: ImmutableList, set: frozenset}
_NO_CUSTOM_CONVERTER = object()
_cltopy_cache = {}

Expand Down Expand Up @@ -105,7 +106,8 @@ def _substitute_typevars(target, typevars):

@cache
def _get_record_predicate_name(target):
return predicatedefn_default_predicate_name(target.__name__)
name = getattr(target, "__predicate_name__", target.__name__)
return predicatedefn_default_predicate_name(name)


@cache
Expand Down Expand Up @@ -163,6 +165,13 @@ def _resolve_custom_converter(target, name, value):
return _NO_CUSTOM_CONVERTER


def _pytocl_cache_value(value):
container_type = _HASHABLE_CONTAINERS.get(type(value), type(value))
if container_type in (tuple, ImmutableList, frozenset):
return container_type(_pytocl_cache_value(element) for element in value)
return value


def pytocl(v, target_type=None):
"""Encode a Python value as a Clingo symbol.

Expand All @@ -173,6 +182,23 @@ class name as the predicate name. ``target_type`` selects a type or union.
>>> print(symbol)
(1,("two",(3,())))
"""
try:
return _pytocl(v, target_type)
except TypeError:
try:
hash((v, target_type))
except TypeError:
v = _pytocl_cache_value(v)
else:
raise
try:
return _pytocl(v, target_type)
except TypeError:
return _pytocl.__wrapped__(v, target_type)


@lru_cache(maxsize=None, typed=True)
def _pytocl(v, target_type=None):
if target_type is None:
target_type = type(v)

Expand All @@ -183,7 +209,8 @@ class name as the predicate name. ``target_type`` selects a type or union.
return custom_value
if target_class == typing.Any:
return v
if not isinstance(target_class, type) or not isinstance(v, target_class):
cache_type = _HASHABLE_CONTAINERS.get(target_class)
if not isinstance(target_class, type) or not isinstance(v, cache_type or target_class):
continue
if issubclass(target_class, clingo.Symbol):
return v
Expand Down
8 changes: 4 additions & 4 deletions src/constraint_handler/propagator/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,13 +698,13 @@ def get_forbidden_warnings(self, ctl: clingo.PropagateInit) -> None:
forbidden_warnings = myClorm.findInPropagateInit(ctl, prop_atom.Propagator_warning_forbid)
ignored_warnings = myClorm.findInPropagateInit(ctl, prop_atom.Propagator_warning_ignore)

for (error, name), literal in forbidden_warnings.items():
self.forbidden_warnings[error] = literal
for warning, literal in forbidden_warnings.items():
self.forbidden_warnings[warning.symbol] = literal

for (error, name), literal in ignored_warnings.items():
for warning, literal in ignored_warnings.items():
# Initially, set to False, and only set to True if the warning is actually observed
# The actual value is set in the check function
self.ignored_warnings[error] = literal, False
self.ignored_warnings[warning.symbol] = literal, False

# If a forbidden warning exists already, add empty constraint to make the program unsat
# Since the warning comes from just reading the input
Expand Down
6 changes: 3 additions & 3 deletions src/constraint_handler/propagator/optimization_modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,11 @@ def get_optimization_sums(
"""
max_sums = myClorm.findInPropagateInit(ctl, prop_atom.Propagator_optimize_maximizeSum)

for (expr, symbol, priority, _), literal in max_sums.items():
value = get_variable_value(expr, literal)
for atom, literal in max_sums.items():
value = get_variable_value(atom.value, literal)
add_watch(literal)
add_watch(-literal)
self.add_value(symbol, value, priority)
self.add_value(atom.id, value, atom.priority)

self.initialize_best_value()

Expand Down
Loading
Loading