def ppf(self, x): """ Computes the percent point function of the distribution at the point(s) x. It is defined as the inverse of the CDF. y = ppf(x) can be interpreted as the argument y for which the value of the cdf(x) is equal to y. Essentially that means the random varable y is the place on the distribution the CDF evaluates to x. Parameters ---------- x: array, dtype=float, shape=(m x n), bounds=(0,1) The value(s) at which the user would like the ppf evaluated. If an array is passed in, the ppf is evaluated at every point in the array and an array of the same size is returned. Returns ------- ppf: array, dtype=float, shape=(m x n) The ppf at each point in x. """ if (x <= 0).any() or (x >= 1).any(): raise ValueError('all values in x must be between 0 and 1, \ exclusive') norm = Normal(self.mu, self.sigma) ppf = np.exp(self.sigma * norm.ppf(x)) return ppf
def do_step(): # Buffer all the move_by calls and do at once. # Note that this does not buffer other state changes made in objects, # such as a teleport - we really should have that facility for a proper # simulation of a time step # we should also enforce the restriction on the move limit for each # type of object. At the moment, you can get around this limit by calling # move_by in the compute_next_move method! moves = [ ] # give the defenders a chance to tell the normals what to do # and try to teleport any zombies for p in Defender.get_all_present_instances(): moves.append( (p,) + p.compute_next_move() ) # then give the normals a chance for p in Normal.get_all_present_instances(): moves.append( (p,) + p.compute_next_move() ) # and finally the zombies, which may have been teleported to new positions for p in Zombie.get_all_present_instances(): moves.append( (p,) + p.compute_next_move() ) # then execute the moves, even though other state may have been changed # earlier for (p, delta_x, delta_y) in moves: p.move_by(delta_x, delta_y) # then convert normals into zombies if the zombies are close enough # Warning: z - number of zombies, n - number of normals, then the # time complexity of this is O( z n ) for z in Zombie.get_all_present_instances(): for n in Normal.get_all_present_instances(): d_e_e = z.distances_to(n)[3] d_touch = z.get_touching_threshold() # print(z.get_name(), n.get_name(), d_e_e, d_touch) if d_e_e <= d_touch: x = n.get_xpos() y = n.get_ypos() new_z = Zombie(size=n.get_size(), haircolor='green', xpos = x, ypos = y, move_limit=person_move_limit) new_z.arrive() n.leave() Person.del_instance(n)
def test_several_awards(): award1 = Normal(expires_in=5, quality=10) award2 = BlueFirst(expires_in=3, quality=10) award1.update_quality() award2.update_quality() assert award1.quality == 9 assert award1.expires_in == 4 assert award2.quality == 11 assert award2.expires_in == 2
def SocialNavigationGaussian_getPassOnRight(self, persons, h, dibujar): plt.close("all") lx_inf = -6 lx_sup = 8 ly_inf = -6 ly_sup = 8 normals = [] for p in persons: pn = Person(p.x / 1000, p.z / 1000, p.angle, p.vel) pn.draw(2., 1, 4. / 3., pi / 2 - pn.th, drawPersonalSpace=dibujar) pn.draw(2., 1, 4. / 3., pi - pn.th, drawPersonalSpace=dibujar) normals.append(Normal(mu=[[pn.x], [pn.y]], sigma=[-pn.th - pi / 2., 2, 1, 4. / 3], elliptical=True)) normals.append(Normal(mu=[[pn.x], [pn.y]], sigma=[-pn.th, 2, 0.75, 4. / 3], elliptical=True)) # h = 0.4 # h = prox / 100 resolution = 0.1 limits = [[lx_inf, lx_sup], [ly_inf, ly_sup]] _, z = Normal.makeGrid(normals, h, 2, limits=limits, resolution=resolution) # Las posiciones de las personas tienen que estar en metros grid = GM.filterEdges(z, h) if (dibujar): plt.figure() plt.imshow(grid, extent=[lx_inf, lx_sup, ly_inf, ly_sup], shape=grid.shape, interpolation='none', aspect='equal', origin='lower', cmap='Greys', vmin=0, vmax=2) plt.xlabel('X') plt.ylabel('Y') plt.axis('equal') np.savetxt('log.txt', grid, fmt='%i') polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] * 1000 punto.z = pnt[1] * 1000 polyline.append(punto) polylines.append(polyline) plt.show() return polylines
def main(): test_case_list = [ { 'test_args': { 'arg0': 0, 'arg1': '1' }, 'expect_val': { 'ret_val': -1 }, 'comment': 'Demo' }, ] instance_list = [Normal()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
def rand_draw(self, n): """ Return a random draw from the distribution Parameters ---------- n: number, int The number of random draws that you would like. Returns ------- draw: array, dtype=float, shape=(n x 1) The n x 1 random draws from the distribution. """ norm = Normal(self.mu, self.sigma) draw = np.exp(self.sigma * norm.rand_draw(n)) return draw
def main(): test_case_list = [ { 'test_args': { 'x': 12 }, 'expect_val': { 'ret_val': False }, 'comment': '12' }, { 'test_args': { 'x': 123321 }, 'expect_val': { 'ret_val': True }, 'comment': '123321' }, { 'test_args': { 'x': 1234321 }, 'expect_val': { 'ret_val': True }, 'comment': '1234321' }, { 'test_args': { 'x': 121212121212121212121 }, 'expect_val': { 'ret_val': False }, 'comment': '121212121212121212121' }, ] instance_list = [Normal(), Half()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
def main(): test_case_list = [ { 'test_args': {'arg0': 'abcabcbb', }, 'expect_val': {'ret_val': ('abc', 3)}, 'comment': '结果在头部' }, { 'test_args': {'arg0': 'bbbbb', }, 'expect_val': {'ret_val': ('b', 1)}, 'comment': '重复单字符' }, { 'test_args': {'arg0': 'pwwkew', }, 'expect_val': {'ret_val': ('wke', 3)}, 'comment': 'Demo' }, { 'test_args': {'arg0': 'abcdefghijklmnopqrstuvwxyz', }, 'expect_val': {'ret_val': ('abcdefghijklmnopqrstuvwxyz', 26)}, 'comment': '全串不重复' }, { 'test_args': {'arg0': 'aabbccabcab', }, 'expect_val': {'ret_val': ('cab', 3)}, 'comment': '结果在尾部' }, { 'test_args': {'arg0': 'dadf', }, 'expect_val': {'ret_val': ('adf', 3)}, 'comment': '结果在尾部' }, ] instance_list = [Normal(), Map()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
def set_scheduler_type(self): try: algorithm_name = self.args[2].lower() except IndexError: print("Algoritmo não especificado\nFinalizando...") return -1 if algorithm_name == "normal": self.algorithm = Normal(self.tasks) return 0 elif algorithm_name == "fifo": self.algorithm = FIFO(self.tasks) return 0 elif algorithm_name == "rr": self.algorithm = RR(self.tasks) return 0 else: print("Algoritmo não listado\nFinalizando...") return -1
def main(): test_case_list = [ { 'test_args': {'l1': ListNode(2, ListNode(4, ListNode(3))), 'l2': ListNode(5, ListNode(6, ListNode(4)))}, 'expect_val': {'ret_val': ListNode(7, ListNode(0, ListNode(8)))}, 'comment': '无重复' }, { 'test_args': {'l1': ListNode(0, ListNode(9)), 'l2': ListNode(5, ListNode(6, ListNode(4)))}, 'expect_val': {'ret_val': ListNode(5, ListNode(5, ListNode(5)))}, 'comment': '错位' }, { 'test_args': {'l1': ListNode(0, ListNode(9, ListNode(0, ListNode(0)))), 'l2': ListNode(5, ListNode(6, ListNode(4)))}, 'expect_val': {'ret_val': ListNode(5, ListNode(5, ListNode(5)))}, 'comment': '顶0' }, { 'test_args': {'l1': ListNode(0), 'l2': ListNode(1, ListNode(8))}, 'expect_val': {'ret_val': ListNode(1, ListNode(8))}, 'comment': 'Demo' }, ] instance_list = [Normal()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
def SocialNavigationGaussian_getSocialSpace(self, persons, h, draw): plt.close('all') ##Limites de la representacion lx_inf = -6 lx_sup = 10 ly_inf = -6 ly_sup = 10 ##########################################CLUSTERING################################################## normals = [] for p in persons: pn = Person(p.x / 1000, p.z / 1000, p.angle) pn.draw(3, 1, 1.3, pi / 2 - pn.th, drawPersonalSpace=draw) # Valores originales normals.append( Normal(mu=[[pn.x], [pn.y]], sigma=[-pn.th - pi / 2., 3, 1, 1.3], elliptical=True)) # print ("numero de gaussianas",len(normals)) resolution = 0.1 limits = [[lx_inf, lx_sup], [ly_inf, ly_sup]] _, z = Normal.makeGrid(normals, h, 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, h) ###########################LEO EL GRID Y SEPARO LAS POLILINEAS, DESPUES SE HACE CONVEXHULL#################################### polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] * 1000 punto.z = pnt[1] * 1000 polyline.append(punto) polylines.append(polyline) if (draw): ##DIBUJO ZONA Social _, z = Normal.makeGrid(normals, 0.1, 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, 0.1) polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] punto.z = pnt[1] polyline.append(punto) polylines.append(polyline) for ps in polylines: # plt.figure() for p in ps: plt.plot(p.x, p.z, "oc-") plt.axis('equal') plt.xlabel('X') plt.ylabel('Y') plt.show() return polylines
from exponential import Exponential from f_dist import F_dist from gamma import Gamma from inv_gamma import Inverse_gamma from student_t import Student_t from uniform import Uniform from numpy import array x = array([1.2, 1.5, 2.1, 5.4]) x2 = array([.1, .3, .4, .7]) mu, sigma, alpha, beta, k, gamma, d1, d2, kk, theta = [1.2, 2.3, .4, .5, 4, 3, 4, 6, 1.6, .7] lnorm = Lognorm(mu, sigma) norm = Normal(mu, sigma) beta = Beta(alpha, beta) chi = Chi(k) chi2 = Chi_square(k) exp = Exponential(gamma) f = F_dist(d1, d2) gamma = Gamma(kk, theta) invgamma = Inverse_gamma(mu, sigma) t = Student_t(d2) uniform = Uniform(alpha, d2) print 'lnorm.cdf(x): ', lnorm.cdf(x) print 'norm.cdf(x): ', norm.cdf(x) print 'beta.cdf(x2): ', beta.cdf(x2) print 'chi.cdf(x): ', chi.cdf(x) print 'chi2.cdf(x): ', chi2.cdf(x)
def getAllPersonalSpaces(self, persons, represent): personal_spaces = ["intimate", "personal", "social"] # sigma_h, sigma_r, sigma_s, h dict_space_param = { "intimate": [1.3, 1., 1.3, 0.8], "personal": [1.3, 1., 1.3, 0.4], "social": [3., 1., 1.3, 0.1], } dict_space_polylines = { "intimate": [], "personal": [], "social": [], } dict_spaces_to_plot = { "intimate": [], "personal": [], "social": [], } ##Limites de la representacion lx_inf = -6 lx_sup = 10 ly_inf = -6 ly_sup = 10 for space in personal_spaces: normals = [] for p in persons: person = Person(p.x, p.z, p.angle) # print('Pose x', person.x, 'Pose z', person.y, 'Rotacion', person.th) # person.draw(2,1, 4./3.,pi/2 - person.th, drawPersonalSpace=dibujar) #Valores originales person.draw(dict_space_param[space][0], dict_space_param[space][1], dict_space_param[space][2], pi / 2 - person.th, drawPersonalSpace=represent) normals.append( Normal(mu=[[person.x], [person.y]], sigma=[ -person.th - pi / 2., dict_space_param[space][0], dict_space_param[space][1], dict_space_param[space][2] ], elliptical=True)) # print ("numero de gaussianas",len(normals)) resolution = 0.1 limits = [[lx_inf, lx_sup], [ly_inf, ly_sup]] _, z = Normal.makeGrid(normals, dict_space_param[space][3], 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, dict_space_param[space][3]) totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] polyline_to_plt = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] * 1000 punto.z = pnt[1] * 1000 polyline.append(punto) polyline_to_plt.append([pnt[0], pnt[1]]) dict_space_polylines[space].append(polyline_to_plt) if len(polyline_to_plt) != 0: dict_spaces_to_plot[space].append(polyline_to_plt) if represent: for soc in dict_spaces_to_plot["social"]: x, y = zip(*soc) plt.plot(x, y, color='c', marker='.') for per in dict_spaces_to_plot["personal"]: x, y = zip(*per) plt.plot(x, y, color='m', marker='.') for inti in dict_spaces_to_plot["intimate"]: x, y = zip(*inti) plt.plot(x, y, color='r', marker='.') plt.axis('equal') plt.xlabel('X') plt.ylabel('Y') plt.show() return dict_space_polylines['intimate'], dict_space_polylines[ 'personal'], dict_space_polylines['social']
for x in range(z.shape[1]): if isEdge(z, x, y, h): result[y, x] = 1 print("result:") print(result, y, x) return result h = 0.5 resolution = 0.1 limits = [[-10.0, 10.0], [-10.0, 10.0]] normals = [ Normal(mu=[[1.28], [1.28]], sigma=[360 * 3.1415 / 180, 2.0, 1.0, 1.3333333333333333], elliptical=True), Normal(mu=[[1.88], [1.88]], sigma=[290 * 3.1415 / 180, 2.0, 1.0, 1.3333333333333333], elliptical=True), Normal(mu=[[2.48], [1.67]], sigma=[225 * 3.1415 / 180, 2.0, 1.0, 1.3333333333333333], elliptical=True), Normal(mu=[[-1.22], [-2.12]], sigma=[360 * 3.1415 / 180, 2.0, 1.0, 1.3333333333333333], elliptical=True), Normal(mu=[[-2.12], [-2.12]], sigma=[290 * 3.1415 / 180, 2.0, 1.0, 1.3333333333333333], elliptical=True) ] _, z = Normal.makeGrid(normals, h, 2, limits=limits, resolution=resolution)
def test_normal_award(initial_expires_in, initial_quality, expected_quality): award = Normal(expires_in=initial_expires_in, quality=initial_quality) award.update_quality() assert award.expires_in == initial_expires_in - 1 assert award.quality == expected_quality
def __init__(self, dim=None, ncomps=None, data=None, method=None, filename=None, params=None): if not filename is None: # load from file self.load_model(filename) elif not params is None: # initialize with parameters directly self.comps = params['comps'] self.ncomps = params['ncomps'] self.dim = params['dim'] self.priors = params['priors'] elif not data is None: # initialize from data assert dim and ncomps, "Need to define dim and ncomps." self.dim = dim self.ncomps = ncomps self.comps = [] if method is "uniform": # uniformly assign data points to components then estimate the parameters npr.shuffle(data) n = len(data) s = n / ncomps for i in range(ncomps): self.comps.append(Normal(dim, data=data[i * s:(i + 1) * s])) self.priors = np.ones(ncomps, dtype="double") / ncomps elif method is "random": # choose ncomp points from data randomly then estimate the parameters mus = pr.sample(data, ncomps) clusters = [[] for i in range(ncomps)] for d in data: i = np.argmin([la.norm(d - m) for m in mus]) clusters[i].append(d) for i in range(ncomps): print mus[i], clusters[i] self.comps.append( Normal(dim, mu=mus[i], sigma=np.cov(clusters[i], rowvar=0))) self.priors = np.ones(ncomps, dtype="double") / np.array( [len(c) for c in clusters]) elif method is "kmeans": # use kmeans to initialize the parameters (centroids, labels) = vq.kmeans2(data, ncomps, minit="points", iter=100) clusters = [[] for i in range(ncomps)] for (l, d) in zip(labels, data): clusters[l].append(d) # will end up recomputing the cluster centers for cluster in clusters: self.comps.append(Normal(dim, data=cluster)) self.priors = np.ones(ncomps, dtype="double") / np.array( [len(c) for c in clusters]) else: raise ValueError, "Unknown method type!" else: # these need to be defined assert dim and ncomps, "Need to define dim and ncomps." self.dim = dim self.ncomps = ncomps self.comps = [] for i in range(ncomps): self.comps.append(Normal(dim)) self.priors = np.ones(ncomps, dtype='double') / ncomps
draw2dnormal(norm, axes=ax2d) l2, = draw1dnormal(cnorm, axes=ax1d) y = ax2d.get_ylim() x = [cnorm.cond['data'], cnorm.cond['data']] l1, = ax2d.plot(x, y) def update(val): cnorm = norm.condition([0], val) x = [cnorm.cond['data'], cnorm.cond['data']] l1.set_xdata(x) x, y = evalpdf(cnorm) print cnorm #print y l2.set_xdata(y) l2.set_ydata(x) pl.draw() slider.on_changed(update) return slider if __name__ == '__main__': # Tests for the ConditionalNormal class... mu = [1.5, 0.5] sigma = [[1.0, 0.5], [0.5, 1.0]] n = Normal(2, mu=mu, sigma=sigma) sl = draw_slider_demo(n) pl.show()
self.name = ' x '.join([pdf.name for pdf in args]) self.short = "Joint" self.inp = [] self.parameters = [] for i, pdf in enumerate(self.pdfs): # TODO add indexes to repeats self.inp += [inp + str(i + 1) for inp in pdf.inp] self.parameters += [ parameter + str(i + 1) for parameter in pdf.parameters ] def distribution(self, *args): if len(args) != self.dim: raise TypeError(f"expected {self.dim} arguments, got {len(args)}") accum = 1 i = 0 for pdf in self.pdfs: accum *= pdf.distribution(*(args[i:i + pdf.dim])) i += pdf.dim return accum if __name__ == "__main__": X = Normal(5, 1) Y = Gamma(2, 3) #J = JointPDF(X, Y) J = X * Y J.plot()
def main(): a = Api() n = Normal() s = Sunday() test_case_list = [ { 'test_args': { 'haystack': '1234567893450', 'needle': '345' }, 'expect_val': { 'ret_val': 2 }, 'comment': '无重复' }, { 'test_args': { 'haystack': '123434134343434134341', 'needle': '34341' }, 'expect_val': { 'ret_val': 2 }, 'comment': '有重复' }, { 'test_args': { 'haystack': 'asfeqewqfewqfewqffds', 'needle': '34341' }, 'expect_val': { 'ret_val': -1 }, 'comment': '不存在' }, { 'test_args': { 'haystack': 'asfeqewqfewqfewqffds', 'needle': '' }, 'expect_val': { 'ret_val': 0 }, 'comment': '空输入' }, { 'test_args': { 'haystack': '1234', 'needle': 'abcdefghijklmnopqrstuvwxyz' }, 'expect_val': { 'ret_val': -1 }, 'comment': '长needle' }, ] instance_list = [a, n, s] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
import pylab as pl import numpy as np npa = np.array import pdb if False: fp = open("faithful.txt") data = [] for line in fp.readlines(): x, y = line.split() data.append([float(x), float(y)]) data = npa(data) pl.scatter(data[:, 0], data[:, 1]) x = Normal(2, data=data) draw2dnormal(x, show=True, axes=pl.gca()) if True: x = Normal(2, mu=np.array([0.1, 0.7]), sigma=np.array([[0.6, 0.4], [0.4, 0.6]])) s = x.simulate() draw2dnormal(x) pl.scatter(s[:, 0], s[:, 1]) pl.show() print(s) if False: x = Normal(2, mu=np.array([0.1, 0.7]),
def main(): test_case_list = [ { 'test_args': { 's': 'aaaabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzzzzyyxxwwvvuuttssrrqqppoonnmmllkkjjiihhggffeeddccbbaa' }, 'expect_val': { 'ret_val': 'aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzzzzyyxxwwvvuuttssrrqqppoonnmmllkkjjiihhggffeeddccbbaa' }, 'comment': '长' }, { 'test_args': { 's': "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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': '' }, 'expect_val': { 'ret_val': '' }, 'comment': '空串' }, { 'test_args': { 's': 'a' }, 'expect_val': { 'ret_val': 'a' }, 'comment': '深井冰' }, { 'test_args': { 's': 'ac' }, 'expect_val': { 'ret_val': 'a' }, 'comment': '真.深井冰' }, { 'test_args': { 's': 'babad' }, 'expect_val': { 'ret_val': 'bab' }, 'comment': 'Demo' }, { 'test_args': { 's': 'cbbd' }, 'expect_val': { 'ret_val': 'bb' }, 'comment': 'Demo' }, { 'test_args': { 's': 'abcdefcdcfaa' }, 'expect_val': { 'ret_val': 'fcdcf' }, 'comment': 'Demo' }, ] instance_list = [Normal(), Greed(), Grid()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
from f_dist import F_dist from gamma import Gamma from inv_gamma import Inverse_gamma from student_t import Student_t from uniform import Uniform from numpy import array x = array([1.2, 1.5, 2.1, 5.4]) x2 = array([.1, .3, .4, .7]) mu, sigma, alpha, beta, k, gamma, d1, d2, kk, theta = [ 1.2, 2.3, .4, .5, 4, 3, 4, 6, 1.6, .7 ] lnorm = Lognorm(mu, sigma) norm = Normal(mu, sigma) beta = Beta(alpha, beta) chi = Chi(k) chi2 = Chi_square(k) exp = Exponential(gamma) f = F_dist(d1, d2) gamma = Gamma(kk, theta) invgamma = Inverse_gamma(mu, sigma) t = Student_t(d2) uniform = Uniform(alpha, d2) print 'lnorm.cdf(x): ', lnorm.cdf(x) print 'norm.cdf(x): ', norm.cdf(x) print 'beta.cdf(x2): ', beta.cdf(x2) print 'chi.cdf(x): ', chi.cdf(x) print 'chi2.cdf(x): ', chi2.cdf(x)
def main(): test_case_list = [ { 'test_args': { 's': ' -42n54 x' }, 'expect_val': { 'ret_val': -42 }, 'comment': 'Demo' }, { 'test_args': { 's': ' w -42n54 x' }, 'expect_val': { 'ret_val': 0 }, 'comment': 'Demo' }, { 'test_args': { 's': '4193 with words' }, 'expect_val': { 'ret_val': 4193 }, 'comment': 'Demo' }, { 'test_args': { 's': '-91283472332' }, 'expect_val': { 'ret_val': -2147483648 }, 'comment': 'Demo' }, { 'test_args': { 's': '91283472332' }, 'expect_val': { 'ret_val': 2147483647 }, 'comment': 'Demo' }, { 'test_args': { 's': '+1' }, 'expect_val': { 'ret_val': 1 }, 'comment': 'Demo' }, ] instance_list = [Normal()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
def main(): test_case_list = [ { # """ # L C I R # E T O E S I I G # E D H N # """ 'test_args': { 's': 'LEETCODEISHIRING', 'rows': 3 }, 'expect_val': { 'ret_val': 'LCIRETOESIIGEDHN' }, # '' 'comment': 'Demo3' }, { # """ # L D R # E O E I I # E C I H N # T S G # """ 'test_args': { 's': 'LEETCODEISHIRING', 'rows': 4 }, 'expect_val': { 'ret_val': 'LDREOEIIECIHNTSG' }, # '' 'comment': 'Demo4' }, { # """ # P Y A I H R N PYAIHRN # A P L S I I G APLSIIG # """ 'test_args': { 's': 'PAYPALISHIRING', 'rows': 2 }, 'expect_val': { 'ret_val': 'PYAIHRNAPLSIIG' }, # '' 'comment': 'Demo2' }, ] instance_list = [Normal(), Move()] test_list = [] for t in test_case_list: for ins in instance_list: c = Compare(t['comment']) c.clazz = type(ins).__name__ c.time_cost = ins.test(**t) test_list.append(c) test_list.sort(key=lambda compare: compare.time_cost) for one in test_list: print(one)
from normal import Normal from plot_normal import draw2dnormal import pylab as pl import numpy as np npa = np.array if False: fp = open("faithful.txt") data = [] for line in fp.readlines(): x,y = line.split() data.append([float(x),float(y)]) data = npa(data) pl.scatter(data[:,0],data[:,1]) x = Normal(2, data=data) draw2dnormal(x,show=True,axes=pl.gca()) if True: x = Normal(2,mu = np.array([0.1,0.7]), sigma = np.array([[ 0.6, 0.4], [ 0.4, 0.6]])) s = x.simulate() draw2dnormal(x) pl.scatter(s[:,0],s[:,1]) pl.show() print s if False: x = Normal(2,mu = np.array([0.1,0.7]), sigma = np.array([[ 0.6, 0.4], [ 0.4, 0.6]])) #draw2dnormal(x,show=True) print x new = x.condition([0],0.1)
def getPersonalSpace(self, persons, h, dibujar): plt.close('all') ##DESCOMENTAR EL FIGUREEE # plt.figure() #ax = fig.add_subplot(111, projection='3d') #fig, ax = plt.subplots() #ax.grid(True) # x = y = np.arange(-3.0, 3.0, 0.05) # X, Y = np.meshgrid(x, y) ##Limites de la representacion lx_inf = -6 lx_sup = 10 ly_inf = -6 ly_sup = 10 """"" ##cambio los limites para los otros valores de sigma lx_inf = 0 lx_sup = 10 ly_inf = 0 ly_sup = 10 """ "" # zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))]) # Z = zs.reshape(X.shape) ##########################################CLUSTERING################################################## normals = [] for p in persons: pn = Person(p.x, p.z, p.angle) #print('Pose x', pn.x, 'Pose z', pn.y, 'Rotacion', pn.th) pn.draw(2., 1, 4. / 3., pi / 2 - pn.th, drawPersonalSpace=dibujar) #normals.append(Normal(mu=[[pn.x], [pn.y]], sigma=[-pn.th - pi/2, 2.0, 2.0, 2.0], elliptical=True)) normals.append( Normal(mu=[[pn.x], [pn.y]], sigma=[-pn.th - pi / 2., 2, 1, 4. / 3], elliptical=True)) #normals.append(Normal(mu=[[pn.x], [pn.y]], sigma=[-pn.th, 2, 1, 4. / 3], elliptical=True)) #print ("numero de gaussianas",len(normals)) # h = 0.1 # h = prox/100 resolution = 0.1 limits = [[lx_inf, lx_sup], [ly_inf, ly_sup]] _, z = Normal.makeGrid(normals, h, 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, h) #plt.figure() #plt.imshow(z, shape=grid.shape, interpolation='none', aspect='equal', origin='lower', cmap='Greys', vmin=0, vmax=2) #plt.figure() #plt.imshow(grid, shape=grid.shape, interpolation='none', aspect='equal', origin='lower', cmap='Greys', vmin=0, vmax=2) # if (dibujar): # # plt.figure() # plt.imshow(grid, extent=[lx_inf, lx_sup, ly_inf, ly_sup], shape=grid.shape, interpolation='none', aspect='equal', origin='lower', cmap='Greys', vmin=0, vmax=2) # plt.xlabel('X') # plt.ylabel('Y') # plt.axis('equal') np.savetxt('log.txt', grid, fmt='%i') ###########################LEO EL GRID Y SEPARO LAS POLILINEAS, DESPUES SE HACE CONVEXHULL#################################### polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] punto.z = pnt[1] polyline.append(punto) polylines.append(polyline) if (dibujar): ##DIBUJO ZONA Social _, z = Normal.makeGrid(normals, 0.1, 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, 0.1) polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] punto.z = pnt[1] polyline.append(punto) polylines.append(polyline) for ps in polylines: #plt.figure() for p in ps: plt.plot(p.x, p.z, "oc-") plt.axis('equal') plt.xlabel('X') plt.ylabel('Y') # plt.show() ###DIBUJO ZONA Personal _, z = Normal.makeGrid(normals, 0.4, 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, 0.4) polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] punto.z = pnt[1] polyline.append(punto) polylines.append(polyline) for ps in polylines: # plt.figure() for p in ps: plt.plot(p.x, p.z, "om-") plt.axis('equal') plt.xlabel('X') plt.ylabel('Y') # plt.show() ###DIBUJO ZONA INTIMA _, z = Normal.makeGrid(normals, 0.8, 2, limits=limits, resolution=resolution) grid = GM.filterEdges(z, 0.8) polylines = [] totalpuntosorden = getPolyline(grid, resolution, lx_inf, ly_inf) for pol in totalpuntosorden: polyline = [] for pnt in pol: punto = SNGPoint2D() punto.x = pnt[0] punto.z = pnt[1] polyline.append(punto) polylines.append(polyline) for ps in polylines: # plt.figure() for p in ps: plt.plot(p.x, p.z, "or-") plt.axis('equal') plt.xlabel('X') plt.ylabel('Y') # plt.show() plt.show() return polylines