Z3
Loading...
Searching...
No Matches
Optimize Class Reference
Inheritance diagram for Optimize:

Public Member Functions

 __init__ (self, optimize=None, ctx=None)
 __copy__ (self)
 __deepcopy__ (self, memo={})
 __del__ (self)
 __enter__ (self)
 __exit__ (self, *exc_info)
 set (self, *args, **keys)
 help (self)
 param_descrs (self)
 assert_exprs (self, *args)
 add (self, *args)
 __iadd__ (self, fml)
 assert_and_track (self, a, p)
 add_soft (self, arg, weight="1", id=None)
 set_initial_value (self, var, value)
 maximize (self, arg)
 minimize (self, arg)
 push (self)
 pop (self)
 check (self, *assumptions)
 reason_unknown (self)
 model (self)
 unsat_core (self)
 lower (self, obj)
 upper (self, obj)
 lower_values (self, obj)
 upper_values (self, obj)
 from_file (self, filename)
 from_string (self, s)
 assertions (self)
 objectives (self)
 __repr__ (self)
 sexpr (self)
 statistics (self)
 translate (self, target)
 set_on_model (self, on_model)
Public Member Functions inherited from Z3PPObject
 use_pp (self)

Data Fields

 ctx = _get_ctx(ctx)
 optimize = Z3_mk_optimize(self.ctx.ref())

Protected Attributes

 _on_models_id = None

Additional Inherited Members

Protected Member Functions inherited from Z3PPObject
 _repr_html_ (self)

Detailed Description

Optimize API provides methods for solving using objective functions and weighted soft constraints

Definition at line 8577 of file z3py.py.

Constructor & Destructor Documentation

◆ __init__()

__init__ ( self,
optimize = None,
ctx = None )

Definition at line 8580 of file z3py.py.

8580 def __init__(self, optimize=None, ctx=None):
8581 self.ctx = _get_ctx(ctx)
8582 if optimize is None:
8583 self.optimize = Z3_mk_optimize(self.ctx.ref())
8584 else:
8585 self.optimize = optimize
8586 self._on_models_id = None
8587 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8588
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.

◆ __del__()

__del__ ( self)

Definition at line 8595 of file z3py.py.

8595 def __del__(self):
8596 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8597 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8598 if self._on_models_id is not None:
8599 del _on_models[self._on_models_id]
8600
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.

Member Function Documentation

◆ __copy__()

__copy__ ( self)

Definition at line 8589 of file z3py.py.

8589 def __copy__(self):
8590 return self.translate(self.ctx)
8591

◆ __deepcopy__()

__deepcopy__ ( self,
memo = {} )

Definition at line 8592 of file z3py.py.

8592 def __deepcopy__(self, memo={}):
8593 return self.translate(self.ctx)
8594

◆ __enter__()

__enter__ ( self)

Definition at line 8601 of file z3py.py.

8601 def __enter__(self):
8602 self.push()
8603 return self
8604

◆ __exit__()

__exit__ ( self,
* exc_info )

Definition at line 8605 of file z3py.py.

8605 def __exit__(self, *exc_info):
8606 self.pop()
8607

◆ __iadd__()

__iadd__ ( self,
fml )

Definition at line 8639 of file z3py.py.

8639 def __iadd__(self, fml):
8640 self.add(fml)
8641 return self
8642

◆ __repr__()

__repr__ ( self)
Return a formatted string with all added rules and constraints.

Definition at line 8786 of file z3py.py.

8786 def __repr__(self):
8787 """Return a formatted string with all added rules and constraints."""
8788 return self.sexpr()
8789

◆ add()

add ( self,
* args )
Assert constraints as background axioms for the optimize solver. Alias for assert_expr.

Definition at line 8635 of file z3py.py.

8635 def add(self, *args):
8636 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8637 self.assert_exprs(*args)
8638

◆ add_soft()

add_soft ( self,
arg,
weight = "1",
id = None )
Add soft constraint with optional weight and optional identifier.
   If no weight is supplied, then the penalty for violating the soft constraint
   is 1.
   Soft constraints are grouped by identifiers. Soft constraints that are
   added without identifiers are grouped by default.

Definition at line 8672 of file z3py.py.

8672 def add_soft(self, arg, weight="1", id=None):
8673 """Add soft constraint with optional weight and optional identifier.
8674 If no weight is supplied, then the penalty for violating the soft constraint
8675 is 1.
8676 Soft constraints are grouped by identifiers. Soft constraints that are
8677 added without identifiers are grouped by default.
8678 """
8679 if _is_int(weight):
8680 weight = "%d" % weight
8681 elif isinstance(weight, float):
8682 weight = "%f" % weight
8683 if not isinstance(weight, str):
8684 raise Z3Exception("weight should be a string or an integer")
8685 if id is None:
8686 id = ""
8687 id = to_symbol(id, self.ctx)
8688
8689 def asoft(a):
8690 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8691 return OptimizeObjective(self, v, False)
8692 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8693 return [asoft(a) for a in arg]
8694 return asoft(arg)
8695
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.

◆ assert_and_track()

assert_and_track ( self,
a,
p )
Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.

If `p` is a string, it will be automatically converted into a Boolean constant.

>>> x = Int('x')
>>> p3 = Bool('p3')
>>> s = Optimize()
>>> s.assert_and_track(x > 0,  'p1')
>>> s.assert_and_track(x != 1, 'p2')
>>> s.assert_and_track(x < 0,  p3)
>>> print(s.check())
unsat
>>> c = s.unsat_core()
>>> len(c)
2
>>> Bool('p1') in c
True
>>> Bool('p2') in c
False
>>> p3 in c
True

Definition at line 8643 of file z3py.py.

8643 def assert_and_track(self, a, p):
8644 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8645
8646 If `p` is a string, it will be automatically converted into a Boolean constant.
8647
8648 >>> x = Int('x')
8649 >>> p3 = Bool('p3')
8650 >>> s = Optimize()
8651 >>> s.assert_and_track(x > 0, 'p1')
8652 >>> s.assert_and_track(x != 1, 'p2')
8653 >>> s.assert_and_track(x < 0, p3)
8654 >>> print(s.check())
8655 unsat
8656 >>> c = s.unsat_core()
8657 >>> len(c)
8658 2
8659 >>> Bool('p1') in c
8660 True
8661 >>> Bool('p2') in c
8662 False
8663 >>> p3 in c
8664 True
8665 """
8666 if isinstance(p, str):
8667 p = Bool(p, self.ctx)
8668 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8669 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8670 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8671
void Z3_API Z3_optimize_assert_and_track(Z3_context c, Z3_optimize o, Z3_ast a, Z3_ast t)
Assert tracked hard constraint to the optimization context.

◆ assert_exprs()

assert_exprs ( self,
* args )
Assert constraints as background axioms for the optimize solver.

Definition at line 8623 of file z3py.py.

8623 def assert_exprs(self, *args):
8624 """Assert constraints as background axioms for the optimize solver."""
8625 args = _get_args(args)
8626 s = BoolSort(self.ctx)
8627 for arg in args:
8628 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8629 for f in arg:
8630 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8631 else:
8632 arg = s.cast(arg)
8633 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8634
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.

◆ assertions()

assertions ( self)
Return an AST vector containing all added constraints.

Definition at line 8778 of file z3py.py.

8778 def assertions(self):
8779 """Return an AST vector containing all added constraints."""
8780 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8781
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.

◆ check()

check ( self,
* assumptions )
Check consistency and produce optimal values.

Definition at line 8727 of file z3py.py.

8727 def check(self, *assumptions):
8728 """Check consistency and produce optimal values."""
8729 assumptions = _get_args(assumptions)
8730 num = len(assumptions)
8731 _assumptions = (Ast * num)()
8732 for i in range(num):
8733 _assumptions[i] = assumptions[i].as_ast()
8734 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8735
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.

◆ from_file()

from_file ( self,
filename )
Parse assertions and objectives from a file

Definition at line 8770 of file z3py.py.

8770 def from_file(self, filename):
8771 """Parse assertions and objectives from a file"""
8772 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8773
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives....

◆ from_string()

from_string ( self,
s )
Parse assertions and objectives from a string

Definition at line 8774 of file z3py.py.

8774 def from_string(self, s):
8775 """Parse assertions and objectives from a string"""
8776 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8777
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives....

◆ help()

help ( self)
Display a string describing all available options.

Definition at line 8615 of file z3py.py.

8615 def help(self):
8616 """Display a string describing all available options."""
8617 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8618
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.

◆ lower()

lower ( self,
obj )

Definition at line 8750 of file z3py.py.

8750 def lower(self, obj):
8751 if not isinstance(obj, OptimizeObjective):
8752 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8753 return obj.lower()
8754

◆ lower_values()

lower_values ( self,
obj )

Definition at line 8760 of file z3py.py.

8760 def lower_values(self, obj):
8761 if not isinstance(obj, OptimizeObjective):
8762 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8763 return obj.lower_values()
8764

◆ maximize()

maximize ( self,
arg )
Add objective function to maximize.

Definition at line 8703 of file z3py.py.

8703 def maximize(self, arg):
8704 """Add objective function to maximize."""
8705 return OptimizeObjective(
8706 self,
8707 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8708 is_max=True,
8709 )
8710
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.

◆ minimize()

minimize ( self,
arg )
Add objective function to minimize.

Definition at line 8711 of file z3py.py.

8711 def minimize(self, arg):
8712 """Add objective function to minimize."""
8713 return OptimizeObjective(
8714 self,
8715 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8716 is_max=False,
8717 )
8718
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.

◆ model()

model ( self)
Return a model for the last check().

Definition at line 8740 of file z3py.py.

8740 def model(self):
8741 """Return a model for the last check()."""
8742 try:
8743 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8744 except Z3Exception:
8745 raise Z3Exception("model is not available")
8746
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.

◆ objectives()

objectives ( self)
returns set of objective functions

Definition at line 8782 of file z3py.py.

8782 def objectives(self):
8783 """returns set of objective functions"""
8784 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8785
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...

◆ param_descrs()

param_descrs ( self)
Return the parameter description set.

Definition at line 8619 of file z3py.py.

8619 def param_descrs(self):
8620 """Return the parameter description set."""
8621 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8622
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.

◆ pop()

pop ( self)
restore to previously created backtracking point

Definition at line 8723 of file z3py.py.

8723 def pop(self):
8724 """restore to previously created backtracking point"""
8725 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8726
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.

◆ push()

push ( self)
create a backtracking point for added rules, facts and assertions

Definition at line 8719 of file z3py.py.

8719 def push(self):
8720 """create a backtracking point for added rules, facts and assertions"""
8721 Z3_optimize_push(self.ctx.ref(), self.optimize)
8722
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.

◆ reason_unknown()

reason_unknown ( self)
Return a string that describes why the last `check()` returned `unknown`.

Definition at line 8736 of file z3py.py.

8736 def reason_unknown(self):
8737 """Return a string that describes why the last `check()` returned `unknown`."""
8738 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8739
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.

◆ set()

set ( self,
* args,
** keys )
Set a configuration option.
The method `help()` return a string containing all available options.

Definition at line 8608 of file z3py.py.

8608 def set(self, *args, **keys):
8609 """Set a configuration option.
8610 The method `help()` return a string containing all available options.
8611 """
8612 p = args2params(args, keys, self.ctx)
8613 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8614
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.

◆ set_initial_value()

set_initial_value ( self,
var,
value )
initialize the solver's state by setting the initial value of var to value

Definition at line 8696 of file z3py.py.

8696 def set_initial_value(self, var, value):
8697 """initialize the solver's state by setting the initial value of var to value
8698 """
8699 s = var.sort()
8700 value = s.cast(value)
8701 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8702
void Z3_API Z3_optimize_set_initial_value(Z3_context c, Z3_optimize o, Z3_ast v, Z3_ast val)
provide an initialization hint to the solver. The initialization hint is used to calibrate an initial...

◆ set_on_model()

set_on_model ( self,
on_model )
Register a callback that is invoked with every incremental improvement to
objective values. The callback takes a model as argument.
The life-time of the model is limited to the callback so the
model has to be (deep) copied if it is to be used after the callback

Definition at line 8814 of file z3py.py.

8814 def set_on_model(self, on_model):
8815 """Register a callback that is invoked with every incremental improvement to
8816 objective values. The callback takes a model as argument.
8817 The life-time of the model is limited to the callback so the
8818 model has to be (deep) copied if it is to be used after the callback
8819 """
8820 id = len(_on_models) + 41
8821 mdl = Model(self.ctx)
8822 _on_models[id] = (on_model, mdl)
8823 self._on_models_id = id
8825 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8826 )
8827
8828
void Z3_API Z3_optimize_register_model_eh(Z3_context c, Z3_optimize o, Z3_model m, void *ctx, Z3_model_eh model_eh)
register a model event handler for new models.

◆ sexpr()

sexpr ( self)
Return a formatted string (in Lisp-like format) with all added constraints.
We say the string is in s-expression format.

Definition at line 8790 of file z3py.py.

8790 def sexpr(self):
8791 """Return a formatted string (in Lisp-like format) with all added constraints.
8792 We say the string is in s-expression format.
8793 """
8794 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8795
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.

◆ statistics()

statistics ( self)
Return statistics for the last check`.

Definition at line 8796 of file z3py.py.

8796 def statistics(self):
8797 """Return statistics for the last check`.
8798 """
8799 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8800
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.

◆ translate()

translate ( self,
target )
Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.

>>> c1 = Context()
>>> c2 = Context()
>>> o1 = Optimize(ctx=c1)
>>> o2 = o1.translate(c2)

Definition at line 8801 of file z3py.py.

8801 def translate(self, target):
8802 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8803
8804 >>> c1 = Context()
8805 >>> c2 = Context()
8806 >>> o1 = Optimize(ctx=c1)
8807 >>> o2 = o1.translate(c2)
8808 """
8809 if z3_debug():
8810 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8811 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8812 return Optimize(opt, target)
8813
Z3_optimize Z3_API Z3_optimize_translate(Z3_context c, Z3_optimize o, Z3_context target)
Copy an optimization context from a source to a target context.

◆ unsat_core()

unsat_core ( self)

Definition at line 8747 of file z3py.py.

8747 def unsat_core(self):
8748 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8749
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...

◆ upper()

upper ( self,
obj )

Definition at line 8755 of file z3py.py.

8755 def upper(self, obj):
8756 if not isinstance(obj, OptimizeObjective):
8757 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8758 return obj.upper()
8759

◆ upper_values()

upper_values ( self,
obj )

Definition at line 8765 of file z3py.py.

8765 def upper_values(self, obj):
8766 if not isinstance(obj, OptimizeObjective):
8767 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8768 return obj.upper_values()
8769

Field Documentation

◆ _on_models_id

_on_models_id = None
protected

Definition at line 8586 of file z3py.py.

◆ ctx

ctx = _get_ctx(ctx)

Definition at line 8581 of file z3py.py.

◆ optimize

optimize = Z3_mk_optimize(self.ctx.ref())

Definition at line 8583 of file z3py.py.