Example #1
0
def get_distances(indexes):
    X = [Int("x_%s" % i) for i in range(len(indexes))]
    csts = And([
        X[i] - X[j] <= indexes[i][1] for (i, j) in zip(range(len(indexes)),
                                                       range(len(indexes))[1:])
    ])
    csts2 = And([(X[i] - X[j] >= 0)
                 for (i, j) in zip(range(len(indexes)),
                                   range(len(indexes))[1:])])
    csts = And(csts, csts2)
    Y = [Int("y_%s" % i) for i in range(20)]
    prod = product(*[range(len(indexes))], *[(range(20))])
    val_csts = And([])
    for a in prod:
        #this is for each possible assignment
        A = And([X[w - 1] == t for (w, t) in enumerate(a)])
        B = And([])
        _v = 0
        for start in [0, 1]:
            while (_v < len(a)):
                if _v in a:
                    start = flip(start)
                B = And(B, Y[_v] == start)
                _v += 1
        val_csts = Or(Or(val_csts, A), B)
        #val_csts = And([i for i in range(10)])

    #val_csts = Or(And(([X[i] == 1 for i in range(20)]), [Y[1] == 1 for i in range(20)]))
    return X, csts, Y, val_csts
Example #2
0
def Password():
    from z3 import Int, Solver

    Buffer = Int('Buffer')
    v9 = Int('v9')
    v10 = Int('v10')
    v11 = Int('v11')
    v12 = Int('v12')
    v13 = Int('v13')
    v14 = Int('v14')
    v15 = Int('v15')
    v16 = Int('v16')
    v17 = Int('v17')

    s = Solver()

    s.add(v14 + v15 == 205)
    s.add(v13 + v16 == 201)
    s.add(v11 + v14 + v15 == 314)
    s.add(v13 + v16 + v12 + v17 == 367)
    s.add(Buffer + v9 == 194)
    s.add(v17 + v16 + v15 + v14 + v13 + v12 + v11 + v10 + v9 + Buffer == 923)
    s.add(v16 == 85)
    s.add(Buffer + v10 == 128)
    s.add(v12 - v15 == -50)
    s.add(v14 + v17 == 219)

    return "Status : %s \nPassword = %s" % (
        s.check(),
        chr(s.model()[Buffer].as_long()) + chr(s.model()[v9].as_long()) +
        chr(s.model()[v10].as_long()) + chr(s.model()[v11].as_long()) +
        chr(s.model()[v12].as_long()) + chr(s.model()[v13].as_long()) +
        chr(s.model()[v14].as_long()) + chr(s.model()[v15].as_long()) +
        chr(s.model()[v16].as_long()) + chr(s.model()[v17].as_long()))
Example #3
0
def main(args):
    data = [extract(s.strip()) for s in sys.stdin]
    data = [(x[3], tuple(x[:-1])) for x in data]
    m = max(data)
    in_range = [x for x in data if dist(x[1], m[1]) <= m[0]]
    print(len(in_range))

    x = Int('x')
    y = Int('y')
    z = Int('z')
    orig = (x, y, z)
    cost = Int('cost')
    cost_expr = x * 0
    for r, pos in data:
        cost_expr += If(z3_dist(orig, pos) <= r, 1, 0)
    opt = Optimize()
    print("let's go")
    opt.add(cost == cost_expr)
    opt.maximize(cost)
    # I didn't do this step in my initial #2 ranking solution but I
    # suppose you should.
    # z3 does them lexicographically by default.
    opt.minimize(z3_dist((0, 0, 0), (x, y, z)))

    opt.check()

    model = opt.model()
    #    print(model)
    pos = (model[x].as_long(), model[y].as_long(), model[z].as_long())
    print("position:", pos)
    print("num in range:", model[cost].as_long())
    print("distance:", dist((0, 0, 0), pos))
Example #4
0
def main():
    bots = []

    with open("input.txt") as f:
        for line in f:
            bots.append(tuple(map(int, re.findall(r"-?\d+", line))))

    x, y, z, r = max(bots, key=lambda b: b[3])
    in_range = sum(
        (abs(x - b[0]) + abs(y - b[1]) + abs(z - b[2]) <= r) for b in bots)
    print("Part 1:", in_range)

    x, y, z = Int("x"), Int("y"), Int("z")
    point = (x, y, z)
    count = sum(If(z3_dist(b[:3], point) <= b[3], 1, 0) for b in bots)

    opt = Optimize()
    opt.maximize(count)
    opt.minimize(z3_dist(point, (0, 0, 0)))

    opt.check()
    model = opt.model()
    result = model[x].as_long() + model[y].as_long() + model[z].as_long()

    print("Part 2:", result)
Example #5
0
 def load(self, start, length):
     if start not in self._memory.keys():
         return Int("M_{0}_{1}".format(start, length))
     tmp: MemoryItem = self._memory[start]
     if tmp.length == length:
         return tmp.content
     return Int("M_{0}_{1}".format(start, length))
Example #6
0
def add_area_constraints(lattice, sc):
    """Ensure each area of the puzzle contains exactly one tetrahex."""
    for area_label in {c for line in AREAS for c in line}:
        area_points = []
        area_type_cells = []
        area_instance_cells = []
        for p in lattice.points:
            r, c = point_to_areas_row_col(p)
            if AREAS[r][c] == area_label:
                area_points.append(p)
                area_type_cells.append(sc.shape_type_grid[p])
                area_instance_cells.append(sc.shape_instance_grid[p])

        area_type = Int(f"at-{area_label}")
        sc.solver.add(area_type >= 0)
        sc.solver.add(area_type <= 4)
        sc.solver.add(
            And(*[Or(c == -1, c == area_type) for c in area_type_cells]))

        area_instance = Int(f"ai-{area_label}")
        sc.solver.add(
            Or(*[
                area_instance == lattice.point_to_index(p) for p in area_points
            ]))
        sc.solver.add(
            And(*
                [Or(c == -1, c == area_instance)
                 for c in area_instance_cells]))

        sc.solver.add(PbEq([(c != -1, 1) for c in area_type_cells], 4))
Example #7
0
    def __init__(self, id:int, gate:Gate, prev:OrderedDict[int,Instruction], qubit_map:Dict[int, Qubit], other_args:List=[]):

        # The instructions numerical identifier
        self.id : int = id

        # The gate of the instruction
        self.gate : Gate = gate

        # A name for the instruction
        self.name : str = str(self.gate.name) + "_" + str(self.id)

        # Previous instructions in the dependency graph: those instrs that this one depends on
        self.prev : OrderedDict[int,Instruction] = prev

        # Available Qubits, mapped from their indices
        self.qubit_map: Dict[int, Qubit] = qubit_map

        # Qubit indicies applied to:
        # This is intuitively the primary mapping from "logical" indices to real ones. 
        # The consistency over the entire graph is maintained by the constraints.
        self.on_indices: OrderedDict[int, Int] = OrderedDict([(edge,Int(self.name+".edge_"+str(edge))) for edge in prev.keys()])

        # Time slot to run this instruction in
        self.time: Int = Int(self.name + ".timeslot")

        # Reliability of this instruction: depends on the operation and which qubit it's assigned to
        self.reliability: Real = Real(self.name + ".reliability")

        # Other args like rotations: TODO
        self.other_args: List = other_args
Example #8
0
def untimeshift(phi, times):
    for k, v in times.items():
        while v:
            phi = z3.substitute(phi, (Int(k + ("'" * v)), Int(k)))
            v -= 1

    return phi
Example #9
0
    def __init__(self, name: str, optional: bool) -> None:
        super().__init__(name)
        self.work_amount = 0
        self.priority = 1  # by default

        # required resources to perform the task
        self.required_resources = []  # type: List[Resource]

        # z3 Int variables
        self.start = Int("%s_start" % name)  # type: ArithRef
        self.end = Int("%s_end" % name)  # type: ArithRef
        self.duration = Int("%s_duration" % name)  # type: ArithRef

        # by default, the task is mandatory
        self.scheduled = True  # type: Union[bool, BoolRef]

        # but it can be se as optional. In that case, the self.scheduled
        # above flag will be overridden as a z3 BoolRef
        self.optional = optional  # type: bool

        # add this task to the current context
        if ps_context.main_context is None:
            raise AssertionError(
                "No context available. First create a SchedulingProblem"
            )
        # the task_number is an integer that is incremented each time
        # a task is created. The first task has number 1, the second number 2 etc.
        self.task_number = ps_context.main_context.add_task(self)  # type: int

        # the counter used for negative integers
        # negative integers are used to schedule optional tasks
        # for such tasks, they are actually scheduled in the past
        # with start_time = end_time is a negative point in the timeline
        self._current_negative_integer = 0  # type: int
Example #10
0
def add_optimize_targets2(solver, int_dict, order_dict):
    # new optimize target
    # A*o1+(1-A)*o2
    # o1 = AVG[v'(pkg)/|V(pkg)|] if v'(pkg)!=|V(pkg)| ((not installed))
    # o2 = (|P|-|P'|)/|P| if p is installed, p belongs to P'
    A = 0.5
    o1 = Real("o1")
    o2 = Real("o2")
    sum_ins = Int("sum_ins")
    sum_all = Int("sum_all")
    count_ins = Int("count_ins")
    sum_ins, sum_all, count_ins = 0, 0, 0

    count_all = 0
    for pkg in int_dict:
        sum_ins = If(int_dict[pkg] != len(order_dict[pkg]),
                     sum_ins + int_dict[pkg], sum_ins)
        count_ins = If(int_dict[pkg] != len(order_dict[pkg]), count_ins + 1,
                       count_ins)
        sum_all = If(int_dict[pkg] != len(order_dict[pkg]),
                     sum_all + len(order_dict[pkg]), sum_all)
        count_all += 1

    o1 = ToReal(sum_ins) / ToReal(sum_all)
    o2 = 1 - (ToReal(count_ins) / count_all)
    target = A * o1 + (1 - A) * o2
    solver.maximize(target)
    return solver
Example #11
0
def main():
    # 1. Create a list of z3 Int variables called prestate which is [x[0], x[1], x[2],....,x[15]]
    # use the range() function in Python and the parameter N
    # do not hardcode the list explicitly
    prestate = [Int("x["+str(i)+"]") for i in range(N)]
    # 2. create a list of z3 Int variables called poststate which is [x'[0], x'[1], x'[2],....,x'[N-1]]
    poststate = [Int("x'["+str(i)+"]") for i in range(N)]

    # Do not change
    # Defines init as prestate that is legal
    init = legal_config(prestate)

    # 3. Write the base_case predicate using the Implies() function of z3
    # base_case = Implies(And(bounds(prestate), init), invariant(prestate))
    base_case = Implies(init, invariant(prestate))

    # 4. Write the induction step predicate using the Implies() function of z3
    # prestate and poststate and transition_relation
    # ind_case = Implies(And(bounds(prestate), invariant(prestate), transition_relation(prestate, poststate)), And(bounds(poststate), invariant(poststate)))
    ind_case = Implies(And(invariant(prestate), transition_relation(prestate, poststate)), invariant(poststate))

    # Do not change
    print("## Proving base case:")
    prove(base_case)
    print("## Proving induction case")
    prove(ind_case)
Example #12
0
 def z3_solve(self, n, timeout_amount):
     """ Integer factorization using z3 theorem prover implementation:
     We can factor composite integers by SAT solving the model N=PQ directly using the clasuse (n==p*q),
     wich gives a lot of degree of freedom to z3, so we want to contraint the search space.
     Since every composite number n=pq, there always exists some p>sqrt(n) and q<sqrt(n).
     We can safely asume the divisor p is in the range n > p >= next_prime(sqrt(n)) 
     if this later clause doesn't hold and sqrt(p) is prime the number is a perfect square.
     We can also asume that p and q are alyaws odd otherwise our whole composite is even.
     Not all composite numbers generate a valid model that z3 can SAT.
     SAT solving is efficient with low bit count set in the factors, 
     the complexity of the algorithm grows exponential with every bit set.
     The problem of SAT solving integer factorization still is NP complete,
     making this just a showcase. Don't expect big gains.
     """
     s = Solver()
     s.set("timeout", timeout_amount * 1000)
     p = Int("p")
     q = Int("q")
     i = int(isqrt(n))
     np = int(next_prime(i))
     s.add(p * q == n, n > p, n > q, p >= np, q < i, q > 1, p > 1,
           q % 2 != 0, p % 2 != 0)
     try:
         s_check_output = s.check()
         if s_check_output == sat:
             res = s.model()
             P, Q = res[p].as_long(), res[q].as_long()
             assert P * Q == n
             return P, Q
         else:
             return None, None
     except:
         return None, None
Example #13
0
 def __init__(self, solver):
     self.solver = solver
     self.row_shifts = {r: Int(f"rowshift-{r}") for r in range(0, SIZE, 2)}
     self.col_shifts = {c: Int(f"colshift-{c}") for c in range(0, SIZE, 2)}
     for v in self.row_shifts.values():
         solver.add(Or(v == 0, v == 1))
     for v in self.col_shifts.values():
         solver.add(Or(v == 0, v == 1))
Example #14
0
    def GenerateAcycConstraints(self):
        constraints = [Bool(True)]

        for comp in self.components:
            for inputPort in comp.inputPorts:
                constraints.append(
                    Int(self.PN2LNMap[inputPort.name]) < Int(self.PN2LNMap[
                        comp.outputPort.name]))

        return And(constraints)
Example #15
0
    def __init__(self, function, meta):
        self.function = function
        self.meta = meta

        self.constraints = []

        _uuid = uuid.uuid4()
        self.z3_fun = Int(str(_uuid) + '_fun')
        self.z3_pin = Int(str(_uuid) + '_pin')
        self.z3_bus = Int(str(_uuid) + '_bus')
Example #16
0
    def GenerateDistinctOutputLabelConstraints(self):
        constraints = [Bool(True)]

        for i in range(len(self.components)):
            for j in range(i + 1, len(self.components)):
                dist_ij = (Int(
                    self.PN2LNMap[self.components[i].outputPort.name]) != Int(
                        self.PN2LNMap[self.components[j].outputPort.name]))
                constraints.append(dist_ij)

        return And(constraints)
Example #17
0
def generate_constraint_vars(source_loop_vars, sink_loop_vars):
    source_cvars = {}
    sink_cvars = {}
    source_step_cvars = {}
    sink_step_cvars = {}
    for v in source_loop_vars:
        source_cvars[v] = Int(f'{v}_source')
        source_step_cvars[v] = Int(f'{v}_step_source')
    for v in sink_loop_vars:
        sink_cvars[v] = Int(f'{v}_sink')
        sink_step_cvars[v] = Int(f'{v}_step_sink')
    return (source_cvars, sink_cvars, source_step_cvars, sink_step_cvars)
Example #18
0
 def as_formula(self):
     if self.is_top():
         return BoolVal(True)
     if self.is_bottom():
         return BoolVal(False)
     constraints = []
     for var in self.dict.keys():
         interval = self.dict[var]
         if not interval.is_high_inf():
             constraints.append(Int(var) <= IntVal(interval.high.n))
         if not interval.is_low_minf():
             constraints.append(Int(var) >= IntVal(interval.low.n))
     return And(constraints)
Example #19
0
def findConfig(ships, observations, dimensions=(10, 10)):
    (M, N) = dimensions
    NS = len(ships)
    s = Solver()
    W = map(lambda (w, h): w, ships)
    H = map(lambda (w, h): h, ships)
    (xs, ys, ds) = ([], [], [])
    for k in range(NS):
        xs.append(Int('x_%d' % k))
        ys.append(Int('y_%d' % k))
        ds.append(Bool('d_%d' % k))
        #assert that x,y are in the dimensions' range
        s.add(xs[k] < M, xs[k] >= 0, ys[k] < N, ys[k] >= 0)

    occupied = dict()
    observe = dict()

    for i in range(M):
        occupied[i] = dict()
        observe[i] = dict()
        for j in range(N):
            occupied[i][j] = dict()
            observe[i][j] = False
            for k in range(NS):
                rect1 = rect(xs[k], ys[k], W[k], H[k], i, j)
                rect2 = rect(xs[k], ys[k], H[k], W[k], i, j)
                occupied[i][j][k] = Or(And(ds[k], rect1),
                                       And(Not(ds[k]), rect2))
                observe[i][j] = Or(occupied[i][j][k], observe[i][j])
    sumvar = 0
    for ((i, j), hit) in observations:
        if hit:
            s.add(observe[i][j])
        else:
            s.add(Not(observe[i][j]))

    for i in range(M):
        for j in range(N):
            sumvar = If(observe[i][j], 1, 0) + sumvar

    s.add(sumvar == getAreaCount(ships))
    if s.check() == sat:
        model = s.model()
        output = []
        for k in range(NS):
            output.append((model[xs[k]].as_long(), model[ys[k]].as_long(),
                           is_true(model[ds[k]])))
        return output
    else:
        #print "UNSAT!"
        return "UNSAT"
Example #20
0
  def __create_grids(self):
    """Create the grids used to model region constraints."""
    self.__parent_grid: Dict[Point, ArithRef] = {}
    for p in self.__lattice.points:
      v = Int(f"rcp-{RegionConstrainer._instance_index}-{p.y}-{p.x}")
      if self.__complete:
        self.__solver.add(v >= R)
      else:
        self.__solver.add(v >= X)
      self.__solver.add(v < len(self.__parent_types))
      self.__parent_grid[p] = v

    self.__subtree_size_grid: Dict[Point, ArithRef] = {}
    for p in self.__lattice.points:
      v = Int(f"rcss-{RegionConstrainer._instance_index}-{p.y}-{p.x}")
      if self.__complete:
        self.__solver.add(v >= 1)
      else:
        self.__solver.add(v >= 0)
      self.__solver.add(v <= self.__max_region_size)
      self.__subtree_size_grid[p] = v

    self.__region_id_grid: Dict[Point, ArithRef] = {}
    for p in self.__lattice.points:
      v = Int(f"rcid-{RegionConstrainer._instance_index}-{p.y}-{p.x}")
      if self.__complete:
        self.__solver.add(v >= 0)
      else:
        self.__solver.add(v >= -1)
      self.__solver.add(v < len(self.__lattice.points))
      parent = self.__parent_grid[p]
      self.__solver.add(Implies(parent == X, v == -1))
      self.__solver.add(Implies(
          parent == R,
          v == self.__lattice.point_to_index(p)
      ))
      self.__region_id_grid[p] = v

    self.__region_size_grid: Dict[Point, ArithRef] = {}
    for p in self.__lattice.points:
      v = Int(f"rcrs-{RegionConstrainer._instance_index}-{p.y}-{p.x}")
      if self.__complete:
        self.__solver.add(v >= self.__min_region_size)
      else:
        self.__solver.add(Or(v >= self.__min_region_size, v == -1))
      self.__solver.add(v <= self.__max_region_size)
      parent = self.__parent_grid[p]
      subtree_size = self.__subtree_size_grid[p]
      self.__solver.add(Implies(parent == X, v == -1))
      self.__solver.add(Implies(parent == R, v == subtree_size))
      self.__region_size_grid[p] = v
Example #21
0
    def test_get_point_expr(self):
        """Unittest for ExpressionQuadTree.get_point_expr."""
        points = [Point(y, x) for y in range(2) for x in range(2)]
        t = ExpressionQuadTree(points)

        y, x = Int("y"), Int("x")
        t.add_expr("test", lambda p: And(p.y == y, p.x == x))

        for p in points:
            expr = t.get_point_expr("test", p)
            self.assertEqual(expr, And(p.y == y, p.x == x))

        with self.assertRaises(ValueError):
            t.get_point_expr("test", Point(3, 3))
Example #22
0
def optimum_dist(bots):
    x = Int('x')
    y = Int('y')
    z = Int('z')
    cost_expr = x * 0
    for i, j, k, r in bots:
        cost_expr += If(z3_dist((x, y, z), (i, j, k)) <= r, 1, 0)
    opt = Optimize()
    opt.maximize(cost_expr)
    opt.minimize(z3_dist((0, 0, 0), (x, y, z)))
    opt.check()
    model = opt.model()
    coords = (model[x].as_long(), model[y].as_long(), model[z].as_long())
    return dist((0, 0, 0), coords)
Example #23
0
def GenerateVerificationConstraint(spec, specConn, circuits, psiConn,
                                   circuitModel):
    constraints = [Bool(True)]

    substList = []
    for circuit in circuits:
        substList.extend([(Int(labelName),
                           circuitModel.eval(Int(labelName), True))
                          for (_, labelName) in circuit.labels.iteritems()])

    constraints.append(substitute(psiConn, substList))
    constraints.append(specConn)
    constraints.append(Not(spec))
    return And(constraints)
Example #24
0
 def z3_solve(self, n, timeout_amount):
     p = Int("x")
     q = Int("y")
     s = Solver()
     i = int(isqrt(n))
     s.add(p * q == n, p > 1, q > i, q > p)
     s.set("timeout", timeout_amount * 1000)
     try:
         s_check_output = s.check()
         print(s_check_output)
         res = s.model()
         return res[p], res[q]
     except:
         return None, None
Example #25
0
def part_2(nanobots: List[Nanobot]) -> int:
    x, y, z = Ints("x y z")
    opt = Optimize()
    bot_cond = []
    for i, bot in enumerate(nanobots):
        cond = Int(f"bot_{i}")
        bot_cond.append(cond)
        opt.add(cond == If(z_manhattan(x, y, z, bot.point) <= bot.r, 1, 0))
    overlaps = Sum(bot_cond)
    dist_zero = Int('dist_zero')
    opt.add(dist_zero == z_manhattan(x, y, z, Point(0, 0, 0)))
    _ = opt.maximize(overlaps)
    dist = opt.maximize(dist_zero)
    opt.check()
    return dist.upper()
Example #26
0
 def z3_solve(self, n, timeout_amount):
     s = Solver()
     s.set("timeout", timeout_amount * 1000)
     p = Int("x")
     q = Int("y")
     i = int(isqrt(n))
     if i**2 == n: # check if we are dealing with a perfect square otherwise try to SMT.
         return i,i
     s.add(p * q == n, p > 1, q > i, q > p) # In every composite n=pq,there exists a p>sqrt(n) and q<sqrt(n).
     try:
         s_check_output = s.check()
         res = s.model()
         return res[p], res[q]
     except:
         return None, None
Example #27
0
def add_sea_constraints(sym, sg, rc):
    """Add the sea constraints (one connected sea with no three cells
  sharing a vertex)."""
    # There must be only one sea, containing all black cells.
    sea_id = Int("sea-id")
    for p in sg.lattice.points:
        sg.solver.add(sg.cell_is(p, sym.W) == (rc.region_id_grid[p] != sea_id))

    # Constrain sea_id to be the index of one of the points in
    # the smallest area, among those areas of size greater than 4.
    area_to_points = defaultdict(list)
    for p in sg.lattice.points:
        r, c = point_to_areas_row_col(p)
        area_to_points[AREAS[r][c]].append(p)
    area_points = min((ps for ps in area_to_points.values() if len(ps) > 4),
                      key=len)
    sg.solver.add(
        Or(*[sea_id == sg.lattice.point_to_index(p) for p in area_points]))

    # The sea may not contain three cells sharing a vertex.
    for p in sg.lattice.points:
        np1 = p.translate(Vector(1, -1))
        np2 = p.translate(Vector(1, 1))
        if np1 in sg.grid and np2 in sg.grid:
            sg.solver.add(
                Or(sg.grid[p] == sym.W, sg.grid[np1] == sym.W,
                   sg.grid[np2] == sym.W))

        np1 = p.translate(Vector(-1, -1))
        np2 = p.translate(Vector(-1, 1))
        if np1 in sg.grid and np2 in sg.grid:
            sg.solver.add(
                Or(sg.grid[p] == sym.W, sg.grid[np1] == sym.W,
                   sg.grid[np2] == sym.W))
Example #28
0
    def __add_single_loop_constraints(self):
        solver = self.__symbol_grid.solver
        sym: LoopSymbolSet = self.__symbol_grid.symbol_set

        cell_count = len(self.__symbol_grid.grid)

        for p in self.__symbol_grid.grid:
            v = Int(f"log-{LoopConstrainer._instance_index}-{p.y}-{p.x}")
            solver.add(v >= -cell_count)
            solver.add(v < cell_count)
            self.__loop_order_grid[p] = v

        solver.add(Distinct(*self.__loop_order_grid.values()))

        for p, cell in self.__symbol_grid.grid.items():
            li = self.__loop_order_grid[p]

            solver.add(If(sym.is_loop(cell), li >= 0, li < 0))

            for idx, d1, d2 in self.__all_direction_pairs():
                pi = p.translate(d1)
                pj = p.translate(d2)
                if pi in self.__loop_order_grid and pj in self.__loop_order_grid:
                    solver.add(
                        Implies(
                            And(cell == idx, li > 0),
                            Or(self.__loop_order_grid[pi] == li - 1,
                               self.__loop_order_grid[pj] == li - 1)))
Example #29
0
def mk_var(name, vsort):
    """
    Create a variable of type vsort.

    Examples:

    >>> from z3 import *
    >>> v = mk_var('real_v', Real('x').sort())
    >>> print v
    real_v

    """
    if vsort.kind() == Z3_INT_SORT:
        v = Int(name)
    elif vsort.kind() == Z3_REAL_SORT:
        v = Real(name)
    elif vsort.kind() == Z3_BOOL_SORT:
        v = Bool(name)
    elif vsort.kind() == Z3_DATATYPE_SORT:
        v = Const(name, vsort)

    else:
        raise AssertionError,\
            'Cannot handle this sort (s: {}, {})'\
            .format(vsort, vsort.kind())

    return v
Example #30
0
    def __init__(
        self,
        name: str,
        horizon: Optional[int] = None,
        delta_time: Optional[timedelta] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
    ):
        super().__init__(name)
        # the problem context, where all will be stored
        # at creation
        self.context = ps_context.SchedulingContext()
        # set this context as global
        ps_context.main_context = self.context

        # define the horizon variable
        self.horizon = Int("horizon")
        self.fixed_horizon = False  # set to True is horizon is fixed
        if is_strict_positive_integer(horizon):  # fixed_horizon
            self.context.add_constraint(self.horizon == horizon)
            self.fixed_horizon = True
        elif horizon is not None:
            raise TypeError("horizon must either be a strict positive integer or None")

        # check time data
        if delta_time is not None and not isinstance(delta_time, timedelta):
            raise TypeError("delta_time must be a timedelta instance")
        if start_time is not None and not isinstance(start_time, datetime):
            raise TypeError("start_time must be a datetime instance")
        if end_time is not None and not isinstance(end_time, datetime):
            raise TypeError("delta_time must be a datetime instance")

        self.delta_time = delta_time
        self.start_time = start_time
        self.end_time = end_time