def test_2(): """ func = F x = X vertex_tpl = [0,0] itmax = 50 tol = 1.e-15 xpt = .5 """ #xo = ia(-100.,100.) #yo = ia(-100.,100.) xo = ad(ia(-100., 100.), name='x', N=2, dim=0) yo = ad(ia(-100., 100.), name='y', N=2, dim=1) #X = interval_lagrange_tester([xo,yo]) X = [xo, yo] F = test_HC_BC_2 g = F(X) ans, i, F = BC_newton(F, X, [0, 0], tol=1.e-20) print 'test 2' print 'ans = ', ans print 'i iterations = ', i print 'F = ', F print F.grad print F.hess return
def test( xshift=0., xb=0., #1st vertex: x value xe=12., #last vertex: x value yb=12., ye=0., area=72., xc=4., yc=4.): xb = xb + xshift xe = xe + xshift alphab = 0. #tangent at the start of the curve Cab_given = 0. #curvature desired at the beggining alphae = 0. #tangent at the end of the curve Cae_given = 0. #curvature desired at the end ## Curve Integral parameters: ini_CV = InitializeControlVertices(xb, yb, xe, ye, alphab, alphae, Cab_given, Cae_given, area, xc, yc) curve = Bspline(ini_CV.vertices, 4, 50) plot(ini_CV) curve.compute_area() curve.MomentMatrices() curve.compute_moments() curve.computeXc() print '\n\nArea interval Finding....' print 'area: ', curve.area print '\nXC interval Finding....' print 'using x3=6.+{} and actual area:'.format(xshift) eXc = ini_CV.calc_xc(6. + xshift, curve.area) print 'est Xc = ', eXc print 'actual Xc = ', curve.Xc print 'diff = ', curve.Xc - eXc #""" #self = ini_CV xcini = ia(5., 9.) area = ia(71., 73.) print '\nNow use ...' print 'area = 72., ', xcini, ' Xc = ', ini_CV.calc_xc(xcini, curve.area) print 'area = IA(), ', xcini, ' Xc = ', ini_CV.calc_xc(ia(0., 12.), area) area = ia(50., 90.) print 'area = IA(big), ', xcini, ' Xc = ', ini_CV.calc_xc(xcini, area) #""" print '\n\n' return curve, ini_CV
def __init__(self, spec, verbose=False): self._verbose = verbose self.spec = spec self.sobol_seq = sobol.sobolSeq([1, 1], [1, 1]) #alternatvely, initialize a true IA hull self.hdp = hullclp() #hull_use_HICLP.hullclp() self.hdp.lwl = ia(spec.lwl[0], spec.lwl[1]) self.hdp.draft = ia(spec.draft[0], spec.draft[1]) self.hdp.bwl = ia(spec.bwl[0], spec.bwl[1]) self.hdp.vol = ia(spec.vol[0], spec.vol[1]) self.hdp.Cb = ia(spec.Cb[0], spec.Cb[1]) self.hdp.Cwp = ia(spec.Cwp[0], spec.Cwp[1]) self.hdp.Ccp = ia(spec.Ccp[0], spec.Ccp[1]) self.hdp.LCG = ia(spec.LCG[0], spec.LCG[1]) self.hdp.Cmidshp = ia(spec.Cmidshp[0], spec.Cmidshp[1]) self.hdp.AC_revise() #""" self.hdp.states = self.hdp.shape_bow_section_inizers() self.hdp.states = self.hdp.shape_stern_section_inizers() self.hdp.states = self.hdp.SAC_run_area_ini() self.hdp.states = self.hdp.SAC_Xc_init() self.hdp.states = self.hdp.LCG_constraints() #""" self.hdp.AC_revise() self.feasible_designs = [] self.infeasible_designs = []
def __init__(self, vertices, k, nump, t=None, trange=None, bounds=ia(0., 1.)): super(rbspline, self).__init__(vertices, k, nump, t=None, trange=None) if t is None: self.t_copy = kv.make_knot_vector(k, len(vertices) - 1, self.trange, type='open') else: self.t_copy = t self.t = copy.deepcopy(self.t_copy) self.bounds = bounds self.upper_boundary_knots = None # knots which bound the coarser level of detail for C2 continuity self.lower_boundary_knots = None # knots which bound the finer level of detail for C2 continuity self.level = 0 # 0 is the coarsest self.interior_knots = [] # ? self.parent = None # chg to quad tree for surf self.children = [] # chg to quad tree for surf self.active_indicies = self.active( bounds ) #set(self.offset_reference.keys()) # portions of the spline space that have associated vertices self.active_prange = bounds
def set_list(plist): for p in plist: #x = self.sobol_seq.next() x = .5 val = self.hdp(p)[0].getpoint(x) print 'setting ', p, val val = ia(val, val) self.hdp.__setattr__(p.name, val) return
def BC_newton(func, x, vertex_tpl, itmax=50, tol=1.e-15): """The scalar valued interval Newton's method TODO: make this exploit monotonicity monotonicity checking box consistency (monotonic interval newton iteration on a single DOF) inputs ---------- func = function to be minimized/extremized c = constraints in f(x,c) x = free variables in f(x,c) vertex_tpl = [0,0] max_it """ xi = copy.deepcopy(x) i = 0 not_converged = True xyz = vertex_tpl[0] # which dimension are we in [0,1,2]? #index = vertex_tpl[1] # which vertex are we attempting to contract? n = 1 ##len(x[0]) gn = xyz * n #pick the correct element of the gradient while (i < itmax and not_converged): #for xpt in [.00001,.5,.99999]: for xpt in [.5]: xm = copy.deepcopy(xi) midx = xi[xyz].value.getpoint(xpt) xm[xyz].value = midx f = func(xm) # F = func(xi) # if False: inner_grad = ia(f.grad[0, gn].inf, f.grad[0, gn].sup) inner_nx = xm[gn].value - f.value / inner_grad test_x_inner = xi[xyz].value & inner_nx inner_mid = test_x_inner.getpoint(.5) inner_midscalar = copy.deepcopy(xi) inner_midscalar[xyz].value = inner_mid inner_midvec = copy.deepcopy(xi) f_innerscalar = func(inner_midscalar) f_inner = func(inner_midvec) #newgrad = ia() nx = xm[gn].value - f.value / F.grad[0, gn] #nx = xm[gn].value - F.value/F.grad[0,gn] xiold = copy.deepcopy(xi) xi[xyz].value = xi[xyz].value & nx not_converged = IntervalAnalysis.some_convergence_criteria( xiold[xyz], xi[xyz], tol) i += 1 return xi, i, F
def factorial_search(self, test_parameters): #, designs = None): """ test_parameters :: object of class TestParameters reference bckwds w/ str :: lwl <-> candidate[str(ds.hdp.lwl)] """ """ reference this way! print 'lwl = ', candidate[str(ds.hdp.lwl)] TODO: now copy the design space and reduce per this specific design then """ SMALL = DesignSpace.SMALL tp = test_parameters keys = tp.keys #candidate = tp.next_design() for i, el in enumerate(tp.designs_): print 'design ', i candidate = dict(zip(keys, el)) #flatten(el))) design = copy.deepcopy(self.hdp) design.lwl = ia(candidate[str(design.lwl)] - SMALL, candidate[str(design.lwl)] + SMALL) design.bwl = ia(candidate[str(design.bwl)] - SMALL, candidate[str(design.bwl)] + SMALL) design.draft = ia(candidate[str(design.draft)] - SMALL, candidate[str(design.draft)] + SMALL) design.vol = ia(candidate[str(design.vol)] - SMALL, candidate[str(design.vol)] + SMALL) design.Cb = ia(candidate[str(design.Cb)] - SMALL, candidate[str(design.Cb)] + SMALL) design.Cwp = ia(candidate[str(design.Cwp)] - SMALL, candidate[str(design.Cwp)] + SMALL) design.Ccp = ia(candidate[str(design.Ccp)] - SMALL, candidate[str(design.Ccp)] + SMALL) design.LCG = ia(candidate[str(design.LCG)] - SMALL, candidate[str(design.LCG)] + SMALL) design.Cmidshp = ia(candidate[str(design.Cmidshp)] - SMALL, candidate[str(design.Cmidshp)] + SMALL) if design.valid_design: self.feasible_designs.append(design) else: self.infeasible_designs.append(design) #print 'lwl = ', candidate[str(ds.hdp.lwl)] solve for the boat! return
def get_box_containing(self, *X): for box in self.boxes: if box.contains(*X): return box ndims = self.boxes[0].ndims empty_box = [] for i in range(ndims): ebxi = ia(0., 0.) ebxi.isempty = True empty_box.append(ebxi) ans = Box(*empty_box) ans.isempty = True return ans
def plot_a_basis(self, bounds, blist, interval=ia(0., 1.), nump=30, offset=0., scaler=None): p = self.p a = interval[0] b = interval[1] s = np.linspace(a, b, nump, endpoint=True) basis = np.zeros((nump, self.n)) for i, u in enumerate(s): basis[i][blist] = self.TLMBasisFuns(u)[blist] plt.plot(s, basis[:] - offset) return
def set_this(self, key, x, design_sq): """TODO, if something goes wrong, back up one level and breadth first search """ val = self.hdp(key)[0] if isinstance(val, ia): val = self.hdp(key)[0].getpoint(x) val = ia(val, val) self.hdp.__setattr__(key.name, val) lastnode = design_sq.get_latest_child() nextnode = lp.States(self.hdp.states, parent=lastnode) lastnode.children.append(nextnode) self.hdp.states = nextnode.states print 'done ', key, '=>', val else: print 'skipped ', key return design_sq
def __init__(self, vertices, k, nump, t=None, trange=None, bounds=ia(0., 1.)): super(LevelSpline, self).__init__(vertices, k, nump, t=None, trange=None) if t is None: self.t_copy = kv.make_knot_vector(k, len(vertices) - 1, self.trange, type='open') else: self.t_copy = t self.t = copy.deepcopy(self.t_copy) self.bounds = bounds # active parametric range self.upper_boundary_knots = None # knots which bound the coarser level of detail for C2 continuity self.lower_boundary_knots = None # knots which bound the finer detail level for C2 continuity self.level = 0 # 0 is the coarsest self.interior_knots = [] # ? self.parent = None # need to re-write as quad tree...? self.children = [] # need to re-write as quad tree...? self.vertex_map = [ [a, b] for a, b in zip(range(self.n), self.t[self.k - 2:self.n + 2]) ] # knots where basis live? self.vertex_map[1][1] = (self.t[self.k - 1] + self.t[self.k]) / 2. self.vertex_map[-2][1] = (self.t[self.n] + self.t[self.n - 1]) / 2. self.offset_reference = {} # Forsey Offset style...? for el in self.vertex_map: self.offset_reference[el[0]] = [el[0], el[1]] self.active_indicies = set(self.offset_reference.keys( )) # portions of the spline space that have associated vertices self.offsets = None # offset from lower level representation to this representation self.base_curve = True # TODO: if this is used anywhere it needs to be false for non base levels return
def plot_truncated_basis(self, bounds, interval=ia(0., 1.), nump=30, offset=0., scaler=None): p = self.p a = interval[0] b = interval[1] #bi = self.active(interval) s = np.linspace(a, b, nump, endpoint=True) #numb = bi[1] - bi[0] + 1 basis = np.zeros((nump, self.n)) for i, u in enumerate(s): #span = self.FindSpan(u) #self.BasisFuns(span,u,basis[i,span-p-bi[0]:span+1]) basis[i] = self.truncate_basis(bounds, u)[:, 0] basis[i][basis[i] < 0.] = 0. #plt.plot(s,) plt.plot(s, basis[:] - offset) return #basis
}) st = lp.States(s) #st1 = (st == (y,ia(1.,3.))) #st1 = (st == (ia(-100.,100.),x)) #st1 = (st1 * (x,ia(2.,2.),y)) #st1 = (st1 ** (x,2.,y)) #st1 = (st1 ** (y,.5,x)) #st1 = (st1 ** (y,-1.,x)) # finding exponenets must have positive y #st1 = (st == (y,ia(1.,3.))) #st1 = (st1 ** (ia(1.73205080757,1.73205080757) , x, y ) ) st1 = (st == (y, ia(-1., 3.))) #st1 = (st1 ** (y,-2.,x)) st1 = (st1**(y, -1., x)) print 'Query: y in {},y = x**2'.format(st1(y)) print 'answer:' print 'y = {}'.format(st1(y)) print 'x = {}'.format(st1(x)) print 'NOTE: this does not support either ' print 'integer reasoning of CLP(BNR) Prolog' print 'nor Boolean reasoning of CLP(BNR)' print 'at the moment' #E=0. #st2 = (st + (x,1.,a))
return if __name__ == '__main__': k = 4 nump = 100 start = [0., 12.] end = [12., 0.] num = 11 #makes c0c's 5 basis function be enclosed in ia(.2,.8) vv = spline.curvalinear_vertices(start, end, num) #c0 = hb.LevelSpline(vv,k,nump)rbspline c0 = rbspline(vv, k, nump) c0.print_properties() c0i = c0.bounds_refinement(bounds=ia(.75, .8), knots=[.77, .775, .78]) c0.print_properties() c0c = copy.copy(c0) c0c.hierarchical_obsvrs = [] c1 = c0c.dyadic_refinement() c0.print_properties() #c1.t[4] = .54 c1i = rbspline(c1.vertices, k, nump, t=c1.t) c1i = c1i.bounds_refinement(bounds=ia(.75, .8), knots=[.77, .775, .78]) # # c1.plot_basis_interval([0.,1.],100,.0) # c0i.plot_basis_interval([.6,.9],10000,1.) # c0.plot_basis_interval([0.,1.],100,2.)
def var_to_ad_ia(var_inf, var_sup, N, dim, name): return ad(ia(var_inf, var_sup), name=name, N=N, dim=dim)
def get_range_of_basis(self, basis_index): a = self.t[basis_index] b = self.t[basis_index + self.k] return ia(a, b)
area=72. """ def test_HC_BC_2(V): """ constraint: f(x,y) = x^3 + 100x + 10y = 0 #""" x = V[0] y = V[1] return 10. * y + x**3 + 100. * x xo = ad(ia(-100., 100.), name='x', N=2, dim=0) yo = ad(ia(-100., 100.), name='y', N=2, dim=1) X = [xo, yo] g = test_HC_BC_2(X) print g.value print '' print g.grad print '' print g.hess print '' print 10. * yo + xo**3 + 100. * xo print '' print 3. * (xo**2) + 100. print 3. * 2. * (xo) Fthis = F_Xc(ini_CV, area=ia(50., 90.))
""" new_dims = [] for ds, do in zip(self.X, other.X): new_dims.append(ds | do) return Box(*new_dims) def contains(self, *X): """is the pt (X[0], X[1],...) in box? TODO: """ check_dim = [] for i, el in enumerate(X): check_dim.append(self[i].contains(el)) iscontained = np.asarray([el for el in check_dim]).all() return iscontained #np.asarray([el for el in check_dim]) def gett(*x): return x if __name__ == "__main__": b1 = Box(ia(0., 1.), ia(0., 1.)) b2 = Box(ia(.3, .5), ia(.7, 1.8)) b3 = b1 & b2 b4 = b1 | b2 u = .8 v = 1. print b3.contains(u, v) #blist = BoxList(b3,b4) #b_new = blist.get_box_containing(.5,.5)
A_Bmid = lp.PStates(name='A_Bmid') A_Llateral = lp.PStates(name='A_Llateral') A_Lflat = lp.PStates(name='A_Lflat') A_mid = lp.PStates(name='A_mid') A_lateral = lp.PStates(name='A_lateral') A_flat = lp.PStates(name='A_flat') BulbBeam = lp.PStates(name='BulbBeam') BulbDepth = lp.PStates(name='BulbDepth') CBulbMid = lp.PStates(name='CBulbMid') #TODO: fix this with class to construct rules graph! A_mid = A_mid == ia(10., 20.) #issue: order of assignment "matters" BulbBeam = BulbBeam == ia(5., 10.) CBulbMid = CBulbMid == ia(.5, 1.) print 'problem:' BulbDepth = BulbDepth == ia(0.1, 40.) #makes it blow down #BulbDepth = BulbDepth == ia(0.05,0.2) print 'BulbDepth = BulbDepth == ia(0.,40.) #makes it blow down' ## ##---- ## #""" # add CBuldMid to st #""" #initialize, if not already done st, vars_ = CBulbMid.construct(CBulbMid, lp.States(lp.State({})), {})
box1.surface.dyadic_loft_refinement() s1 = box1.surface.child surfaces.plot() ## ##*******************************8 ## practice: get bounds to cover the fwd edge # # s0.mastercurve.get_bounds_given_index # loc = surfaces.intersect_top(box2,box1) #0.5 basis_enclosed = box1.surface.child.get_basis_which_are_enclosed( thbspline.Box(ia(0.,loc),ia(0.,.125)) ) #basis_enclosed box1.surface.child.get_basis_which_are_active( # thbspline.Box(ia(0.,loc),ia(0.,.125)) ) box1_indices_of_interest = [el[0] for el in basis_enclosed] #basis_for_ji = [b0.mastercurve_u.basis()] #bdji = thbspline.BoundsList(box1_indices_of_interest) #box1_indices_of_interest = [0,1,2,3,4,5] #box1_indices_of_interest = [0,1] ranges = [] boxes = [] for index in box1_indices_of_interest: thisb = box1.surface.child.get_bounds_given_indices(index,0) ranges.append(thisb )
}) st = lp.States(s) #st1 = (st == (y,ia(1.,3.))) #st1 = (st == (ia(-100.,100.),x)) #st1 = (st1 * (x,ia(2.,2.),y)) #st1 = (st1 ** (x,2.,y)) #st1 = (st1 ** (y,.5,x)) #st1 = (st1 ** (y,-1.,x)) # finding exponenets must have positive y #st1 = (st == (y,ia(1.,3.))) #st1 = (st1 ** (ia(1.73205080757,1.73205080757) , x, y ) ) st1 = (st == (y, ia(-1., 3.))) #st1 = (st1 ** (y,-2.,x)) st1 = (st1**(y, -1., x)) print 'Query: y in {},y = x**2'.format(st1(y)) print 'answer:' print 'y = {}'.format(st1(y)) print 'x = {}'.format(st1(x)) print 'NOTE: this does not support either ' print 'integer reasoning of CLP(BNR) Prolog' print 'nor Boolean reasoning of CLP(BNR)' print 'at the moment' #E=0. #st2 = (st + (x,1.,a))
def tests(): """quick test of cleanup of rbspline (thbspline curves) dev -------- the list, ll, computed in the sub function 'verify_uneffected' is checked with total summations checking locally with a few vertices instead, we have: ll[5][3] Out[152]: array([-0.08166504, 10.31408691]) ll[0][3] Out[153]: array([-0.08166504, 10.31408691]) ll[5][9] Out[154]: array([0.27685547, 6.08837891]) ll[0][9] Out[155]: array([0.27685547, 6.08837891]) what about after editing the fine levels? c2.restrict(use_active=False) - c1.vertices #good c2.restrict() - c1.vertices #good c1.prolong() - c2.vertices #good c2.vertices[12:20] += .3 c2.vertices[12:20] Out[159]: array([[1.10712891, 4.71552734], [1.33833008, 4.2206543 ], [1.59736328, 3.75654297], [1.88459473, 3.32282715], [2.20039062, 2.91914063], [2.54511719, 2.54511719], [2.91914062, 2.20039063], [3.32282715, 1.88459473]]) c1.prolong() - c2.vertices >>> array of zeros (using 1 level accurate prolongation) c2.restrict() - c1.vertices >>> array of zeros c2.restrict(use_active=False) >>> array([[ 1.44250091e-03, 1.20014425e+01], [-4.51083090e-02, 1.14132250e+01], [-8.81422756e-02, 1.03024827e+01], [-8.22544401e-02, 8.74782368e+00], [ 5.42588730e-02, 7.35894637e+00], [ 2.45653380e-01, 6.05424713e+00], [ 6.02625875e-01, 4.93856337e+00], [ 1.43486036e+00, 4.31571974e+00], [ 1.80838219e+00, 3.24588219e+00], [ 2.57622381e+00, 2.57622381e+00], [ 3.27786487e+00, 1.84036487e+00], [ 3.80845660e+00, 9.27597222e-01], [ 4.97235451e+00, 6.36417010e-01], [ 6.04771222e+00, 2.39118470e-01], [ 7.36124756e+00, 5.65600581e-02], [ 8.74660327e+00, -8.34748525e-02], [ 1.03034145e+01, -8.72105037e-02], [ 1.14126620e+01, -4.56713618e-02], [ 1.20016772e+01, 1.67718702e-03]]) c2.vertices[12:20] += .3 vector = c0c.project_vertices_all_active() v2 = c1.prolong() vector - v2 >>> vector of all zeros more succinct v = c0c.prolong() vv = c1.prolong(vector=v) vv - c0c.project_vertices_all_active() now go the other way vr1 = c2.restrict() vr0 = c1.restrict(vector = vr1) vr0 - c0c.vertices make operators to speed the process c2.prolong_vertices_to_this_level() - c2.vertices """ tol = 1.e-14 adj1 = ia(0.125, 0.375) adj2 = ia(0.1875, 0.25) adj3 = ia(0.0, 0.25) c1.bounds = BoundsList([ia(0.01, 0.75)]) c2.bounds = BoundsList([ ia(0.03125, 0.09375), ia(0.0625, 0.125), ia(0.09375, 0.15625), ]) c2.bounds = BoundsList([ia(.1, .28), ia(.3, .5), ia(.51, .72)]) self = c0c for u in np.linspace(0., 1., 30): print self(u) - self.eval_new(u) # old THB - new THB test = self.CurvePoint(u) - self.eval_new(u) test2 = self.CurvePoint(u) - self.eval_new2(u) print test #Bspline - new THB print test2 #Bspline - new THB print self.CurvePoint(u) - self(u) #Bspline - old THB assert (np.linalg.norm(test) < tol), 'ERROR: curves dont match. diff= {}'.format(test) assert (np.linalg.norm(test2) < tol), 'ERROR: curves dont match. diff= {}'.format(test2) print '--- --- --- ---' print 'curve evaluation is identical across methods' print '--- --- --- ---' c0c.plotcurve() c0c.plot_thbasis() def verify_uneffected(): ll = [] for i in [0., .2, .4, .6, .8, .99]: #ll.append(c0c.project_vertices_sensible(i)) ll.append(c0c.project_vertices_all_active()) ck1 = ll[0] for el in ll[1:]: print np.linalg.norm(ck1 - el) print 'The difference in vertices is (now!!!)' print 'zero, no matter where they are ' print 'computed' return verify_uneffected() def verify_thb_fine_edit(): """here we can no longer check against the old B-spline But we may still compare THB evaluation methods against each other. AND Verify that is does not matter where one computes the projected vertives from. """ c2.vertices[12:20] += .3 self = c0c for u in np.linspace(0., 1., 30): test = self(u) - self.eval_new(u) # old THB - new THB # # this one is not going to be the same: test2 = self.children.children.CurvePoint(u) - self.eval_new2(u) #unless c2.bounds = ia(0.,1.) print test #Bspline - new THB print test2 assert (np.linalg.norm(test) < tol), 'ERROR: curves dont match. diff= {}'.format(test) #assert(np.linalg.norm(test2)<tol),'ERROR: curves dont match. diff= {}'.format(test2) print '--- --- --- ---' print 'Now check constancy of vertices' ll = [] for i in [0., .2, .3, .4, .5, .6, .8, .99]: ll.append(c0c.project_vertices_sensible(i)) ck1 = ll[0] for el in ll[1:]: print np.linalg.norm(ck1 - el) return verify_thb_fine_edit() return
Created on Sun Jan 1 21:47:38 2017 @author: lukemcculloch """ import numpy as np from design_space import HullSpace import sqKanren as lp from extended_interval_arithmetic import ia from hull_inference_ob_graph import Hull as hullclp from interval_arithmetic import ia as oia if __name__ == '__main__': self = HullSpace() self.ini_coeff() self.dsmax = ia(22., 22.) self.Cb = ia(.95, .95) self.vol = ia(2000., 300000.) self.lwl = ia(120., 120.) self.bwl = ia(20., 20.) self.draft = ia(20., 20.) #self.AC_revise() self.Cwp = ia(.3, 1.) self.Ccp = ia(0., 1.) #self.Cp = ia(.96,.99) #self.Cp = ia(.96,.96) #self.Cwp = ia(.7,.7) #""" self.states = self.shape_bow_section_inizers() self.states = self.shape_stern_section_inizers() self.states = self.SAC_run_area_ini()