Ejemplo n.º 1
0
def search_rectangle(b1, e1, b2, e2, b3, e3, b4, e4):
    x1 = Real('x1')
    x2 = Real('x2')
    x3 = Real('x3')
    x4 = Real('x4')

    y1 = Real('y1')
    y2 = Real('y2')
    y3 = Real('y3')
    y4 = Real('y4')

    optimizer = Optimize()

    add_cond_on_segment(optimizer, b1, e1, x1, y1)
    add_cond_on_segment(optimizer, b2, e2, x2, y2)
    add_cond_on_segment(optimizer, b3, e3, x3, y3)
    add_cond_on_segment(optimizer, b4, e4, x4, y4)

    add_cond_orthogonal(optimizer, x1, y1, x2, y2, x3, y3)
    add_cond_orthogonal(optimizer, x2, y2, x3, y3, x4, y4)
    add_cond_orthogonal(optimizer, x3, y3, x4, y4, x1, y1)
    add_cond_orthogonal(optimizer, x4, y4, x1, y1, x2, y2)

    # equal_distance
    #optimizer.add_soft((x2-x1)**2+(y2-y1)**2==(x4-x3)**2+(y4-y3)**2)
    #optimizer.add_soft((x3-x2)**2+(y3-y2)**2==(x4-x1)**2+(y4-y1)**2)

    #optimizer.maximize(z3abs((x2-x1)*(y4-y1)-(x4-x1)*(y2-y1)))

    result = optimizer.check()

    print(result)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plotline(ax, b1, e1)
    plotline(ax, b2, e2)
    plotline(ax, b3, e3)
    plotline(ax, b4, e4)

    if result != z3.unsat:
        print(optimizer.model())
        model = optimizer.model()
        x1 = convert_py_type(model[x1])
        x2 = convert_py_type(model[x2])
        x3 = convert_py_type(model[x3])
        x4 = convert_py_type(model[x4])
        y1 = convert_py_type(model[y1])
        y2 = convert_py_type(model[y2])
        y3 = convert_py_type(model[y3])
        y4 = convert_py_type(model[y4])

        plotline(ax, [x1, y1], [x2, y2], 'k')
        plotline(ax, [x2, y2], [x3, y3], 'k')
        plotline(ax, [x3, y3], [x4, y4], 'k')
        plotline(ax, [x4, y4], [x1, y1], 'k')

    else:
        print('no soltion')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()
Ejemplo n.º 2
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))
Ejemplo n.º 3
0
def maximize_distance(bots):
  o = Optimize()

  z3_abs = lambda k: If(k >= 0, k, -k)
  z3_in_ranges = [Int('in_range_of_bot_' + str(i)) for i in xrange(len(bots))]
  z3_x, z3_y, z3_z = (Int('x'), Int('y'), Int('z'))
  z3_sum = Int('sum')
  z3_dist = Int('dist')

  for i, (x, y, z, r) in enumerate(bots):
    o.add(z3_in_ranges[i] == If(distance((z3_x, z3_y, z3_z), (x, y, z), z3_abs) <= r, 1, 0))

  o.add(z3_sum == sum(z3_in_ranges))

  o.add(z3_dist == distance((z3_x, z3_y, z3_z), (0, 0, 0), z3_abs))

  h1, h2 = o.maximize(z3_sum), o.minimize(z3_dist)
  o.check()
  # o.lower(h1), o.upper(h1)

  lower, upper = o.lower(h2), o.upper(h2)
  # o.model()[z3_x], o.model()[z3_y], o.model()[z3_z]

  if str(lower) != str(upper): raise Exception('lower ({}) != upper ({})'.format(lower, upper))
  return (lower, upper)
Ejemplo n.º 4
0
def find_max(constraints, expr, l = None):
    if l is None:
        l = logger

    if type(expr) == int:
        return expr

    constraint_strs = [f'{c}' for c in constraints]

    max_optimize = Optimize()
    max_optimize.set('timeout', 10000)
    max_optimize.assert_exprs(*constraints)
    max_optimize.maximize(expr)
    status = max_optimize.check()
    if status != sat:
        l.warning(f'Unable to find max ({status}) for:\n' + '\n'.join(constraint_strs))
        return None

    max_val = max_optimize.model().eval(expr).as_long()

    # Make sure it's actually the max, since z3 has a bug
    #   https://github.com/Z3Prover/z3/issues/4670
    solver = Solver()
    solver.set('timeout', 10000)
    solver.add(constraints + [expr > max_val])
    status = solver.check()

    if status != unsat:
        l.error(f'Z3 bug\nFind max ({expr}) => {max_val} with status ({status}):\n' + '\n'.join(constraint_strs))
        return None
    return max_val
Ejemplo n.º 5
0
    def __init__(self, state_graph: StateGraph, default_value: Fraction,
                 statistics: Statistics, settings: Settings,
                 model_type: PrismModelType):

        self.state_graph = state_graph
        self.statistics = statistics
        self.settings = settings
        self.model_type = model_type

        if default_value < 0:
            raise ValueError("Oracle values must be greater or equal to 0")

        self.default_value = RealVal(default_value)

        self.solver = Solver()
        self.solver_mdp = Optimize()

        # The way we refine the Oracle depends on the model type
        if model_type == PrismModelType.DTMC:
            self.refine_oracle = self.refine_oracle_mc

        elif model_type == PrismModelType.MDP:
            self.refine_oracle = self.refine_oracle_mdp

        else:
            raise Exception("Oracle: Unsupported model type")

        self.oracle_states: Set[StateId] = set()

        self.oracle: Dict[StateId, z3.ExprRef] = dict()
def test(qcirc):
    #print(qcirc)
    print("Translate to Z3")
    circ = QuantumCircuit_to_Circuit(qcirc, melbourne_rels, positions)
    # Collect Constraints
    print("Create Constraint Generator")
    cons = circ.constraints()
    # New Optimizer
    s = Optimize()
    # Add constraints
    print("Add All constraints")
    for con in cons:
        s.add(con)
        #print(con)
    # Add reliability objective
    print("Add Objective")
    s.maximize(reliability_objective(circ))
    # Check and print
    print("Checking")
    sat = str(s.check())
    print(sat)
    if sat == "unsat":
        raise Exception("unsat")

    print("Extracting Model")
    m = s.model()

    # Confirm that an improvement in reliability was made
    print("Reliability Checking")
    improved_reliability(m, s, melbourne_rels, qcirc)

    # Translate to qiskit QuantumCircuit
    print("Translate to Qiskit")
    rcirc = model_to_QuantumCircuit(m, circ)
def test_allBadSpecsAreBad(spec):
    badSpecs = getAllBadSpecs(spec, 15)
    for badSpec in badSpecs:
        foundry = Foundry(
            Optimize()).applyAndTrackSpec(badSpec).applyAndTrackSpec(spec)
        assert foundry.check() == unsat
        assert len(foundry.getReasonsForUnsat()) != 0
Ejemplo n.º 8
0
def find_min(constraints, expr, default_min=0):
    if type(expr) == int:
        return expr

    constraint_strs = [f'{c}' for c in constraints]

    min_optimize = Optimize()
    min_optimize.set('timeout', 10000)

    min_optimize.assert_exprs(*constraints)
    min_optimize.minimize(expr)
    status = min_optimize.check()
    if status != sat:
        print(f'Unable to find min ({status}) for:\n' +
              '\n'.join(constraint_strs))
        return None

    min_val = min_optimize.model().eval(expr).as_long()

    # Make sure it's actually the min, since z3 has a bug
    #   https://github.com/Z3Prover/z3/issues/4670
    solver = Solver()
    solver.set('timeout', 10000)
    solver.add(constraints + [expr < min_val])
    status = solver.check()

    if status != unsat:
        print(
            f'Z3 bug\nFind min ({expr}) => {min_val} with status ({status}):\n'
            + '\n'.join(constraint_strs))
        return None
    return min_val
Ejemplo n.º 9
0
    def from_model(model):
        start_over()
        context = Context()
        context.load_metamodel()
        context.load_model(model)

        solver = Optimize()

        generate_meta_constraints()
        generate_config_constraints()

        solver.add(*get_all_meta_facts())
        solver.add(*get_all_config_facts())

        context.declare(INTEGRITY_VARIABLES)
        context.declare_helper_functions()

        for each_constraint in INTEGRITY_CONSTRAINTS:
            solver.add(context.evaluate(each_constraint))

        for each_running_service in model.goals.services:
            constraint = RUNNING_SERVICE.format(each_running_service.name)
            solver.add(context.evaluate(constraint))

        for each_constraint in model.constraints:
            solver.add(context.evaluate(each_constraint))

        for each_constraint in context.value_constraints:
            solver.add(context.evaluate(each_constraint))

        #print solver.sexpr()
        return Z3Problem(model, context, solver)
Ejemplo n.º 10
0
def get_model(constraints, minimize=(), maximize=()):
    s = Optimize()
    s.set("timeout", 100000)

    for constraint in constraints:
        if type(constraint) == bool and not constraint:
            raise UnsatError

    constraints = [
        constraint for constraint in constraints if type(constraint) != bool
    ]

    for constraint in constraints:
        s.add(constraint)
    for e in minimize:
        s.minimize(e)
    for e in maximize:
        s.maximize(e)

    result = s.check()
    if result == sat:
        return s.model()
    elif result == unknown:
        logging.debug("Timeout encountered while solving expression using z3")
    raise UnsatError
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
def to_z3_problem(problem: DependencyProblem,
                  states: List[EncodedState]) -> Optimize:
    minimizer = Optimize()
    minimizer.add(to_formula(problem, states))

    cost = Int('cost')
    cost_constraint = cost == total_cost(states, problem.repository)
    minimizer.add(cost_constraint)

    minimizer.minimize(cost)
    return minimizer
def bruteForceRepairLine(broken: List[Pitch], spec: Spec) -> List[int]:
    foundry = Foundry(Optimize())
    foundry.applySpec(spec)
    for fixedNoteIndexes in revpowset(range(0, len(broken))):
        foundry.opt.push()
        for i in fixedNoteIndexes:
            foundry.apply(
                Constraint(spec.line[i] == broken[i], ConstraintType.REPAIRER,
                           "Ignore"))
        if foundry.check() == sat:
            return foundry.extractPitches(spec.line)
        foundry.opt.pop()
    raise Exception("No valid line could be found")
Ejemplo n.º 14
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)
def geometry_free_solve_(ddn1, ddn2, ws, station_data, sta1, sta2, prn1, prn2, ticks):
    lambda_1 = lambda_1s[prn1[0]]
    lambda_2 = lambda_2s[prn1[0]]

    # Φ_i - R_i = B_i + err  with B_i = b_i + λ_1*N_1 - λ_2*N_2
    B_i = bias(tec.geometry_free)
    
    sol = Optimize()
#    sol = Solver()
    errs = Reals('err_11 err_12 err_21 err_22')
    n1s = Ints('n1_11 n1_12 n1_21 n1_22')
    n2s = Ints('n2_11 n2_12 n2_21 n2_22')

    sol.add(n1s[0] - n1s[1] - n1s[2] + n1s[3] == ddn1)
    sol.add(n2s[0] - n2s[1] - n2s[2] + n2s[3] == ddn2)

    for i, (sta, prn) in enumerate(product([sta1, sta2], [prn1, prn2])):
        sol.add(n1s[i] - n2s[i] == ws[i])
        B_i_samples = []
        for tick in ticks:
            B_i_samples.append( B_i(station_data[sta][prn][tick])[0] )
        B_i_avg = numpy.mean(B_i_samples)
#        B_i_avg = B_i_samples[0]
        print(B_i_avg, numpy.std(B_i_samples))
        sol.add(lambda_1 * ToReal(n1s[i]) - lambda_2 * ToReal(n2s[i]) + errs[i] > B_i_avg)
        sol.add(lambda_1 * ToReal(n1s[i]) - lambda_2 * ToReal(n2s[i]) - errs[i] < B_i_avg)
    """
        sol.add(errs[0] < .9)
        sol.add(errs[1] < .9)
        sol.add(errs[2] < .9)
        sol.add(errs[3] < .9)
    """
    #sol.add(errs[0] + errs[1] + errs[2] + errs[3] < 17)
    objective = sol.minimize(errs[0] + errs[1] + errs[2] + errs[3])
    if sol.check() != sat:
        return None
    sol.lower(objective)
    if sol.check() != sat:
        return None
#    sol.add(errs[0] + errs[1] + errs[2] + errs[3] < 2)
    # can't do L2 norm with z3, L1 will have to do...
#    sol.(errs[0] + errs[1] + errs[2] + errs[3])

    
    return (
        [sol.model()[n1s[i]].as_long() for i in range(4)],
        [sol.model()[n2s[i]].as_long() for i in range(4)],
        [frac_to_float(sol.model()[errs[i]]) for i in range(4)],
    )
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
def find_optimal_space(nanobots):
    (x, y, z) = (Int('x'), Int('y'), Int('z'))
    in_ranges = [
        Int('in_range_{}'.format(i)) for i in range(len(nanobots))
    ]
    range_count = Int('sum')
    optimiser = Optimize()
    for i, nanobot in enumerate(nanobots):
        optimiser.add(in_ranges[i] == If(zabs(x - nanobot.x) + zabs(y - nanobot.y) + zabs(z - nanobot.z) <= nanobot.r, 1, 0))
    optimiser.add(range_count == sum(in_ranges))
    dist_from_zero = Int('dist')
    optimiser.add(dist_from_zero == zabs(x) + zabs(y) + zabs(z))
    optimiser.maximize(range_count)
    result = optimiser.minimize(dist_from_zero)
    optimiser.check()
    return optimiser.lower(result)
 def solve_optimization(self):
     """
     Setup and solve a Z3 optimization for finding the best schedule
     """
     self.opt = Optimize()
     self.create_z3_vars()
     self.basic_bounds()
     self.scheduling_constraints()
     self.fidelity_constraints()
     self.coherence_constraints()
     self.objective_function()
     # Solve step
     self.opt.check()
     # Extract the schedule computed by Z3
     result = self.extract_solution()
     return result
Ejemplo n.º 19
0
def create_optimizer():
    s = Optimize()

    input = Ints(' '.join(map(lambda s: str(s), range(14))))
    for i in input:
        s.add(i > 0, i < 10)

    data = [
        (1, 11, 16),
        (1, 12, 11),
        (1, 13, 12),
        (26, -5, 12),
        (26, -3, 12),
        (1, 14, 2),
        (1, 15, 11),
        (26, -16, 4),
        (1, 14, 12),
        (1, 15, 9),
        (26, -7, 10),
        (26, -11, 11),
        (26, -6, 6),
        (26, -11, 15),
    ]

    x, y, z = 0, 0, 0
    for (zz, b, c), i in zip(data, input):
        w = i
        x = z % 26
        z /= zz
        x += b
        x = x != w
        y = 25
        y *= x
        y += 1
        z *= y
        y = w + c
        y *= x
        z += y

    s.add(z == 0)

    num = 0
    for i in input:
        num *= 10
        num += i

    return s, num
Ejemplo n.º 20
0
    def __init__(self, state_graph, statistics, settings, model_type):
        self.statistics = statistics
        self.state_graph = state_graph
        self.model_type = model_type

        logger.debug("Initialize oracle...")

        self._initialize_oracle(settings)

        logger.debug("Initialize obligation cache...")
        self._obligation_cache = ObligationCache()
        logger.debug("Initialize optimization solver...")
        # Initialize solver for optimization queries
        self.opt_solver = Optimize()

        self._realval_zero = RealVal(0)
        self._realval_one = RealVal(1)

        self.obligation_queue_class = settings.get_obligation_queue_class()
def dd_solve_(dd, vr1s1, vr1s2, vr2s1, vr2s2, wavelength, ionosphere=False):
    sol = Optimize()
    r1s1, r1s2, r2s1, r2s2 = Ints('r1s1 r1s2 r2s1 r2s2')
#    err = Real('err')
    err1, err2, err3, err4 = Reals('err1 err2 err3 err4')
#    sol.add(err > 0)

    if ionosphere:
        ion = Real('ion')
        sol.add(ion > 0)
        sol.add(ion < 25)
    else:
        ion = 0

    sol.add(r1s1 - r1s2 - r2s1 + r2s2 == dd)

    sol.add(ToReal(r1s1)*wavelength + err1 > vr1s1 - ion)
    sol.add(ToReal(r1s1)*wavelength - err1 < vr1s1 - ion)

    sol.add(ToReal(r1s2)*wavelength + err2 > vr1s2 - ion)
    sol.add(ToReal(r1s2)*wavelength - err2 < vr1s2 - ion)

    sol.add(ToReal(r2s1)*wavelength + err3 > vr2s1 - ion)
    sol.add(ToReal(r2s1)*wavelength - err3 < vr2s1 - ion)

    sol.add(ToReal(r2s2)*wavelength + err4 > vr2s2 - ion)
    sol.add(ToReal(r2s2)*wavelength - err4 < vr2s2 - ion)

    objective = sol.minimize(err1 + err2 + err3 + err4)

    if sol.check() != sat:
        return None
    
    sol.lower(objective)
    if sol.check() != sat:
        return None

    return (
        [sol.model()[r].as_long() for r in [r1s1, r1s2, r2s1, r2s2]],
        [frac_to_float(sol.model()[err]) for err in [err1, err2, err3, err4]],
        frac_to_float(sol.model()[ion]) if ionosphere else 0
    )
    def solve_boolean_formula_with_z3_smt2(self, bf):
        """Find minimum satisfying assignemnt for the boolean formula.
        # Example:
        # >>> bf = '(and (or a b) (not (and a c)))'
        # >>> appeared_symbol_list = ['a', 'b', 'c']
        # >>> solve_boolean_formula_with_z3_smt2(bf, appeared_symbol_list)
        # ([b = True, a = False, c = False, s = 1], 1)
        """
        appeared_symbol_list = list(
            set([
                a if "not " not in a else a[5:-1]
                for a in self.prov_notations.values()
            ]))
        declaration_str = '\n'.join(
            list(
                map(lambda x: '(declare-const {} Bool)'.format(x),
                    appeared_symbol_list)))
        declaration_str += '\n(declare-const s Int)'
        declaration_str += '\n(define-fun b2i ((x Bool)) Int (ite x 1 0))'

        size_str = '(+ {})'.format(' '.join(
            list(map(lambda x: '(b2i {})'.format(x), appeared_symbol_list))))
        assert_str = '(assert {})\n'.format(bf)
        assert_str += '(assert (= s {}))\n(assert (>= s 0))'.format(
            size_str)  # changed from (> s 0)

        z3_bf = parse_smt2_string(declaration_str + '\n' + assert_str)
        opt = Optimize()
        opt.add(z3_bf)
        s = Int('s')
        opt.minimize(s)  # changed from opt.minimize(s)

        if opt.check() == sat:
            best_model = opt.model()
            min_size = 0
            for cl in best_model:
                if isinstance(best_model[cl], BoolRef) and best_model[cl]:
                    min_size += 1
            return best_model, min_size
        else:
            return None, -1
Ejemplo n.º 23
0
    def __init__(self, file_name):
        self.solver = Optimize()

        inputs = [Int(f'model_{i}') for i in range(14)]
        self.solver.add([i >= 1 for i in inputs])
        self.solver.add([i <= 9 for i in inputs])

        # Please don't ask me to explain this. There's a common pattern in the input code that treats z like a number
        # of base 26 and the operations are either right shift or left shift on that number +- some value.
        self.solver.add(inputs[0] + 6 - 6 == inputs[13])
        self.solver.add(inputs[1] + 11 - 6 == inputs[12])
        self.solver.add(inputs[2] + 5 - 13 == inputs[11])
        self.solver.add(inputs[3] + 6 - 8 == inputs[8])
        self.solver.add(inputs[4] + 8 - 1 == inputs[5])
        self.solver.add(inputs[6] + 9 - 16 == inputs[7])
        self.solver.add(inputs[9] + 13 - 16 == inputs[10])

        my_sum = IntVal(0)
        for index in range(len(inputs)):
            my_sum = (my_sum * 10) + inputs[index]

        self.value = Int('value')
        self.solver.add(my_sum == self.value)
Ejemplo n.º 24
0
def getAllBadSpecs(spec: Spec,
                   maxCount=None,
                   doShuffle=True,
                   filterOutUnsatisfiable=True) -> List[Spec]:
    badSpecs = []
    constraintsToInclude = powset(spec.constraints)
    constraintsToInvert = constraintsToInclude[::-1]

    constraintsToInclude = constraintsToInclude[:-1]
    constraintsToInvert = constraintsToInvert[:-1]

    if doShuffle:
        constraintsToInclude, constraintsToInvert = shuffle(
            constraintsToInclude, constraintsToInvert)

    if maxCount is None:
        maxCount = len(constraintsToInclude)
    else:
        maxCount = min(maxCount, len(constraintsToInclude))

    for i in range(maxCount):
        constraints = [
            pitchesLetterValueValid(spec.line)
        ]  # Needed ensure that the spec doesn't cheat on the gamut constraint
        constraints += constraintsToInclude[i]
        constraints += [x.inv() for x in constraintsToInvert[i]]
        badSpec = Spec(spec.line, constraints, spec.maximisations,
                       spec.minimisations)
        foundry = Foundry(Optimize()).applySpec(badSpec)

        if filterOutUnsatisfiable:
            if foundry.check() == sat:
                badSpecs.append(badSpec)
        else:
            badSpecs.append(badSpec)

    return badSpecs
Ejemplo n.º 25
0
def solve_pkgver_z3(pkg_dict,
                    constrain_version_dict,
                    optim_target="approximate"):
    # solver = Solver()
    solver = Optimize()
    int_dict = build_int_dict(pkg_dict)
    order_dict = build_order_dict(pkg_dict)
    solver = add_dependency_constrains(solver, pkg_dict, order_dict, int_dict)
    solver = add_int_constrains(solver, pkg_dict, int_dict)
    solver = add_version_constrains(solver, constrain_version_dict, order_dict,
                                    int_dict)
    if optim_target == "approximate":
        solver = add_optimize_targets(solver, int_dict)
    if optim_target == "exact":
        solver = add_optimize_targets2(solver, int_dict, order_dict)
        solver.set(timeout=60000)
    try:
        if solver.check():
            pkgvers = parse_z3_model(solver.model(), int_dict, order_dict)
            return pkgvers
        else:
            return None
    except:
        return None
def opt():
    return Optimize()
Ejemplo n.º 27
0
    num_swap = Int('num_swap')
# for fidelity optimization

    if objective_name == "fidelity":
        u = [Int("num_1qbg_p{}".format(n)) for n in range(N)]
        v = [Int("num_2qbg_e{}".format(k)) for k in range(K)]
        vv = [Int("num_swap_e{}".format(k)) for k in range(K)]
        w = [Int("num_meas_p{}".format(n)) for n in range(N)]
        fidelity = Int('log_fidelity')

    # else:
# for depth optimization
    depth = Int('depth')


    z3 = Optimize()


    """
    Constraints
    """

    for t in range(T):
        for m in range(M):
            z3.add(pi[m][t] >= 0, pi[m][t] < N)
            for mm in range(m):
                z3.add(pi[m][t] != pi[mm][t])

    for l in range(L):
        z3.add(time[l] >= 0, time[l] < T)
        if l in G_1:
Ejemplo n.º 28
0
# Variables
is_bomb = np.array([
    Bool("is_bomb_%s%s" % (r, c)) for (r, c) in rectangle(H, W)
]).reshape(H, W).tolist()


# Bomb placement
def at_least_one_bomb_for_each_rectangle(h, w):
    return [
        PbGe([(is_bomb[r + dr][c + dc], 1) for (dr, dc) in rectangle(h, w)], 1)
        for (r, c) in rectangle(H - h + 1, W - w + 1)
    ]


# Clauses
s = Optimize()
s.add(at_least_one_bomb_for_each_rectangle(2, 3))
s.add(at_least_one_bomb_for_each_rectangle(3, 2))

# Objective
num_bombs = Sum([If(is_bomb[r][c], 1, 0) for (r, c) in rectangle(H, W)])
min_bombs = s.minimize(num_bombs)

if s.check() == sat:
    assert s.lower(min_bombs) == 6
    print("The minimum number of bombs satisfying the constraints == %s." %
          s.lower(min_bombs))
    print(diagram(s.model()))
else:
    print("Z3 failed to find a solution.")
Ejemplo n.º 29
0
import time
import csv
from z3 import Optimize
from z3 import *

# create a dictionary contains all the street name variables
street = {}

# create a list of list contains all the intersections
intersects = []

# track increament variable
i = 0

# Optimize API solver objective functions
opt = Optimize()

# adding integer variables
X = []

# adding constrain for each street variable
C = []

# read from the .csv file
with open("../Dataset/intersection_lane.csv") as f:
    reader = csv.reader(f, delimiter=",")
    # for each row in file:
    for row in reader:
        st1 = row[0]
        # create two new variable STREET1, STREET2
        if not st1 in street:
    def __init__(self,
                 backend_prop,
                 crosstalk_prop,
                 weight_factor=0.5,
                 measured_qubits=None):
        """CrosstalkAdaptiveSchedule initializer.

        Args:
            backend_prop (BackendProperties): backend properties object
            crosstalk_prop (dict): crosstalk properties object
                crosstalk_prop[g1][g2] specifies the conditional error rate of
                g1 when g1 and g2 are executed simultaneously.
                g1 should be a two-qubit tuple of the form (x,y) where x and y are physical
                qubit ids. g2 can be either two-qubit tuple (x,y) or single-qubit tuple (x).
                We currently ignore crosstalk between pairs of single-qubit gates.
                Gate pairs which are not specified are assumed to be crosstalk free.

                Example::

                    crosstalk_prop = {(0, 1) : {(2, 3) : 0.2, (2) : 0.15},
                                                (4, 5) : {(2, 3) : 0.1},
                                                (2, 3) : {(0, 1) : 0.05, (4, 5): 0.05}}

                The keys of the crosstalk_prop are tuples for ordered tuples for CX gates
                e.g., (0, 1) corresponding to CX 0, 1 in the hardware.
                Each key has an associated value dict which specifies the conditional error rates
                with nearby gates e.g., ``(0, 1) : {(2, 3) : 0.2, (2) : 0.15}`` means that
                CNOT 0, 1 has an error rate of 0.2 when it is executed in parallel with CNOT 2,3
                and an error rate of 0.15 when it is executed in parallel with a single qubit
                gate on qubit 2.
            weight_factor (float): weight of gate error/crosstalk terms in the objective
                :math:`weight_factor*fidelities + (1-weight_factor)*decoherence errors`.
                Weight can be varied from 0 to 1, with 0 meaning that only decoherence
                errors are optimized and 1 meaning that only crosstalk errors are optimized.
                weight_factor should be tuned per application to get the best results.
            measured_qubits (list): a list of qubits that will be measured in a particular circuit.
                This arg need not be specified for circuits which already include measure gates.
                The arg is useful when a subsequent module such as state_tomography_circuits
                inserts the measure gates. If CrosstalkAdaptiveSchedule is made aware of those
                measurements, it is included in the optimization.
        Raises:
            ImportError: if unable to import z3 solver

        """
        super().__init__()
        self.backend_prop = backend_prop
        self.crosstalk_prop = crosstalk_prop
        self.weight_factor = weight_factor
        if measured_qubits is None:
            self.input_measured_qubits = []
        else:
            self.input_measured_qubits = measured_qubits
        self.bp_u1_err = {}
        self.bp_u1_dur = {}
        self.bp_u2_err = {}
        self.bp_u2_dur = {}
        self.bp_u3_err = {}
        self.bp_u3_dur = {}
        self.bp_cx_err = {}
        self.bp_cx_dur = {}
        self.bp_t1_time = {}
        self.bp_t2_time = {}
        self.gate_id = {}
        self.gate_start_time = {}
        self.gate_duration = {}
        self.gate_fidelity = {}
        self.overlap_amounts = {}
        self.overlap_indicator = {}
        self.qubit_lifetime = {}
        self.dag_overlap_set = {}
        self.xtalk_overlap_set = {}
        self.opt = Optimize()
        self.measured_qubits = []
        self.measure_start = None
        self.last_gate_on_qubit = None
        self.first_gate_on_qubit = None
        self.fidelity_terms = []
        self.coherence_terms = []
        self.model = None
        self.dag = None
        self.parse_backend_properties()