def draw_simplex_3d_euclidean_bounds(simplex, obj_nr=0, L=[1., 1.], points=[]): '''2d->2d simplex lower bound surface. Draws a single objective below 2D simplex''' from matplotlib import pyplot as plt from matplotlib import cm t = a([simplex[0][:-1], simplex[1][:-1], simplex[2][:-1]]) y = a([simplex[0][-1]['obj'], simplex[1][-1]['obj'], simplex[2][-1]['obj']]) # (obj1, obj2) for A, B, C X1 = np.arange(-0.1, 2.1, 0.05) X2 = np.arange(-0.1, 2.1, 0.05) X1, X2 = np.meshgrid(X1, X2) fig = plt.figure() ax = fig.gca(projection='3d') LB = lower_bound_surface(X1, X2, t, y, L) ax.plot_surface(X1, X2, LB[:,:,obj_nr], linewidth=0, rstride=1, cstride=1, cmap=cm.coolwarm) ax.plot_wireframe(np.hstack((t[:,0], t[0,0])), np.hstack(([t[:,1], t[0,1]])), np.hstack((y[:,obj_nr],y[0,obj_nr])), zorder=1000) ## Line surface # points = [simplex[-1]['mins_ABC'][1]] for p in points: ax.plot([p[0]], [p[1]], [p[2]], 'go') # points = [[1.5892857095626787, 1.5892857194077434, 1.186929245703222]] # for p in points: # ax.plot([p[0]], [p[1]], [p[2]], 'ro') plt.show()
def analyse_beam(data): beam = generate_beam_from_json(data) beam.calculations() sections = [(section.start, section.end) for section in beam.sections] distance = a([np.linspace(section.start, section.end) for section in beam.sections]) return { 'sections': sections, 'distance': [distance[i].tolist() for i in range(beam.num_sections)], 'shear_force': { 'equations': beam.shear_force_eqs, 'values': [beam.shear_force_values[i].tolist() for i in range(beam.shear_force_values.shape[0])], 'plot': { 'x': distance.reshape(-1).tolist(), 'y': beam.shear_force_values.reshape(-1).tolist(), 'backup': { 'x': a([np.linspace(s.start, s.end) for s in beam.sections]).reshape(-1).tolist(), 'y': a([np.linspace(beam.shear_force_values[i], beam.shear_force_values[i]) for i in range(beam.num_sections)]).reshape(-1).tolist() } } }, 'bending_moment': { 'equations': beam.bending_moment_eqs, 'values': [beam.bending_moment_values[i].tolist() for i in range(beam.bending_moment_values.shape[0])], 'plot': { 'x': distance.reshape(-1).tolist(), 'y': beam.bending_moment_values.reshape(-1).tolist() } } }
def show_lower_pareto_bound(simplexes): from matplotlib import pyplot as plt '''For 2D -> 2D problem show the lower pareto bound.''' # Warning: unfinished, untested. def lower_bound_for_interval(t, y, dist=None, L=[1.,1.], verts=[0,1]): '''Returns lower L bound line in (f1,f2) space for an interval in multidimensional feasible region.''' def lower_bound_cracks(x1, x2, y1, y2, dist): '''Computes lower L bound crack points for the given interval.''' if dist is None: dist = enorm(x2-x1) t1 = (y1[0]-y2[0])/(2.*L[0]) + dist/2. t2 = (y1[1]-y2[1])/(2.*L[1]) + dist/2. if t1 >= t2: p1 = [y1[0] - L[0]*t2, y1[1] - L[1]*t2] p2 = [y1[0] - L[0]*t1, y2[1] - dist*L[1] + L[1]*t1] else: p2 = [y2[0] - dist*L[0] + L[0]*t2, y1[1] - L[1]*t2] p1 = [y1[0] - L[0]*t1, y1[1] - L[1]*t1] return [p1, p2] p1, p2 = lower_bound_cracks(t[verts[0]], t[verts[1]], y[verts[0]], y[verts[1]], dist) return a([y[verts[0]], p1, p2, y[verts[1]]]) # For each simplex we have dimensions+1 vertex, so what does this mean. # Patobulinimas: We could check if any of them are dominated and keep the # least dominated. for simplex in simplexes: t = a([simplex[0][:-1], simplex[1][:-1], simplex[2][:-1]]) y = a([simplex[0][-1]['obj'], simplex[1][-1]['obj'], simplex[2][-1]['obj']]) # (obj1, obj2) for A, B, C lb = lower_bound_for_interval(t, y) plt.plot(lb[:,0], lb[:,1]) # Draw longest (or nondominated) edge lower bound and mark these vertexes as stars. plt.show()
def draw_bounds(x1, x2, L=[1.,1.]): '''Draws 3 plots describing bounds for 1D->2D problems''' from matplotlib import pyplot as plt import matplotlib.ticker as plticker fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18,6)) ## Normalize x1, x2 for 2D variable space x2 = [enorm(a(x2[:-1]) - a(x1[:-1])), x2[-1]] x1 = [0, x1[-1]] ax1 = draw_objective_bounds_and_hat_epsilon(x1, x2, ax=ax1, L=L) ax2 = draw_tolerance_change(x1, x2, ax=ax2, L=L) ax3 = draw_objective_bounds(x1, x2, ax=ax3, L=L) ax1.xaxis.set_major_locator(plticker.MultipleLocator(base=0.2)) ax1.yaxis.set_major_locator(plticker.MultipleLocator(base=0.1)) # ax1.axis([0,1.,0,1.2]) ax2.xaxis.set_major_locator(plticker.MultipleLocator(base=0.2)) ax2.yaxis.set_major_locator(plticker.MultipleLocator(base=0.1)) ax3.xaxis.set_major_locator(plticker.MultipleLocator(base=0.2)) ax3.yaxis.set_major_locator(plticker.MultipleLocator(base=0.1)) # ax3.axis([0,1.2,0,1.2]) plt.show()
def test_select_point_to_explore_in_two_dimensions(self): ''' This test case just runs code on a multi-dimensional input dataset. It doesn't test any conditions, but could presumably do so in the future. ''' acquire( x=a([ [-0.5, -0.5], [-0.5, 0.5], ]), # Fake fmap and Cmap values from another set of x's fmap=a([ [0.03254087], [-0.03254087], ]), Cmap=a([ [0.07894662, -0.07894662], [-0.07894662, 0.07894662], ]), bounds=a([ [-1.0, 1.0], [-1.0, 1.0], ]), kernelfunc=default_kernel )
def test_run_optimization(self): f, _ = newton_rhapson( x=a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], [2.0, 2.0], [1.5, -1.0] ]), f0=a([ [0.0], [0.0], [0.0], [0.0], [0.0], ]), comparisons=a([ [3, 1], [0, 1], [2, 1], [4, 0], [2, 4], ]), kernelfunc=default_kernel, Hfunc=compute_H, gfunc=compute_g, sigma=2, maxiter=20, ) self.assertTrue(f[3][0] > f[1][0]) self.assertTrue(f[0][0] > f[1][0]) self.assertTrue(f[2][0] > f[1][0]) self.assertTrue(f[4][0] > f[0][0]) self.assertTrue(f[2][0] > f[4][0])
def test_get_distinct_x_from_comparisons(self): comp = a([ [[0.0], [1.0]], [[2.0], [3.0]] ]) x = get_distinct_x(comp) self.assertAlmostEqual(x, a([[0.0], [1.0], [2.0], [3.0]]))
def test_compute_expectation(self): ''' Intermediate results expected Kernel matrix: 1.0 .135335283 .135335283 1.0 K^-1: 1.018657360 -0.137860282 -0.137860282 1.018657360 Kernel vector: .324652467 .882496903 k' * Kinv: 0.209048353 0.854205285 ''' expected = predict_f(x=a([ [-1.0, 1.0], [1.0, 1.0], ]), fmap=a([ [1.0], [3.0], ]), xnew=a([0.5, 1.0]), kernelfunc=default_kernel) self.assertAlmostEqual(expected, 2.771664208)
def getColor(self, u, v): if self.tex is None: return a([1.,1.,1.]) else: u, v = map(int,(u*(self.tex.size[0]-1),v*(self.tex.size[1]-1))) c = a(self.tex.getpixel((u,v)), float) return c/255
def test_select_point_to_exploit(self): # We attempt to force exploitation by covering most of the input # space and expecting that the maximization algorithm will choose # the point between the highest outputs, given a symmetric output function. next_point = acquire( x=a([ [-0.75], [-0.25], [0.25], [0.75], ]), # I got these fmap and Cmap values from running our optimizer # on the input data with comparisons [1, 0], [1, 3], [2, 0], [2, 3]. fmap=a([ [0.08950024], [0.21423927], [0.21423927], [0.08950024], ]), Cmap=a([ [0.15672336, -0.07836168, -0.07836168, 0.0], [-0.07836168, 0.15672336, 0.0, -0.07836168], [-0.07836168, 0.0, 0.15672336, -0.07836168], [0.0, -0.07836168, -0.07836168, 0.15672336], ]), bounds=a([ [-1.0, 1.0], ]), kernelfunc=default_kernel) self.assertTrue(next_point[0] > -.25) self.assertTrue(next_point[0] < .25)
def getNormal(self, u, v): if self.bump is None: return a([0,0,0]) else: u, v = map(int,(u*(self.bump.size[0]-1),v*(self.bump.size[1]-1))) n = 2*a(self.bump.getpixel((u,v)), float)/255 - a([1.,1.,1]) return Vec3(*n).normalized()
def test_run_optimization(self): f, _ = newton_rhapson( x=a([[0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], [2.0, 2.0], [1.5, -1.0]]), f0=a([ [0.0], [0.0], [0.0], [0.0], [0.0], ]), comparisons=a([ [3, 1], [0, 1], [2, 1], [4, 0], [2, 4], ]), kernelfunc=default_kernel, Hfunc=compute_H, gfunc=compute_g, sigma=2, maxiter=20, ) self.assertTrue(f[3][0] > f[1][0]) self.assertTrue(f[0][0] > f[1][0]) self.assertTrue(f[2][0] > f[1][0]) self.assertTrue(f[4][0] > f[0][0]) self.assertTrue(f[2][0] > f[4][0])
def test_select_point_to_exploit(self): # We attempt to force exploitation by covering most of the input # space and expecting that the maximization algorithm will choose # the point between the highest outputs, given a symmetric output function. next_point = acquire( x=a([ [-0.75], [-0.25], [0.25], [0.75], ]), # I got these fmap and Cmap values from running our optimizer # on the input data with comparisons [1, 0], [1, 3], [2, 0], [2, 3]. fmap=a([ [0.08950024], [0.21423927], [0.21423927], [0.08950024], ]), Cmap=a([ [0.15672336, -0.07836168, -0.07836168, 0.0], [-0.07836168, 0.15672336, 0.0, -0.07836168], [-0.07836168, 0.0, 0.15672336, -0.07836168], [0.0, -0.07836168, -0.07836168, 0.15672336], ]), bounds=a([ [-1.0, 1.0], ]), kernelfunc=default_kernel ) self.assertTrue(next_point[0] > -.25) self.assertTrue(next_point[0] < .25)
def test_skip_repetitions_within_comparison(self): comp = a([ [[0.0], [1.0]], [[2.0], [2.0]] ]) x = get_distinct_x(comp) self.assertAlmostEqual(x, a([[0.0], [1.0], [2.0]]))
def test_skip_repetitions_across_comparisons(self): comp = a([ [[1.0], [2.0]], [[2.0], [3.0]] ]) x = get_distinct_x(comp) self.assertAlmostEqual(x, a([[1.0], [2.0], [3.0]]))
def test_compute_expectation(self): ''' Intermediate results expected Kernel matrix: 1.0 .135335283 .135335283 1.0 K^-1: 1.018657360 -0.137860282 -0.137860282 1.018657360 Kernel vector: .324652467 .882496903 k' * Kinv: 0.209048353 0.854205285 ''' expected = predict_f( x=a([ [-1.0, 1.0], [1.0, 1.0], ]), fmap=a([ [1.0], [3.0], ]), xnew=a([0.5, 1.0]), kernelfunc=default_kernel ) self.assertAlmostEqual(expected, 2.771664208)
def test_get_distinct_x_from_2_dimensional_input_data(self): comp = a([ [[1.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [3.0, 3.0]] ]) x = get_distinct_x(comp) self.assertAlmostEqual(x, a([[1.0, 2.0], [2.0, 2.0], [3.0, 3.0]]))
def optimal_myopic(domain, domain_mu_prior, domain_cm_prior, xObs, yObs,\ xres, yres, ysdbounds, lenscale, sigvar, noisevar2): out = {} bounds = [domain[0], domain[-1]] xcandidates = linspace(bounds[0], bounds[1], xres) out['x'] = xcandidates out['ev'] = zeros_like(xcandidates) ysdcandidates = linspace(ysdbounds[0], ysdbounds[1], yres) pysdcandidates = norm.pdf(ysdcandidates) for ix0, x0 in enumerate(xcandidates): x0 = a([x0]) xObsPlusX0 = append(xObs, x0) xcmpri0 = jbgp.K_se(x0, x0, lenscale, sigvar) ymu0 = jbgp.conditioned_mu(x0, xObs, yObs, lenscale, sigvar, noisevar2) ycm0 = jbgp.conditioned_covmat(x0, atleast_2d(xcmpri0), xObs, lenscale, sigvar, noisevar2) ysd0 = diag(ycm0) ycands = a([ymu0 + (ysd0 * n) for n in ysdcandidates]) for iy0, y0 in enumerate(ycands): yObsPlusY0 = append(yObs, y0) py0 = pysdcandidates[iy0] mu0 = jbgp.conditioned_mu(domain, xobsPlusX0, yObsPlusY0, lenscale, sigvar, noisevar2) evmax = mu0.max() out['ev'][ix0] += evmax * py0 return out
def emep(domainbounds, xObs, yObs, lenscale, sigvar, noisevar2, xres, yres, ysdbounds): """expected value of the max expected value of the posterior""" out = {} xcandidates = linspace(domainbounds[0], domainbounds[1], xres) out['x'] = xcandidates out['emep'] = zeros_like(xcandidates) ySDcandidates = linspace(ysdbounds[0], ysdbounds[1], yres) pdfySDcandidates = norm.pdf(ySDcandidates) cdfySDcandidates = norm.cdf(ySDcandidates) for ix0, xx0 in enumerate(xcandidates): # print 'x: ' + str(ix0) x0 = a([xx0]) # get ymu and ysd for x0 so know what points to consider for generating prob-weighted ev of max of posterior ymu0 = jbgp.conditioned_mu(x0, xObs, yObs, lenscale, sigvar, noisevar2) xcmpri0 = jbgp.K_se(x0, x0, lenscale, sigvar) # get covmat for xSam ycm0 = jbgp.conditioned_covmat(x0, atleast_2d(xcmpri0), xObs, lenscale, sigvar, noisevar2) ysd0 = diag(ycm0) # y-vals to consider with probs pysdcandidates ycands = a([ymu0 + (ysd0 * d) for d in ySDcandidates]) xObsPlusX0 = append(xObs, x0) # add considered point to xObs locations # run simulations of what happens with certain y-vals mep = zeros_like(cdfySDcandidates) for iy0, y0 in enumerate(ycands): # print 'y: ' + str(iy0) yObsPlusY0 = append(yObs, y0) py0 = pdfySDcandidates[iy0] mu0 = jbgp.conditioned_mu(domain, xObsPlusX0, yObsPlusY0, lenscale, sigvar, noisevar2) mep[iy0] = mu0.max() out['emep'][ix0] = trapz(maxevpost, cdfySDcandidates) return out
def setUp(self): self.default_f = a([ [6.0], [1.0], [2.0], ]) self.default_comparison = a([0, 2], dtype=np.int) self.default_sigma = 2.0
def testBlockSub2CenterCarWithoutBand(self): '''test BlockSub2CenterCarWithoutBand''' example = ( ( 0, a([-1.9,-1.9,-1.9])), ( 1, a([-1.7,-1.9,-1.9])) ) for ind,right in example: sub = self.bnd.BlockInd2SubWithoutBand(ind) rslt = self.bnd.BlockSub2CenterCarWithoutBand(sub) npt.assert_array_equal(rslt, right)
def test_compute_kernel_vector(self): x = a([ [0.0, 1.0], [1.0, 1.0] ]) xnew = a([0.0, 0.0]) k = kernel_vector(default_kernel, x, xnew) self.assertAlmostEqual(k, a([[.60653066], [.367879441]]))
def testNorm1(self): '''test Norm1.''' example = ( ( a( [1,1,1] ), 1 ) , ( a( [[1,3,4],[2,-2,1]] ), a( [4,2] )) ) for x,y in example: rslt = Band.norm1(x) npt.assert_allclose(rslt, y)
def testBlockSub2CenterCarWithoutBand(self): '''test BlockSub2CenterCarWithoutBand''' if 1 == 1: return example = ( ( 0, a([-1.9,-1.9,-1.9])), ( 1, a([-1.7,-1.9,-1.9])) ) for ind,right in example: sub = self.bnd.BlockInd2SubWithoutBand(ind) rslt = self.bnd.BlockSub2CenterCarWithoutBand(sub) npt.assert_array_equal(rslt, right)
def sort_vertexes_longest_edge_first(simplex): '''Motves longest edge vertexes to the simplex vertex list beggining.''' edge_lengths = [] for i in xrange(len(simplex)): edge_lengths.append(enorm(a(simplex[i-1][:-1]) - a(simplex[i][:-1]))) max_len_index = edge_lengths.index(max(edge_lengths)) top_vertex = simplex.pop(max_len_index - 2) simplex.append(top_vertex) return simplex
def get_simplex_lower_bound_minimum(X, simp, L, verts=3): # How to set current simplex for one argument function? '''Uses 3 vertex information''' if not is_in_simplex(simp[:,:-1], X): return float('inf') lb_values = [] for i, v in enumerate(simp): if i < verts: lb_values.append(v[-1] - L*enorm(a(v[:-1]) - a(X))) return max(lb_values)
def test_get_indices_for_comparisons(self): comp = a([[[1.0, 2.5], [3.0, 2.0]], [[1.0, 2.5], [1.0, 2.5]], [[2.0, 3.0], [3.0, 2.0]]]) x = a([[1.0, 2.5], [3.0, 2.0], [2.0, 3.0]]) indices = get_comparison_indices(x, comp) self.assertEqual(indices, a([ [0, 1], [0, 0], [2, 1], ]))
def test_one_iteration_yields_expected_result(self): ''' Taking our results from the computation of H in the last test, H^-1: [ -1.066045352 -0.661325899 -0.301834093 -0.661325899 -1.045461463 -0.027289758 -0.301834093 -0.027289758 -1.066045352 ] b (computed fresh): [ [-.603424068] [0.0] [.603424068] ] g: [ [-9.616613948] [4.388339650] [1.558974488] ] Then, we compute that H^-1 * g: [ [6.879072286] [1.729331837] [1.120927715] ] ''' f1, _ = newton_rhapson( x=a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], ]), f0=a([ [6.0], [1.0], [2.0], ]), comparisons=a([ [0, 2], [2, 0], ]), kernelfunc=default_kernel, Hfunc=compute_H, gfunc=compute_g, sigma=2.0, maxiter=1, ) self.assertAlmostEqual( f1, a([ [-.879072286], [-.729331837], [.879072285], ]))
def testBlockInd2SubWithoutBand(self): '''test BlockInd2SubWithoutBand''' example = ( (5, a([5,0,0]) ), (21,a([1,1,0]) ), (a([401,402]),a([[1,2],[0,0],[1,1]])) ) for ind,sub in example: result = self.bnd.BlockInd2SubWithoutBand(ind) npt.assert_array_equal(result,sub) ExceptionExample = (10000,8000) for i in ExceptionExample: self.assertRaises(exceptions.IndexError, self.bnd.BlockInd2SubWithoutBand,i)
def test_one_iteration_yields_expected_result(self): ''' Taking our results from the computation of H in the last test, H^-1: [ -1.066045352 -0.661325899 -0.301834093 -0.661325899 -1.045461463 -0.027289758 -0.301834093 -0.027289758 -1.066045352 ] b (computed fresh): [ [-.603424068] [0.0] [.603424068] ] g: [ [-9.616613948] [4.388339650] [1.558974488] ] Then, we compute that H^-1 * g: [ [6.879072286] [1.729331837] [1.120927715] ] ''' f1, _ = newton_rhapson( x=a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], ]), f0=a([ [6.0], [1.0], [2.0], ]), comparisons=a([ [0, 2], [2, 0], ]), kernelfunc=default_kernel, Hfunc=compute_H, gfunc=compute_g, sigma=2.0, maxiter=1, ) self.assertAlmostEqual(f1, a([ [-.879072286], [-.729331837], [.879072285], ]))
def test_compute_kernel_matrix(self): x = a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], ]) K = kernel_matrix(default_kernel, x) self.assertAlmostEqual(K, a([ [1.0, .60653066, .367879441], [.60653066, 1.0, .082084999], [.367879441, .082084999, 1.0], ]))
def testBlockInd2SubWithoutBand(self): '''test BlockInd2SubWithoutBand''' if 1 == 1:return example = ( (5, a([5,0,0]) ), (21,a([1,1,0]) ), (a([401,402]),a([[1,0,1],[2,0,1]])) ) for ind,sub in example: result = self.bnd.BlockInd2SubWithoutBand(ind) npt.assert_array_equal(result,sub,'{0} is wrong '.format(ind)) ExceptionExample = (10000,8000) for i in ExceptionExample: self.assertRaises(exceptions.IndexError, self.bnd.BlockInd2SubWithoutBand,i)
def is_in_region(t, p): '''Checks if point is in the triangle region using Barycentric coordinates: www.farinhansford.com/dianne/teaching/cse470/materials/BarycentricCoords.pdf''' A = det(a([[t[0][0], t[1][0], t[2][0]], [t[0][1], t[1][1], t[2][1]], [1., 1., 1.]])) A1 = det(a([[p[0], t[1][0], t[2][0]], [p[1], t[1][1], t[2][1]], [1, 1, 1]])) A2 = det(a([[t[0][0], p[0], t[2][0]], [t[0][1], p[1], t[2][1]], [1, 1, 1]])) A3 = det(a([[t[0][0], t[1][0], p[0]], [t[0][1], t[1][1], p[1]], [1, 1, 1]])) u = A1 / A v = A2 / A w = A3 / A if u >= 0 and v >= 0 and w >= 0: return True return False
def test_get_indices_for_comparisons(self): comp = a([ [[1.0, 2.5], [3.0, 2.0]], [[1.0, 2.5], [1.0, 2.5]], [[2.0, 3.0], [3.0, 2.0]] ]) x = a([[1.0, 2.5], [3.0, 2.0], [2.0, 3.0]]) indices = get_comparison_indices(x, comp) self.assertEqual(indices, a([ [0, 1], [0, 0], [2, 1], ]))
def test_compute_b_with_j_for_each_point(self): b = compute_b( f=self.default_f, comparisons=a([ [0, 2], [2, 1], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(b, a([ [.056317811], [-.207629909], [.151312099], ]))
def test_compose_c_matrix(self): C = compute_C( f=self.default_f, comparisons=a([ [0, 2], [2, 0], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(C, a([ [.136719008, 0.0, -.136719008], [0.0, 0.0, 0.0], [-.136719008, 0.0, .136719008], ]))
def test_compute_kernel_matrix(self): x = a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], ]) K = kernel_matrix(default_kernel, x) self.assertAlmostEqual( K, a([ [1.0, .60653066, .367879441], [.60653066, 1.0, .082084999], [.367879441, .082084999, 1.0], ]))
def hartman3(X): '''http://www.sfu.ca/~ssurjano/hart3.html''' alpha = (1.0, 1.2, 3.0, 3.2) A = a([[3.0, 10, 30], [0.1, 10, 35], [3.0, 10, 30], [0.1, 10, 35]]) P = a([[0.3689, 0.1170, 0.2673], [0.4699, 0.4387, 0.7470], [0.1091, 0.8732, 0.5547], [0.0381, 0.5743, 0.8828]]) sum1 = 0 for i in range(4): sum2 = 0 for j in range(3): sum2 += A[i][j] * (X[j] - P[i][j])**2 sum1 += alpha[i] * np.exp(-sum2) return -sum1
def test_compute_b_with_j_for_each_point(self): b = compute_b( f=self.default_f, comparisons=a([ [0, 2], [2, 1], ]), sigma=self.default_sigma, ) self.assertAlmostEqual( b, a([ [.056317811], [-.207629909], [.151312099], ]))
def test_compose_c_matrix(self): C = compute_C( f=self.default_f, comparisons=a([ [0, 2], [2, 0], ]), sigma=self.default_sigma, ) self.assertAlmostEqual( C, a([ [.136719008, 0.0, -.136719008], [0.0, 0.0, 0.0], [-.136719008, 0.0, .136719008], ]))
def celluloid(self, array, nb_shade): minr = amin(array[:, :, 0]) maxr = amax(array[:, :, 0]) minv = amin(array[:, :, 1]) maxv = amax(array[:, :, 1]) minb = amin(array[:, :, 2]) maxb = amax(array[:, :, 2]) seqr = a(linspace(minr, maxr, nb_shade)) seqv = a(linspace(minv, maxv, nb_shade)) seqb = a(linspace(minb, maxb, nb_shade)) shade_tab = stack((seqr, seqv, seqb), axis=0).T cp = copy(array) for line in range(cp.shape[0]): for color in range(cp.shape[1]): cp[line][color] = self.find_shade(cp[line][color], shade_tab) return cp
def pico(curvaNivel=False): aumento = 0.1 rango = 6 aumentoX = 0.4 h = 2.6 p = 1 if curvaNivel: aumento = 0.025 rango = 18 aumentoX = 0.1 b = 0.6 x = 0 for i in range(0, rango): points_set_1 = a([[-b, -1, h], [-1, -p - x, h], [1, -p - x, h], [b, -1, h]]) t_points = np.arange(0, 1, 0.01) curve_set_1 = Bezier.Curve(t_points, points_set_1) ax.plot(curve_set_1[:, 0], curve_set_1[:, 1], curve_set_1[:, 2], color="green") h = h + aumento x = x + aumentoX
def test_compute_gradient(self): ''' About this computation: Recall from the above test case that the kernel will be: [ [1.0, .60653066, .367879441], [.60653066, 1.0, .082084999], [.367879441, .082084999, 1.0], ] It follows that the inverted kernel is: [ [ 1.88589785, -1.09427888, -0.60395917], [-1.09427888, 1.64173123, 0.2678012 ], [-0.60395917, 0.2678012 , 1.2002017 ] ] From the above example for computing b, we know that b is: [ [.056317811], [-.207629909], [.151312099], ] Therefore, the expected calculation of -K^-1 * f + b is: -9.013189880 .056317811 -8.956872069 4.388339650 + -.207629909 = 4.180709741 0.955550420 .151312099 1.106862519 ''' g = compute_g(kernelfunc=default_kernel, x=a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], ]), f=self.default_f, comparisons=a([ [0, 2], [2, 1], ]), sigma=self.default_sigma) self.assertAlmostEqual( g, a([ [-8.956872069], [4.180709741], [1.106862519], ]))
def test_compute_H(self): ''' This test reuse intermediate test results that can be seen in tests for computing the kernel, computing the gradient, and computing C. From these previous test cases, we know that: K^-1 is: [ [ 1.88589785, -1.09427888, -0.60395917], [-1.09427888, 1.64173123, 0.2678012 ], [-0.60395917, 0.2678012 , 1.2002017 ] ] and C is: [ [.136719008, 0.0, -.136719008], [0.0, 0.0, 0.0], [-.136719008, 0.0, .136719008], ] We add these two matrices to compute the second derivative H. ''' H = compute_H( kernelfunc=default_kernel, x=a([ [0.0, 1.0], [1.0, 1.0], [-1.0, 0.0], ]), f=a([ [6.0], [1.0], [2.0], ]), comparisons=a([ [0, 2], [2, 0], ]), sigma=2.0, ) self.assertAlmostEqual( H, a([ [-1.749178842, 1.094278880, 0.467240162], [1.094278880, -1.641731230, -0.267801200], [0.467240162, -0.267801200, -1.063482692], ]))
def g_get_points(n): z = a([[0], [1]]) for k in range(n): m = g1(z) n = g2(z) z = np.concatenate((m,n), axis=1) x = z.real y = z.imag return x, y
def test_b_j_composed_of_one_summand_if_only_one_relevant_pair(self): res = b_j( f=self.default_f, j=2, comparisons=a([ [0, 2], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(res, -.056317811)
def test_b_j_made_up_of_multiple_terms_if_j_in_multiple_comparisons(self): res = b_j( f=self.default_f, j=2, comparisons=a([ [0, 2], [2, 1], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(res, .151312099)
def test_b_j_is_zero_when_no_comparisons_contain_j(self): res = b_j( f=self.default_f, j=1, comparisons=a([ [0, 2], [2, 0], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(res, 0.0)
def test_c_entry_with_two_constrasting_comparisons(self): res = c_m_n( f=self.default_f, m=0, n=2, comparisons=a([ [0, 2], [2, 0], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(res, -.136719008)
def test_select_point_to_explore(self): next_point = acquire( x=a([ [-0.75], [-0.4], ]), # I got these fmap and Cmap values from running our optimizer # on the input data with comparisons [0, 1] fmap=a([ [0.03254087], [-0.03254087], ]), Cmap=a([ [0.07894662, -0.07894662], [-0.07894662, 0.07894662], ]), bounds=a([ [-1.0, 1.0], ]), kernelfunc=default_kernel) self.assertTrue(next_point[0] > -.4)
def calculate_framerate(self): """Calculate the image acquisition frequency in Hz and store it in the member variable 'framerate'""" # The "StatFrameRate" attribute always reads 0.0. # Called preiodically from "resume". from numpy import argsort, array as a, nan if len(self.Frames) < 2: return nan # Find the last two image based on their frame count. counts = a([ self.Frames[i].frame.FrameCount for i in range(0, len(self.Frames)) ]) times = a( [self.frame_timestamp(i) for i in range(0, len(self.Frames))]) order = argsort(counts) count1, count2 = counts[order][-2:] time1, time2 = times[order][-2:] if count1 == 0 or count2 == 0: return nan # not enough valid images. # Calculate the frame rate based on the last two images. if time2 == time1: return nan self.framerate = (count2 - count1) / (time2 - time1)
def test_c_entry_is_summand_over_doubled_squared_sigma_when_only_one_relevant_comparison( self): res = c_m_n( f=self.default_f, m=0, n=2, comparisons=a([ [0, 2], ]), sigma=self.default_sigma, ) self.assertAlmostEqual(res, -.250644809 / 8.0)
class agent: c = a([0, 0]) # Row,Col E = [] # Sensing Matrix env = '' # Environment Generator f = 0 # Fitness Score G = [] # Gene Matrix P = [] # Next Step Policy cfg = '' def __init__(self, env, cfg): self.c = [int(g(0, 10)), int(g(0, 10))] self.env = env self.E = env.getSensingMatrix(self.c) self.G = gene(cfg) self.cfg = cfg def step(self): if np.linalg.norm(self.c) < self.cfg.B + 10: self.E = self.env.getSensingMatrix(self.c) self.P = self.G.A @ self.E @ self.G.B for i in range(len(self.P)): if self.P[i] == np.array(self.P).max(): break # Up if i == 0: self.c += a([1, 0]) # Down elif i == 1: self.c += a([-1, 0]) # Left elif i == 2: self.c += a([0, -1]) # Right elif i == 3: self.c += a([0, 1]) # Up Right elif i == 4: self.c += a([1, 1]) # Down Right elif i == 5: self.c += a([-1, 1]) # Down Left elif i == 6: self.c += a([-1, -1]) # Up Left elif i == 7: self.c += a([1, -1]) self.f += self.env.consume(self.c)
def geometry_to_points(geo): points = dict() # Bottom bracket points['bottom bracket'] = a([0., 0.]) # Seat tube points['seat tube bottom'] = points['bottom bracket'] points['seat tube top'] = a([ -cos(radians(geo['seat angle'])) * geo['seat tube'], sin(radians(geo['seat angle'])) * geo['seat tube'], ]) # Axles points['rear axle'] = a([ -sqrt(geo['chain stay']**2 - geo['bottom bracket drop']), geo['bottom bracket drop'], ]) points['front axle'] = a([ points['rear axle'][0] + geo['wheelbase'], points['rear axle'][1], ]) # Head tube points['head tube top'] = a([ geo['reach'], geo['stack'], ]) points['head tube bottom'] = a([ cos(radians(geo['head angle'])) * geo['head tube'] + geo['reach'], -sin(radians(geo['head angle'])) * geo['head tube'] + geo['stack'], ]) return points
def closestPointToCartesian(self, xx, verbose=0): """ brue force search over all triangles """ x, y, z = xx (dd, cpx, cpy, cpz) = FindClosestPointToTriSet(x, y, z, self.F, self.V) cp = a([cpx, cpy, cpz]) dist = norm(xx - cp, 2) bdy = 0 # TODO: I guess! #others = dict(whichFace=tmin) others = {} if (verbose >= 0): print "found cp: x,cp,dist=", xx, cp, dist return cp, dist, bdy, others
def f_get_points(n): z = a([[0, 1], [0, 0]]) for k in range(n): z1 = f1real(z) z2 = f2real(z) z = np.concatenate((z1,z2), axis=1) x = np.zeros([2, 2**n]) y = np.zeros([2, 2**n]) for k in range(2**n): x[:, k] = z[0, k:k+2] y[:, k] = z[1, k:k+2] return x, y