def sort(x): if type(x) == bool: return BoolSort() elif type(x) == int: return IntSort() elif type(x) == float: return RealSort() elif hasattr(x, 'sort'): if x.sort() == BoolSort(): return BoolSort() if x.sort() == IntSort(): return IntSort() if x.sort() == RealSort(): return RealSort() else: raise Exception('unknown sort for expression')
def set_sort(sort_dom, sort_ran): global SORT_DOM SORT_DOM = sort_dom global SORT_RAN SORT_RAN = sort_ran global REL_SORT REL_SORT = ArraySort(sort_dom, ArraySort(sort_ran, BoolSort()))
def declare_predicate(self, elem_predicate: Predicate): arg_types = [ x.get_engine_obj(self._name) for x in elem_predicate.get_arg_types() ] arg_types += [BoolSort()] rel = Function(elem_predicate.get_name(), *arg_types) self._solver.register_relation(rel) elem_predicate.add_engine_object(rel)
def snakes_find_the_head(g): # We'll want a type that represents a cell in the grid. We use a datatype because we can make it a sum type - # that is, its 0-arity constructors represent a closed enumeration of distinct objects. Cell = Datatype("Cell") for x, y in g.coords(): if g.snake(x, y) is not None: Cell.declare("cell_{}_{}".format(x, y)) Cell = Cell.create() # We'll have two functions that we explicitly declare. One is the short-distance "connected" relationship. # The other is a convenience function for turning the coordinates of a cell into the datatype member that # represents that position. Connected = Function("Connected", Cell, Cell, BoolSort()) XYToCell = Function("XYToCell", IntSort(), IntSort(), Cell) cell = {} for x, y in g.coords(): if g.snake(x, y) is not None: cell[x, y] = getattr(Cell, "cell_{}_{}".format(x, y)) g.add(XYToCell(x, y) == cell[x, y]) # Two cells are connected *if and only* if they are adjacent and both hold snakes # We need to be really clear about the "and only if" part; a naive implementation here will let the # solver fill in other arbitrary values for `Connected` in order to make the desired outcome true. # We do this by ensuring there's a value declared for our Connected relationship between every pair # of potential arguments. for x1, y1 in g.coords(): c1 = g.snake(x1, y1) if c1 is None: continue # If there's a snake here, the cell is connected to itself g.add(Connected(cell[x1, y1], cell[x1, y1]) == c1) for x2, y2 in g.coords(): c2 = g.snake(x2, y2) if c2 is None or (x1, y1) == (x2, y2): continue if manh(x1, y1, x2, y2) == 1: g.add(Connected(cell[x1, y1], cell[x2, y2]) == And(c1, c2)) else: # Without this, our function declaration is only partial. The solver can fill in missing values # in order to scupper our good intentions. g.add(Not(Connected(cell[x1, y1], cell[x2, y2]))) # The transitive closure of Connectedness is Reaches Reaches = TransitiveClosure(Connected) # For every cell in the grid, if it's a snake then we can connect it to the head position hx, hy = g.head() for x, y in g.coords(): c = g.snake(x, y) if c is None: continue g.add(Implies(c, Reaches(cell[x, y], XYToCell(hx, hy))))
def GetValFromType(typ, raw_val): srt = GetSortFromType(typ) if srt == IntSort(): return IntVal(raw_val) elif srt == BoolSort(): return BoolVal(raw_val) elif is_bv_sort(srt): sz = srt.size() return BitVecVal(raw_val, sz) else: raise SynthException('Unknown sort')
def GetStringFromType(typ): srt = GetSortFromType(typ) if srt == IntSort(): return 'Int' elif srt == BoolSort(): return 'Bool' elif is_bv_sort(srt): sz = srt.size() return '(BitVec ' + str(sz) + ')' else: raise SynthException('Unknonw sort for string conversion.')
def GetSortFromType(typ): if typ == 'Int': return IntSort() elif typ == 'Bool': return BoolSort() elif isinstance(typ, list): if (len(typ) != 2 or typ[0] != 'BitVec'): raise SynthException('Unknown Type %r' % (typ)) else: intName, size = typ[1] return BitVecSort(size) else: raise SynthException('Unknown Type %r' % (typ))
## Qui a tué le chat? from z3 import Function, EnumSort, BoolSort, ForAll, Solver, Implies, Const, Consts, Exists, Not, And, Or # type et ses constantes Entity, (jack, luna, curiosity) = EnumSort('Entity', ('jack', 'luna', 'curiosity')) Animal = Function('Animal', Entity, BoolSort()) Aimer = Function('Aimer', Entity, Entity, BoolSort()) Tuer = Function('Tuer', Entity, Entity, BoolSort()) s = Solver() x, y, z = Consts('x y z', Entity) # Tous ceux qui aiment tous les animaux sont aimés par qqun s.add( ForAll( x, Implies(ForAll(y, Implies(Animal(y), Aimer(x, y))), Exists(z, Aimer(z, x))))) # Quiconque tue un animal n’est aimé par personne s.add( ForAll( x, Implies(Exists(y, And(Animal(y), Tuer(x, y))), ForAll(z, Not(Exists(z, Aimer(z, x))))))) # Jack aime tous les animaux s.add(ForAll(x, Implies(Animal(x), Aimer(jack, x)))) # C’est soit Jack soit Curiosité qui a tué le chat appelé Luna s.add(Or(Tuer(jack, luna), Tuer(curiosity, luna)))
# We need to declare the variables fist. x = Const('x', Person) # This x defined on the domain of Person y = Const('y', Person) # And this is y return ForAll([x, y],Xor(x == y, R(x) != R(y))) # ForAll expression # In addition to a function for the role of a person, we also need # to be able to write predicates about a their statements in order # to encode the essence of sentences such as "A lies", # and "That (referring to the previous speaker) is not true". # # To do that we use a function from Person to Bool which is True if # the claim is that the person tells the truth, and False otherwise. # Call it S : Person -> Bool S = Function('S', Person, BoolSort()) # Here BoolSort() just says that the return type is of type Bool. # Now using both R and S, we can encode the general rules of the game: # 2, That a Knight must tell the Truth. # For a specific person, say B this would be (R(B) = Knight) ⇒ S(B), encoded # as Implies(R(B) == Knight, S(B)), but we use the ∀x quantifier # and write for all persons: def knights_tell_truths(): """ Encodes 'Knights always tell the truth'. In other terms: for all persons, being a knight implies telling the truth.
# encoding: utf-8 from z3 import Datatype, BoolSort, IntSort, ArraySort, And, Not from .meyer import U from .util.z3py_set import Set from .util.z3py_rel import Rel from .util.z3py_util import const, consts, show_record_element ## @file program.py # This module can be used for definition of specification/program instance # # SET = ArraySort(U, BoolSort()) # OOPSet = ArraySort(IntSort(), ArraySort(U, BoolSort())) PRE = ArraySort(U, BoolSort()) POST = ArraySort(U, ArraySort(U, BoolSort())) PROG = Datatype('Prog') PROG.declare('mk_prog', ('set', SET), ('pre', PRE), ('post', POST)) PROG = PROG.create() set_ = PROG.set pre_ = PROG.pre post_ = PROG.post class Program(): """Base class for Program instance.""" # @param p A program instance created by Z3.py. def __init__(self, p): self.p = p
def booleanp(self, x): return sort(x) == BoolSort()
""" from z3 import Datatype, ArraySort, IntSort, BoolSort, Function, Const from z3_helpers import Iff, Equals # Node is a datatype representing a vertex or node in a Kappa graph. Node = Datatype('Node') Node.declare('node', ('unique_identifier', IntSort())) Node = Node.create() # A datatype for storing a pair of edges Edge = Datatype('Edge') Edge.declare('edge', ('node1', Node), ('node2', Node)) Edge = Edge.create() Nodeset = ArraySort(Node, BoolSort()) Edgeset = ArraySort(Edge, BoolSort()) Labelset = ArraySort(IntSort(), BoolSort()) Labelmap = ArraySort(Node, Labelset) # Graph, before a rule or action has applied. Merged Pregraph and Postgraph # into a single datatype. Graph = Datatype('Graph') Graph.declare('graph', ('has', Nodeset), ('links', Edgeset), ('parents', Edgeset), ('labelmap', Labelmap)) Graph = Graph.create() # Atomic action. An Action is comprised of a set of these. AtomicAction = Datatype('AtomicAction') AtomicAction.declare('id_action')
## Les dragons chinois from z3 import Function, EnumSort, BoolSort, ForAll, Solver, Implies, Const, Consts, Exists, Not, And, Or animal, (dragon) = EnumSort('animal', ('dragon')) humain, (touriste) = EnumSort('humain', ('touriste')) est_fort = Function('est_fort', animal, BoolSort()) souffler_feu = Function('souffler_feu', animal, BoolSort()) # Formaliser les phrases suivantes : # Aucun dragon fort ne peut ne pas souffler le feu. # Un dragon rusé a toujours des cornes. # Aucun dragon faible n’a des cornes. # Les touristes ne chassent que les dragons ne soufflant pas le feu. # On veut répondre à la question suivante : # Un dragon rusé doit-il craindre les touristes ? (autrement dit : est-il chassé ?) """ # Corrigé from z3 import * Dragon, (drago,) = EnumSort('Dragon', ('drago',)) fort = Function('fort',Dragon,BoolSort()) feu = Function('feu',Dragon,BoolSort()) ruse = Function('ruse',Dragon,BoolSort()) cornes = Function('cornes',Dragon,BoolSort()) chasse = Function('chasse',Dragon,BoolSort())
else: GDDeg = GDDeg + 360; if (abs(GDDeg) > 180): if (GDDeg > 180): GDDeg = GDDeg - 360 if (GDDeg < (-180)): GDDeg = GDDeg + 360 ## print ("GDDeg:",GDDeg) ## print ("#################################") return [Dist, DDeg, GDDeg] true = BoolSort().cast(True) false = BoolSort().cast(False) reset = Bool('reset') BInRobot = Bool('BInRobot') forward,spin, Su = Ints('forward spin Su') dist = Real( 'dist') degToBall = Real( 'degToBall') degToGoal = Real( 'degToGoal') # B-Threads global TooFar, TooClose, MaxPower, MaxSpin, MaxAngToBall, MaxAngToGoal TooFar=5 TooClose=3.7 MaxPower=100
def set_sort(sort): global SORT SORT = sort global SET_SORT SET_SORT = ArraySort(sort, BoolSort())
# encoding: utf-8 import inspect from z3 import ArraySort, BoolSort, EnumSort, ForAll, Exists, And, Or, Not, Implies from .z3py_util import U, const, evaluate SORT = U SET_SORT = ArraySort(U, BoolSort()) def set_sort(sort): global SORT SORT = sort global SET_SORT SET_SORT = ArraySort(sort, BoolSort()) def get_sort(): global SORT sort = SORT return sort class Set(): """Base class for set instance.""" # @param p A set instance created by Z3.py. def __init__(self, s): self.s = s def __call__(self, x): return self.has(x)
from z3 import Not, And, ForAll, Implies, IntSort, BoolSort, Solver, Function, Int __counter = 100 __agents = {} def new_noun(name): global __counter global __agents if name not in __agents: __agents[name] = __counter __counter += 1 return Int(__agents[name]) IsKinase = Function("is_kinase", IntSort(), BoolSort()) IsActiveWhenPhosphorylated = Function("is_active_when_phosphorylated", IntSort(), BoolSort()) Phosphorylates = Function("phosphorylates", IntSort(), IntSort(), BoolSort()) Activates = Function("activates", IntSort(), IntSort(), BoolSort()) ActivityIncreasesActivity = Function("activity_increases_activity", IntSort(), IntSort(), BoolSort()) solver = Solver() MEK1 = new_noun("MEK1") ERK1 = new_noun("ERK1") RAF = new_noun("RAF") HRAS = new_noun("HRAS")
# encoding: utf-8 import inspect from z3 import ArraySort, BoolSort, EnumSort, ForAll, Exists, And, Or, Not, Implies from .z3py_set import Set from .z3py_util import U, const, unveil, model SORT_DOM = U SORT_RAN = U REL_SORT = ArraySort(U, ArraySort(U, BoolSort())) def set_sort(sort_dom, sort_ran): global SORT_DOM SORT_DOM = sort_dom global SORT_RAN SORT_RAN = sort_ran global REL_SORT REL_SORT = ArraySort(sort_dom, ArraySort(sort_ran, BoolSort())) def get_sort_dom(): global SORT_DOM sort_dom = SORT_DOM return sort_dom def get_sort_ran(): global SORT_RAN sort_ran = SORT_RAN return sort_ran
def new_modelset(nickname='modelset'): return Function(_collision_free_string(nickname), Model, BoolSort())
#!/usr/bin/env python # from TU Graz presentation by Vedad Hadzic from z3 import Solver, Int, IntSort, BoolSort, Function from z3 import ForAll, And, Or, Not, Implies, sat as SAT # create an integer and a function x = Int("x") f = Function("f", IntSort(), IntSort(), BoolSort()) solver = Solver() solver.add(ForAll([x], Implies(And(x > 0, x < 4), f(x, x)))) solver.add(ForAll([x], Implies(Or(x <= 0, x >= 4), Not(f(x, x))))) if solver.check() != SAT: exit(1) m = solver.model() print(f'f(0,0)={m.eval(f(0,0))}') print(f'f(1,2)={m.eval(f(1,2))}') print(f'f(2,3)={m.eval(f(2,3))}') print(f'f(3,3)={m.eval(f(3,3))}') for i in range(0, 5): # assert ∀ x in (0,4). f(x,x) = 1 # check if satisfiable # get the solution # print the relation table vs = [int(bool(m.eval(f(i, j)))) for j in range(0, 5)]
def __init__(self, input_program: InputProgram, settings: SmtSettings): self.input_program = input_program self.settings = settings env = SmtEnv(input_program.module, settings.forall_mode, self) self.env = env self.frame = env.function("Frame", RealSort()) if settings.forall_mode == ForallMode.FORALL_GLOBALS: self.frames: List[z3.ExprRef] = [] old_command = None j = 0 for i, subst in enumerate(env.macro_substs): frame_i = env.function("F%s" % i, RealSort()) self.frames.append(frame_i) subst.append((env.apply_to_state_valuation(self.frame), env.apply_to_state_valuation(frame_i))) cur_command = self.env.subst_index_to_command[i] if cur_command != old_command: old_command = cur_command j = 0 else: j = j + 1 self.env.command_to_substs[cur_command][j].append((env.apply_to_state_valuation(self.frame), env.apply_to_state_valuation(frame_i))) self.phi = env.function("Phi", RealSort()) self.goal_expr = input_program.goal if settings.inline_goal else env.apply_to_state_valuation(env.function("Goal", BoolSort())) self.chosen_command = INPUTPROGRAM.INT_CTOR("ChosenCommand") self._initial_formulae: Union[None, List[z3.ExprRef]] = None
print(problem) # declare finite data type mansion MansionDT = Datatype("Mansion") MansionDT.declare("Agatha") MansionDT.declare("Butler") MansionDT.declare("Charles") # create finite sort Mansion Mansion = MansionDT.create() # constants for ease of reference a, b, c = Mansion.Agatha, Mansion.Butler, Mansion.Charles # declare predicates killed = Function("killed", Mansion, Mansion, BoolSort()) hates = Function("hates", Mansion, Mansion, BoolSort()) richer = Function("richer", Mansion, Mansion, BoolSort()) # quantified variables x = Const("x", Mansion) y = Const("y", Mansion) e1 = Exists([x], killed(x, a)) e2a = ForAll([x, y], Implies(killed(x, y), hates(x, y))) e2b = ForAll([x, y], Implies(killed(x, y), Not(richer(x, y)))) e3 = ForAll([x], Implies(hates(a, x), Not(hates(c, x)))) e4a = hates(a, a) e4b = hates(a, c) e5 = ForAll([x], Implies(Not(richer(x, a)), hates(b, x))) e6 = ForAll([x], Implies(hates(a, x), hates(b, x)))