66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
|
|
from numpy import *
|
|
from FuncDesigner import *
|
|
|
|
UNDERCONSTRAINED = 0
|
|
OVERCONSTRAINED = 1
|
|
SOLVED = 2
|
|
NO_SOLUTION = 3
|
|
|
|
class Sketch(object):
|
|
def __init__(self):
|
|
self.shapes = []
|
|
self.constraints = []
|
|
self.num_variables = 0
|
|
self.num_constraints = 0
|
|
|
|
def __iter__(self):
|
|
return self.shapes.__iter__()
|
|
|
|
def __contains__(self, item):
|
|
return self.shapes.__contains__(item)
|
|
|
|
def solve(self):
|
|
shape_vars = {}
|
|
varid_to_shape_var = []
|
|
varid = 0
|
|
equations = []
|
|
for c in self.constraints:
|
|
equations += c.toEqu()
|
|
for e in equations:
|
|
coeffs = e[0]
|
|
for c in coeffs:
|
|
shape_var = c[1]
|
|
if not shape_var in shape_vars:
|
|
shape_vars[shape_var] = varid
|
|
varid += 1
|
|
varid_to_shape_var.append(shape_var)
|
|
self.num_constraints = len(equations)
|
|
self.num_variables = len(shape_vars)
|
|
dim = self.num_constraints
|
|
if self.num_variables > dim:
|
|
dim = self.num_variables
|
|
if self.num_variables < self.num_constraints:
|
|
return OVERCONSTRAINED
|
|
elif self.num_variables > self.num_constraints:
|
|
return UNDERCONSTRAINED
|
|
sle_equs = []
|
|
variables = oovars(dim)
|
|
for e in equations:
|
|
coeffs = e[0]
|
|
equ = -e[1]
|
|
for c in coeffs:
|
|
equ = c[0] * variables[shape_vars[c[1]]] + equ
|
|
sle_equs.append(equ)
|
|
s = sle(sle_equs)
|
|
r = s.solve()
|
|
if r.ff != float('inf'):
|
|
# print "SOLVED: ", r(variables)
|
|
for i in range(len(variables)):
|
|
varid_to_shape_var[i][0].setVar(varid_to_shape_var[i][1],
|
|
r(variables[i]))
|
|
# for s in self.shapes:
|
|
# print 'shape:', repr(s.vars)
|
|
return SOLVED
|
|
return NO_SOLUTION
|