Example #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()
Example #2
0
from z3 import Optimize, Real, If

x = Real('x')
y = Real('y')
z = Real('z')


def z3abs(obj):
    return If(x > 0, x, -x)

optimizer = Optimize()
# optimizer.add(x>0.0)
# optimizer.add(y>0.0)
optimizer.add(x*x+y*y==1.0)
optimizer.add_soft(z == x+y)
optimizer.maximize(z)
result = optimizer.check()

print(optimizer.model())
Example #3
0
    def smt_solution(self, timeout, optimize=False):
        if optimize:
            solver = Optimize()
        else:
            solver = Solver()
            solver.set("zero_accuracy",10)
        solver.set("timeout", timeout)


        non_trivial = False
        diff_sol = False
        smt_keep_sol = True # a.k.a A1
        smt_is_sol = True # a.k.a A2

        some_consume = False
        some_produce = False
        variables = set()
        variables_positive = set()
        for p_id, place in enumerate(self.facets):
            ti = place.offset
            smt_ti = Int("b%s" % p_id)

            if ti:
                solver.add(min(0,ti) <= smt_ti, smt_ti <= max(0, ti))
            else:
                solver.add(smt_ti == 0)


            facet_non_trivial = False
            facet_diff_sol = False
            smt_facet_eval = ti
            smt_facet_sol = ti

            # If halfspace's coefficients add to 1 it's
            # as simple as it gets
            simple = sum(abs(x) for x in place.normal) <= 1
            # do_cons_prod indicates if the place has incoming and outgoing transitions
            do_cons_prod = False
            consume = produce = 0
            for coeff in place.normal:
                if coeff > 0:
                    produce = 1
                elif coeff < 0:
                    consume = 1
                if consume * produce:
                    do_cons_prod = True
                    break

            do_cons_prod = reduce(lambda x,y:x*y, [x + 1 for x in place.normal]) < 1

            for t_id, coeff in enumerate(place.normal):
                # SMT coefficient
                smt_coeff = Int("a%s,%s" % (p_id, t_id))
                if optimize:
                    # Try to minimize the coefficient
                    solver.minimize(smt_coeff)
                # SMT variable
                smt_var = Int("x%s" % t_id)

                # Add SMT varible to the set of variables
                variables.add(smt_var)
                # Add SMT varible basic constraint to the set
                variables_positive.add(smt_var >= 0)
                if coeff:
                    # At least one SMT coefficient should be non zero
                    facet_non_trivial = Or(facet_non_trivial, smt_coeff != 0)
                    # At least one SMT coefficient should be different
                    facet_diff_sol = Or(facet_diff_sol, smt_coeff != coeff)
                    # Original solution with SMT variable
                    smt_facet_eval += coeff * smt_var
                    # SMT solution with SMT variable
                    smt_facet_sol += smt_coeff * smt_var
                    # Keep SMT coefficient between original bundaries
                    solver.add(min(0,coeff) <= smt_coeff, smt_coeff <= max(0, coeff))

                    if not self.neg_points and not simple and do_cons_prod:
                        some_produce = Or(some_produce, smt_coeff > 0)
                        some_consume = Or(some_consume, smt_coeff < 0)
                else:
                    # Keep zero coefficients unchanged
                    solver.add(smt_coeff == 0)
            if not self.neg_points:
                # Avoid trivial solution (i.e. all zeros as coeff)
                non_trivial = Or(non_trivial, facet_non_trivial)
            # Solution of smt must be different
            diff_sol = Or(diff_sol, facet_diff_sol)
            # If point is in old-solution should be in smt-solution
            smt_keep_sol = And(smt_keep_sol, smt_facet_eval <= 0)
            # Solutions shoul be a solution
            smt_is_sol = And(smt_is_sol, smt_facet_sol <= 0)

            if not self.neg_points and not simple and do_cons_prod:
                solver.add(simplify(some_consume))
                solver.add(simplify(some_produce))

            if optimize:
                # Try to minimize the independent term
                solver.minimize(smt_ti)

    # This is what we want:
        if not self.neg_points:
            # If there is not negative info, avoid trivial solution (i.e. Not all zero)
            solver.add(simplify(non_trivial))
        # A different solution (i.e. "better")
        solver.add(simplify(diff_sol))
        # If it was a solution before, keep it that way
        solver.add(simplify(ForAll(list(variables), Implies(And(Or(list(variables_positive)), smt_keep_sol), smt_is_sol))))

        # Negative point shouldn't be a solution
        for np in self.neg_points:
            smt_np = False
            for p_id, place in enumerate(self.facets):
                place_at_np = Int("b%s" % p_id)
                for t_id, coeff in enumerate(place.normal):
                    # If coefficient was zero, it will remain zero
                    if coeff and np[t_id]:
                        smt_coeff = Int("a%s,%s" % (p_id, t_id))
                        place_at_np = place_at_np + smt_coeff * np[t_id]

                smt_np = Or(smt_np, place_at_np > 0)
            # Keep out (NOTE halfspaces are Ax + b <= 0)
            solver.add(simplify(smt_np))

        sol = solver.check()
        if sol == unsat:
            ret = False
            logger.info('Z3 returns UNSAT: Cannot reduce without adding neg info')
        elif sol == unknown:
            ret = False
            logger.info('Z3 returns UNKNOWN: Cannot reduce in less than %s miliseconds', timeout)
        else:
            ret = solver.model()
        return ret
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:
Example #5
0
    def smt_solution(self, timeout, neg_points=None, optimize=False):
        # If halfspace's coefficients add to 1 it's
        # as simple as it gets
        normal_sum = sum(abs(x) for x in self.normal)
        if normal_sum == 0:
            return False
        elif normal_sum <= 1:
            simple = True
        else:
            simple = False

        neg_points = neg_points or []

        if optimize:
            solver = Optimize()
        else:
            solver = Solver()
            solver.set("zero_accuracy",10)
        solver.set("timeout", timeout)

        ti = self.offset
        smt_ti = Int("b")
        if ti:
            solver.add(min(0,ti) <= smt_ti, smt_ti <= max(0,ti))
            if optimize:
                # Try to minimize the independent term
                solver.minimize(smt_ti)
        else:
            solver.add(smt_ti == 0)

        variables = set()
        variables_positive = set()

        positive_x = True
        non_trivial = False
        some_consume = False
        some_produce = False

        diff_sol = smt_ti != ti
        smt_keep_sol = ti
        smt_is_sol = smt_ti

        for t_id, coeff in enumerate(self.normal):
            # SMT coefficient
            smt_coeff = Int("a%s" % t_id)
            if optimize:
                # Try to minimize the coefficient
                solver.minimize(smt_coeff)
            # SMT variable
            smt_var = Int("x%s"%t_id)

            # Add SMT varible to the set of variables
            variables.add(smt_var)
            # Add SMT varible basic constraint to the set
            variables_positive.add(smt_var >= 0)

            if coeff:
                # At least one SMT coefficient should be non zero
                non_trivial = Or(non_trivial, smt_coeff != 0)
                # At least one SMT coefficient should be different
                diff_sol = Or(diff_sol, smt_coeff != coeff)
                # Original solution with SMT variable
                smt_keep_sol += coeff * smt_var
                # SMT solution with SMT variable
                smt_is_sol += smt_coeff * smt_var
                # Keep SMT coefficient between original bundaries
                solver.add(min(0,coeff) <= smt_coeff, smt_coeff <= max(0, coeff))

                if not neg_points and not simple:
                    some_produce = Or(some_produce, smt_coeff > 0)
                    some_consume = Or(some_consume, smt_coeff < 0)
            else:
                solver.add(smt_coeff == 0)

    #This is what we want:
        if not neg_points:
            # If there is not negative info, avoid trivial solution (i.e. Not all zero)
            solver.add(simplify(non_trivial))
            if not simple:
                solver.add(simplify(some_consume))
                solver.add(simplify(some_produce))
        # A different solution (i.e. "better")
        solver.add(simplify(diff_sol))
        # If it was a solution before, keep it that way
        solver.add(simplify(ForAll(list(variables), Implies(And(Or(list(variables_positive)), smt_keep_sol <= 0), smt_is_sol <= 0))))

        # New solution shouldn't add a negative point
        for np in neg_points:
            smt_ineq_np = smt_ti
            ineq_np = ti
            for t_id, coeff in enumerate(self.normal):
                ineq_np += coeff * np[t_id]
                smt_coeff = Int("a%s"%(t_id))
                smt_ineq_np += smt_coeff * np[t_id]
            # If neg point was out of this halfspace, keep it out!
            if ineq_np > 0:
                logger.info('Adding HS SMT-NEG restriction')
                solver.add(simplify(smt_ineq_np > 0))

        sol = solver.check()
        if sol == unsat:
            ret = False
            logger.info('Z3 returns UNSAT: Cannot simplify HS without adding neg info')
        elif sol == unknown:
            ret = False
            logger.info('Z3 returns UNKNOWN: Cannot simplify HS in less than %s miliseconds', timeout)
        else:
            ret = solver.model()
        return ret