def checkgrad(f, g, x, e, RETURNGRADS=False, *args): from pylab import norm """Check correctness of gradient function g at x by comparing to numerical approximation using perturbances of size e. Simple adaptation of Carl Rasmussen's matlab-function checkgrad.""" dy = g(x, *args) if isscalar(x): dh = zeros(1, dtype=float) l = 1 else: print "x in checkgrad:" print x l = len(x) dh = zeros(l, dtype=float) for j in range(l): dx = zeros(l, dtype=float) dx[j] = e y2 = f(x + dx, *args) y1 = f(x - dx, *args) #print dx,y2,y1 dh[j] = (y2 - y1) / (2 * e) #print dh[j] print "analytic (gradient call): \n", dy print "approximation (objective call): \n", dh if RETURNGRADS: return dy, dh else: return norm(dh - dy) / norm(dh + dy)
def svm_qp(x, y, is_bias=1, is_wconstrained=1): """svm_qp(x,y,is_bias=1,is_wconstrained=1) returns the weights, bias and margin if the given pattern set X with labels Y is linearly separable, and 0s otherwise. x is the input matrix with dimension N (number of neurons) by P (number of patterns). y is the desired output vector of dimension P. y vector should consist of -1 and 1 only""" import qpsolvers R = x.shape[1] G = -(x * y).T if is_bias: N = x.shape[0] + 1 G = np.append(G.T, -y) G = G.reshape(N, R) G = G.T P = np.identity(N) P[-1, -1] = 1e-12 # regularization #for j in range(N): #P[j,j] += 1e-16 #P += 1e-10 else: N = x.shape[0] P = np.identity(N) if is_wconstrained: if is_bias: G = np.append(G, -np.identity(N)[:N - 1, :]) G = G.reshape(R + N - 1, N) h = np.array([-1.] * R + [0] * (N - 1)) else: G = np.append(G, -np.identity(N)) G = G.reshape(R + N, N) h = np.array([-1.] * R + [0] * N) else: h = np.array([-1.] * R) w = qpsolvers.solve_qp(P, np.zeros(N), G, h) if is_bias: return w[:-1], w[-1], 2 / pylab.norm(w[:-1]) else: return w, 2 / pylab.norm(w)
def corr(x,y): nx = pl.norm(x) ny = pl.norm(y) if nx == 0 or ny == 0: return 0 else: return pl.dot(x,y) / (nx * ny)
def vectors_to_Angle(self, aV1, aV2): mVect1 = pylab.matrix(aV1); mVect2 = pylab.matrix(aV2); nNorms = (pylab.norm(mVect1)*pylab.norm(mVect2)); if nNorms==0: return float('nan'); nAngle = pylab.arccos(mVect1*mVect2.T/nNorms); return float(nAngle);
def dy_Stance(self, t, y, pars, return_force = False): """ This is the ode function that is passed to the solver. Internally, it calles: legfunc1 - force of leg 1 (overwrite for new models) legfunc2 - force of leg 2 (overwrite for new models) :args: t (float): simulation time y (6x float): CoM state pars (dict): parameters, will be passed to legfunc1 and legfunc2. must also include 'foot1' (3x float), 'foot2' (3x float), 'm' (float) and 'g' (3x float) indicating the feet positions, mass and direction of gravity, respectively. return_force (bool, default: False): return [F_leg1, F_leg2] (6x float) instead of dy/dt. """ f1 = max(self.legfunc1(t, y, pars), 0) # only push l1 = norm(array(y[:3]) - array(pars['foot1'])) f1_vec = (array(y[:3]) - array(pars['foot1'])) / l1 * f1 f2 = max(self.legfunc2(t, y, pars), 0) # only push l2 = norm(array(y[:3]) - array(pars['foot2'])) f2_vec = (array(y[:3]) - array(pars['foot2'])) / l2 * f2 if return_force: return hstack([f1_vec, f2_vec]) return hstack([y[3:], (f1_vec + f2_vec) / pars['m'] + pars['g']])
def checkmodelgrad(model,e,RETURNGRADS=False,*args): from pylab import norm """Check the correctness of passed-in model in terms of cost-/gradient- computation, using gradient approximations with perturbances of size e. """ def updatemodelparams(model, newparams): model.params *= 0.0 model.params += newparams.copy() def cost(params,*args): paramsold = model.params.copy() updatemodelparams(model,params.copy().flatten()) result = model.cost(*args) updatemodelparams(model,paramsold.copy()) return result def grad(params,*args): paramsold = model.params.copy() updatemodelparams(model, params.copy().flatten()) result = model.grad(*args) updatemodelparams(model, paramsold.copy()) return result dy = model.grad(*args) l = len(model.params) dh = zeros(l,dtype=float) for j in range(l): dx = zeros(l,dtype=float) dx[j] = e y2 = cost(model.params+dx,*args) y1 = cost(model.params-dx,*args) dh[j] = (y2 - y1)/(2*e) print "analytic: \n", dy print "approximation: \n", dh if RETURNGRADS: return dy,dh else: return norm(dh-dy)/norm(dh+dy)
def getAngle(t1,c1,t2,c2): ''' Get angle between two celestials at t1 and t2 Verify if ignoring the k-cordinate makes any sense timeit 240 microseconds ''' if type(t2) == numpy.ndarray: t2 = t2[0] elif isnan(t2): print "ERROR, t2 is nan!" return t2 p1 = c1.eph(t1)[0] p1[2] = 0.0 p1l = norm(p1) p1 /= p1l p2 = c2.eph(t2)[0] p2[2] = 0.0 p2l = norm(p2) p2 /= p2l #if p1l > p2l: return p1.dot(p2) #else: # return p1.dot(p2) '''
def checkgrad(f,g,x,e,RETURNGRADS=False,*args): from pylab import norm """Check correctness of gradient function g at x by comparing to numerical approximation using perturbances of size e. Simple adaptation of Carl Rasmussen's matlab-function checkgrad.""" # print f # print g # print x # print e # print RETURNGRADS # print args dy = g(x,*args) if isscalar(x): dh = zeros(1,dtype=float) l = 1 else: print "x in checkgrad:" print x l = len(x) dh = zeros(l,dtype=float) for j in range(l): dx = zeros(l,dtype=float) dx[j] = e y2 = f(x+dx,*args) y1 = f(x-dx,*args) #print dx,y2,y1 dh[j] = (y2 - y1)/(2*e) #print dh[j] print "analytic (using your gradient function): \n", dy print "approximation (using the objective function): \n", dh if RETURNGRADS: return dy,dh else: return norm(dh-dy)/norm(dh+dy)
def solveToF(t1,c1,t2,c2,sign=False): if t2 == False: return False tf1 = t2-t1 c1p = c1.eph(t1)[0] c2p = c2.eph(t2)[0] #c1p[2] = 0.0 #c2p[2] = 0.0 c1p = norm(c1p) c2p = norm(c2p) tf2 = pi * sqrt((c1p+c2p)**3 / (8*c1.ref.mu)) #if abs(tf1-tf2) > 3000000: # print "OKAY WIERD SITUATION" # print # print # print # print "TF1",tf1 # print "TF2",tf2 if sign: return tf1-tf2 else: return abs(tf1-tf2)
def dy_Stance(self, t, y, pars, return_force=False): """ This is the ode function that is passed to the solver. Internally, it calles: legfunc1 - force of leg 1 (overwrite for new models) legfunc2 - force of leg 2 (overwrite for new models) :args: t (float): simulation time y (6x float): CoM state pars (dict): parameters, will be passed to legfunc1 and legfunc2. must also include 'foot1' (3x float), 'foot2' (3x float), 'm' (float) and 'g' (3x float) indicating the feet positions, mass and direction of gravity, respectively. return_force (bool, default: False): return [F_leg1, F_leg2] (6x float) instead of dy/dt. """ f1 = max(self.legfunc1(t, y, pars), 0) # only push l1 = norm(array(y[:3]) - array(pars['foot1'])) f1_vec = (array(y[:3]) - array(pars['foot1'])) / l1 * f1 f2 = max(self.legfunc2(t, y, pars), 0) # only push l2 = norm(array(y[:3]) - array(pars['foot2'])) f2_vec = (array(y[:3]) - array(pars['foot2'])) / l2 * f2 if return_force: return hstack([f1_vec, f2_vec]) return hstack([y[3:], (f1_vec + f2_vec) / pars['m'] + pars['g']])
def vectors_to_Angle(self, aV1, aV2): mVect1 = pylab.matrix(aV1) mVect2 = pylab.matrix(aV2) nNorms = (pylab.norm(mVect1) * pylab.norm(mVect2)) if nNorms == 0: return "-" nAngle = pylab.arccos(mVect1 * mVect2.T / nNorms) return float(nAngle)
def getMohoEvePA(t): moho = tk.Moho.eph(t)[0][:2] eve = tk.Eve.eph(t)[0][:2] moho = moho / norm(moho) eve = eve / norm(eve) return degrees(arccos(moho.dot(eve)))
def getMohoKerbinPA(t): moho = tk.Moho.eph(t)[0][:2] kerbin = tk.Kerbin.eph(t)[0][:2] moho = moho / norm(moho) kerbin = kerbin / norm(kerbin) return degrees(arccos(moho.dot(kerbin)))
def treinar(self, eta, max_iteracoes, treinamento, teste, dimension): """ Exibe a interface contendo o conjunto de dados, a reta separadora iniciada e as iterações do algoritmo até a convergência ou o limite de iterações seja atingido. """ self.showing_train_data = True self.trainset = treinamento # train set generation self.perceptron = Perceptron(eta, max_iteracoes, dimension) # perceptron instance self.perceptron.train(self.trainset) # training self.testset = teste # test set generation self.x = 0 self.y = 0 plt.ion() self.fig = plt.figure() self.ax = self.fig.add_subplot(111) # plot of the separation line. # The separation line is orthogonal to w self.fig.canvas.draw() self.ax.set_title('starting perceptron. traning data:') for y in self.trainset: if y[dimension] == 1: self.ax.plot(y[0], y[1], 'oc') else: self.ax.plot(y[0], y[1], 'om') self.fig.canvas.draw() sleep(2) self.ax.set_title('initial separation line:') w0 = self.perceptron.getHistory()[0] n = norm(w0) ww = w0 / n ww1 = [ww[1], -ww[0]] ww2 = [-ww[1], ww[0]] self.line, = self.ax.plot([ww1[0], ww2[0]], [ww1[1], ww2[1]], '--k') self.fig.canvas.draw() sleep(2) for i, w in enumerate(self.perceptron.getHistory()): self.ax.set_title('iteration {0}'.format(i)) sleep(2) n = norm(w) ww = w / n ww1 = [ww[1], -ww[0]] ww2 = [-ww[1], ww[0]] self.line.set_data([ww1[0], ww2[0]], [ww1[1], ww2[1]]) self.fig.canvas.draw() self.ax.set_title('the algorithm converged in {0} iterations'.format( len(self.perceptron.getHistory()) - 1)) self.fig.canvas.draw()
def treinar(self, eta, max_iteracoes, treinamento, teste, dimension): """ Exibe a interface contendo o conjunto de dados, a reta separadora iniciada e as iterações do algoritmo até a convergência ou o limite de iterações seja atingido. """ self.showing_train_data = True self.trainset = treinamento # train set generation self.perceptron = Perceptron(eta, max_iteracoes, dimension) # perceptron instance self.perceptron.train(self.trainset) # training self.testset = teste # test set generation self.x = 0 self.y = 0 plt.ion() self.fig = plt.figure() self.ax = self.fig.add_subplot(111) # plot of the separation line. # The separation line is orthogonal to w self.fig.canvas.draw() self.ax.set_title("starting perceptron. traning data:") for y in self.trainset: if y[dimension] == 1: self.ax.plot(y[0], y[1], "oc") else: self.ax.plot(y[0], y[1], "om") self.fig.canvas.draw() sleep(2) self.ax.set_title("initial separation line:") w0 = self.perceptron.getHistory()[0] n = norm(w0) ww = w0 / n ww1 = [ww[1], -ww[0]] ww2 = [-ww[1], ww[0]] self.line, = self.ax.plot([ww1[0], ww2[0]], [ww1[1], ww2[1]], "--k") self.fig.canvas.draw() sleep(2) for i, w in enumerate(self.perceptron.getHistory()): self.ax.set_title("iteration {0}".format(i)) sleep(2) n = norm(w) ww = w / n ww1 = [ww[1], -ww[0]] ww2 = [-ww[1], ww[0]] self.line.set_data([ww1[0], ww2[0]], [ww1[1], ww2[1]]) self.fig.canvas.draw() self.ax.set_title("the algorithm converged in {0} iterations".format(len(self.perceptron.getHistory()) - 1)) self.fig.canvas.draw()
def nrms(data_fit, data_true): """ Normalized root mean square error. """ # root mean square error rms = pl.mean(pl.norm(data_fit - data_true, axis=0)) # normalization factor is the max - min magnitude, or 2 times max dist from mean norm_factor = 2*pl.norm(data_true - pl.mean(data_true, axis=1), axis=0).max() return (norm_factor - rms)/norm_factor
def lda_report_normalize(lda, data): logging.info('Normalizing coefficients and calculating Mi') wn = -lda.coef_[0] / pl.norm(lda.coef_) w0n = -lda.intercept_[0] / pl.norm(lda.coef_) Mi = np.dot(wn, data.T) + w0n logging.info('w = {}'.format(lda.coef_[0])) logging.info('w0 = {}'.format(lda.intercept_[0])) logging.info('w~ = {}'.format(wn)) logging.info('w0/w = {}'.format(w0n)) return Mi
def angle(v1,v2): v1 = array(v1) v2 = array(v2) val = dot(v1,v2)/float(norm(v1)*norm(v2)) while val<-1: val += 2 while val>1: val -= 2 a = acos(val) a = a*180/pi return a
def lag_vector( vector_path, p=2 ): """ vector_path : path to lag vector on disk, eg., /sciclone/data10/jberwald/RBC/cells/persout/old_8_pdist_lag1.npy p : int or 'inf' """ vec = np.load( vector_path ) if p == 'inf': vecnorm = norm( vec, ord=np.inf ) else: vecnorm = norm( vec, ord=p ) return vecnorm
def simulate(self, f_u, x0, tf): """ Simulate the system. Parameters ---------- f_u: The input function f_u(t, x, i) x0: The initial state. tf: The final time. Return ------ data : A StateSpaceDataArray object. """ #pylint: disable=too-many-locals, no-member x0 = pl.matrix(x0) assert x0.shape[1] == 1 t = 0 x = x0 dt = self.dt data = StateSpaceDataList([], [], [], []) i = 0 n_x = self.A.shape[0] n_y = self.C.shape[0] assert pl.matrix(f_u(0, x0, 0)).shape[1] == 1 assert pl.matrix(f_u(0, x0, 0)).shape[0] == n_y # take square root of noise cov to prepare for noise sim if pl.norm(self.Q) > 0: sqrtQ = scipy.linalg.sqrtm(self.Q) else: sqrtQ = self.Q if pl.norm(self.R) > 0: sqrtR = scipy.linalg.sqrtm(self.R) else: sqrtR = self.R # main simulation loop while t + dt < tf: u = f_u(t, x, i) v = sqrtR.dot(pl.randn(n_y, 1)) y = self.measurement(x, u, v) data.append(t, x, y, u) w = sqrtQ.dot(pl.randn(n_x, 1)) x = self.dynamics(x, u, w) t += dt i += 1 return data.to_StateSpaceDataArray()
def snr(x, y): """ snr - signal to noise ratio v = snr(x,y); v = 20*log10( norm(x(:)) / norm(x(:)-y(:)) ) x is the original clean signal (reference). y is the denoised signal. Copyright (c) 2014 Gabriel Peyre """ return 20 * np.log10(pylab.norm(x) / pylab.norm(x - y))
def cg(A, b, x0): p = b - A.dot(x0) r = copy(p) norm_r0 = norm(r) x = copy(x0) while True: r_k_dot_r_k = r.dot(r) alpha = r_k_dot_r_k / p.dot(A.dot(p)) x += alpha * p r -= alpha * A.dot(p) beta = r.dot(r) / p.dot(A.dot(p)) p = r + beta * p if norm(r)/norm_r0 <= 1e-6: return x
def action(self): direction = self.robot.getAngle()#direction es angulo en el campo del robot posicion = self.robot.getVel()#hacia donde apunta posicionP = self.pelota.getPos()-self.robot.getPos()#donde se encuentra la pelota relativo al robot # print distance # print direction fr = Front() # print "robot: P."+str(self.robot.getPos())+" V."+str(posicion) # print "pelota:"+str(self.pelota.getPos())+" PR."+str(posicionP) angleb = angle(posicion,[posicionP[0],posicionP[1]])#calculo el angulo entre ellos # print "angulo entre ellos:"+str(angleb) # print "direction:"+str(direction) vectorp = norm(posicionP)*array([cos((direction+angleb)/180.0*pi),-sin((direction+angleb)/180.0*pi)])#supongo que el angulo se mide hacia la izquierda #vuelvo a calcular un vector supuesto que tenga la misma direccion # print "nuevo:"+str(vectorp)+" compar:"+str(posicionP) vectorp = vectorp-posicionP#calculo la diferencia de valores if norm(vectorp)>10: #quiere decir que esta medido a la derecha angleb = -angleb fr.setTR(fr.TR(angleb)) fr.setST(fr.ST(angleb)) fr.setTL(fr.TL(angleb)) # i1 = [] # for i in range(-90,90,5): # i1.append(fr.evalFunc(i)) # # plot([i for i in range(-90,90,5)],i1) # show() # # val = integrate(lambda x:fr.evalFuncUp(x),-45,45) if val!=0: val = val/integrate(lambda x:fr.evalFunc(x),-45,45) print "Cambio de angulo:"+str(val) print "Angulo o:"+str(self.robot.getAngle()) self.robot.addAngle(val) self.robot.move() print "Robot:"+str(self.robot.getPos()) print "Pelota:"+str(self.pelota.getPos())
def lod_mvfield(di='.', num=0, nf=1, t=0): x, y, u = lod_vfield(di, num) print('0 mode: \tnorm:\t' + str(pl.norm(pl.norm(u['X']) + pl.norm(u['Y'])))) for m in range(nf): x, y, uc = lod_vfield(di, 2 * m + 1 + num) x, y, us = lod_vfield(di, 2 * m + 2 + num) norc = 0 nors = 0 for f in ['X', 'Y']: norc += pl.norm(uc[f]) nors += pl.norm(us[f]) u[f] += uc[f] * cos((m + 1) * t) + us[f] * sin((m + 1) * t) print('c mode: ' + str(m + 1) + '\tnorm:\t' + str(norc)) print('s mode: ' + str(m + 1) + '\tnorm:\t' + str(nors)) return x, y, u
def draw_polygon(env, points, n=None, color=None, plot_type=3, linewidth=1., pointsize=0.02): """ Draw a polygon defined as the convex hull of a set of points. The normal vector n of the plane containing the polygon must also be supplied. env -- openravepy environment points -- list of 3D points n -- plane normal vector color -- RGBA vector plot_type -- bitmask with 1 for edges, 2 for surfaces and 4 for summits linewidth -- openravepy format pointsize -- openravepy format """ assert n is not None, "Please provide the plane normal as well" t1 = array([n[2] - n[1], n[0] - n[2], n[1] - n[0]], dtype=float) t1 /= norm(t1) t2 = cross(n, t1) points2d = [[dot(t1, x), dot(t2, x)] for x in points] hull = ConvexHull(points2d) return draw_polyhedron(env, points, color, plot_type, hull, linewidth, pointsize)
def main(): inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) targets = np.array([[0], [1], [1], [1]]) p = Perceptron(inputs, targets) p.fit() print '--- predict phase ---' inputs_bias = np.concatenate((-np.ones((inputs.shape[0], 1)), inputs), axis=1) print p.predict(inputs_bias) print '\n' inputs2, targets2 = gen_data(20) p2 = Perceptron(inputs2, targets2) p2.fit() print '\n--- predict phase ---' test_inputs2, test_targets2 = gen_data(10) test_inputs_bias2 = np.concatenate((-np.ones((test_inputs2.shape[0], 1)), test_inputs2), axis=1) print p2.predict(test_inputs_bias2) for i, x in enumerate(test_inputs2): if test_targets2[i][0] == 1: plt.plot(x[0], x[1], 'ob') else: plt.plot(x[0], x[1], 'or') n = norm(p2.w) ww = p2.w / n ww1 = [ww[1], -ww[0]] ww2 = [-ww[1], ww[0]] plt.plot([ww1[0], ww2[0]], [ww1[1], ww2[1]], '--k') plt.show()
def rhs(self, z, t=0.): """ this function represents the system """ # falls endliche fluchtzeit: # abfrage ob norm(x)>10**5 norm_z = pl.norm(z) if norm_z > self.max_norm: myLogger.debug_message("norm(z) exceeds " + str(self.max_norm) + ": norm(z) = " + str(norm_z)) z2 = (z / norm_z) * self.max_norm self.x, self.y = z2 else: self.x, self.y = z xx_dot = self.x_dot(self.x, self.y) yy_dot = self.y_dot(self.x, self.y) zDot = xx_dot, yy_dot # norm_zDot = norm(zDot) # # if norm_zDot>self.max_norm*1e3: # myLogger.debug_message("norm(z dot) exceeds 1e10: norm(z')="+str(norm_zDot)) return np.array([xx_dot, yy_dot])
def find_convex_hull(X, num_iter, num_points=None): """ if num_points is set to None, find_convex_hull will return all the points in the convex hull (that have been found) sorted according to their sharpness. Otherwise, it will return the N-sharpest points. """ (N, D) = X.shape if (num_points == None): num_points = N # randomly choose 'num_iter' direction on the unit sphere. # find the maximal point in the chosen direction, and add 1 to its counter. # only points on the convex hull will be hit, and 'sharp' corners will # have more hits than 'smooth' corners. hits = p.zeros((N, 1)) for j in xrange(num_iter): a = p.randn(D) a = a / p.norm(a) i = p.dot(X, a).argmax() hits[i] += 1 # don't take points with 0 hits num_points = min(num_points, sum(p.find(hits))) # the indices of the n-best points o = list(p.argsort(hits, 0)[xrange(-1, -(num_points + 1), -1)].flat) return X[o, :]
def find_convex_hull(X, num_iter, num_points=None): """ if num_points is set to None, find_convex_hull will return all the points in the convex hull (that have been found) sorted according to their sharpness. Otherwise, it will return the N-sharpest points. """ (N, D) = X.shape if (num_points == None): num_points = N # randomly choose 'num_iter' direction on the unit sphere. # find the maximal point in the chosen direction, and add 1 to its counter. # only points on the convex hull will be hit, and 'sharp' corners will # have more hits than 'smooth' corners. hits = p.zeros((N, 1)) for j in xrange(num_iter): a = p.randn(D) a = a / p.norm(a) i = p.dot(X, a).argmax() hits[i] += 1 # don't take points with 0 hits num_points = min(num_points, sum(p.find(hits))) # the indices of the n-best points o = list(p.argsort(hits, 0)[xrange(-1, -(num_points+1), -1)].flat) return X[o, :]
def VectorToroidalField(TF): Nij = 25 # x = linspace(0,1.4,Nij) # y = linspace(0,1.4,Nij) # x = linspace(1.0,1.4,Nij,float) x = linspace(0.9,RInj[0],Nij,float) y = linspace(-0.4,0.4,Nij,float) X=[]; Y=[]; Bx=[]; By=[]; Mag=[]; for i in range(Nij): #print i for j in range(Nij): R = array( [x[i] , y[j], 0.0 ]) B = TF.local(R) X.append(x[i]); Y.append(y[j]); Bx.append(B[0]) By.append(B[1]); MAG = sqrt(B[0]**2 + B[1]**2 + B[2]**2) if (MAG < 0.8 and pl.norm(R)<1.0) or (MAG < 0.8): Mag.append( MAG ) else: Mag.append( nan ) Q = pl.quiver( X , Y , Bx, By , array(Mag) , pivot='mid', scale=10, width =0.005,cmap=mpl.cm.winter) #,cmap=mpl.cm.winter # pl.title(r'Toroidal B($r,\phi$)-field (uniform in $z$)') pl.title(r'Toroidal Field Map (Top View) B($r,\phi$)/|B$(R_o,\phi)$|') pl.xlabel('x [m]'); pl.ylabel('y [m]'); cb=pl.colorbar(); # pl.xlim(min(x),max(x));pl.ylim(min(y),max(y)) pl.xlim(min(x),RInj[0]);pl.ylim(min(y),max(y)) return X,Y,Bx,By,Mag
def _get_angles(steps,track_length): angles = pl.zeros(track_length-2) polar = pl.zeros(pl.shape(steps)) for i in range(track_length-1): polar[i,0] = pl.norm(steps[i,:]) polar[i,1] = pl.arctan(steps[i,0]/steps[i,1]) if pl.isnan( polar[i,1]): polar[i,1] = 0 if (steps[i,0] >= 0): if (steps[i,1] >= 0): pass elif (steps[i,1] < 0): polar[i,1] += 2.*pl.pi elif (steps[i,0] < 0): if (steps[i,1] >= 0): polar[i,1] += pl.pi elif (steps[i,1] < 0): polar[i,1] += pl.pi for i in range(track_length-2): angles[i] = polar[i+1,1] - polar[i,1] return angles
def initialRand(self, dens, normX=None): '''...''' self.x = zeros(self.N) self.A = zeros(self.N) self.x[permutation(self.N)[range(int(dens * self.N))]] = 1. self.A[permutation(self.N)[range(int(dens * self.N))]] = 1. if normX != None: self.x *= normX / norm(self.x)
def MIRA_update(self): """update weights with smallest possible value to correct mistake""" for k in self.train_set: if np.dot(self.weights, k) <= self.margin: update_ = self.learning_rate*(self.margin - np.dot(self.weights, k)) update_ *= k/(pl.norm(k)**2) self.weights += update_ self.flag = True
def shot(self): direction = self.robot.getAngle()#direction es angulo en el campo del robot posicion = self.robot.getVel()#hacia donde apunta posicionP = self.porteria.getMed()-self.robot.getPos()#donde se encuentra la pelota relativo al robot angleb = angle(posicion,[posicionP[0],posicionP[1]])#calculo el angulo entre ellos vectorp = norm(posicionP)*array([cos((direction+angleb)/180.0*pi),-sin((direction+angleb)/180.0*pi)])#supongo que el angulo se mide hacia la izquierda vectorp = vectorp-posicionP#calculo la diferencia de valores if norm(vectorp)>10: #quiere decir que esta medido a la derecha angleb = -angleb self.robot.addAngle(angleb+self.robot.shotError()) self.pelota.setVel(3*self.robot.getVel()) self.pelota.move()
def _get_conf(window_positions,window_length,diffusion_coefficient): R = 0 for i in range(1,window_length): d = pl.norm(window_positions[i,:]) if (d > R): R = d log_psi = 0.2048-2.5117*diffusion_coefficient*window_length/(R+epsilon); L = -log_psi-1 return L
def is_point_internal(p): x,y,z = p[0],p[1],p[2] if x>hemisphere_center[0]: # point is in the hemisphere return norm(p-hemisphere_center) < r-w_shell if x>(-(h-r)): # point is in the shaft return y*y+z*z < (r-w_shell)*(r-w_shell) return False
def Lyapunov(v, P, W): '''W is a connectome ''' W /= norm(W) theta = W.sum(0) * 0.5 if v.ndim == 1: return -P * 0.5 * v.dot(W).dot(v) + (theta * v).sum() else: return -P * 0.5 * einsum('ij,ij->i', dot(v, W), v) + (theta * v).sum(1)
def MIRA_update(self): """update weights with smallest possible value to correct mistake""" for k in self.train_set: if np.dot(self.weights, k) <= self.margin: update_ = self.learning_rate * (self.margin - np.dot(self.weights, k)) update_ *= k / (pl.norm(k)**2) self.weights += update_ self.flag = True
def update_common_quantities(self): self.particles_per_wall = self.resolution**2 self.mass_of_particles = self.simulation.get_massofgas() self.mass_of_walls = self.particles_per_wall*self.mass_of_particles self.mass_loss_rate = self.density*self.velocity*self.width**2 self.number_of_particles = self.resolution**2 self.dx = self.width/self.resolution self.time_between_walls = self.mass_of_walls/self.mass_loss_rate self.normal /= norm(self.normal) self.center = array(self.center) self.specific_energy_to_temperature_ratio = R/(self.mu*(self.gamma-1.)) self.hfact = self.simulation.get_hfact() for v in [[1.,0.,0.], [0.,1.,0.], [0.,0.,1.]]: u = cross(v,self.normal) if norm(u)>0.: break self.u = u/norm(u) v = cross(u,self.normal) self.v = v/norm(v)
def PlotVF2D(): Nij = 200 r = linspace(0.2,2.2,Nij) z = linspace(-1.0,1.0,Nij) BMagMatrix = zeros((Nij,Nij),float) BZ0 = pl.norm(VF.local(array([0.1,0,0]))) for i in range(Nij): print i for j in range(Nij): R = array( [r[i] , 0 , z[j]] ) B = VF.local(R) Mag = pl.norm( B ) if True: #(Mag < 100.0): BMagMatrix[j,i] = Mag/BZ0 #log(Mag) pl.figure(4) # pl.pcolor(r,z,BMagMatrix); pl.contour(r,z,BMagMatrix,120); pl.title(r'Magnitude of B-field from VF Coils: |B($r,z$)|/|B($0,0$)|') pl.xlabel('r [m]'); pl.ylabel('z [m]'); pl.colorbar()
def PlotTF2D(TF): Nij = 100 x = linspace(0,1.4,Nij,float) y = linspace(0,1.4,Nij,float) BMagMatrix = zeros((Nij,Nij),float) for i in range(Nij): print i for j in range(Nij): R = array( [x[i] , y[j]] ) B = TF.local(R) Mag = pl.norm( B ) if (Mag < 2.5 and pl.norm(R)<1.0) or (Mag < 0.75): BMagMatrix[i,j] = Mag pl.figure() # pl.pcolor(x,y,BMagMatrix); pl.colorbar pl.contour(x,y,BMagMatrix,100); pl.title(r'Magnitude of B-field from TF Coils |B($r,\phi$)|/|B($R_o,\phi$)|') pl.xlabel('x [m]'); pl.ylabel('y [m]'); pl.colorbar()
def change_the_g(self, g): # funzione che in base alla posizione del cristallo su cui cade il # fotone gli cambia il g relativamente alla curvatura del cristallo raggio = math.sqrt (self.photon.r[0]**2 + self.photon.r[1]**2) delta_angle = (self.xtal.rho-raggio ) * self.xtal.curvature gtheta = self.xtal.gtheta + delta_angle return Physics.spherical2cartesian(norm(g),self.xtal.gphi, gtheta)
def test_com_jacobian(dq_norm=1e-3, q=None): if q is None: q = hrp.dof_llim + random(56) * (hrp.dof_ulim - hrp.dof_llim) dq = random(56) * dq_norm com = hrp.compute_com(q) J_com = hrp.compute_com_jacobian(q) expected = com + dot(J_com, dq) actual = hrp.compute_com(q + dq) assert norm(actual - expected) < 2 * dq_norm ** 2 return J_com
def _get_msd(positions,track_length): maxdt = 5#int(pl.floor((track_length-1)/4.)) msd = pl.zeros(maxdt) for i in range(maxdt): for j in range(maxdt): ds = positions[i+j] - positions[j] disp = pl.norm(ds)**2. msd[i] += disp msd[i] = msd[i]/maxdt return msd
def getVel(self, aPos1, aPos2): if aPos1 == []: return ['-', ['-', '-']] nVelX = (aPos2[0] - aPos1[0]) / self.dt nVelY = (aPos2[1] - aPos1[1]) / self.dt # if self.nTrackId==3 and len(self.aAllFrames)<20: # print self.nFrame, aPos1, aPos2, nVelX, nVelY; aVel = [nVelX, nVelY] nVel = pylab.norm(aVel) return [nVel, aVel]
def myfft_gc_skew(x, M=1000): """ x : GC_skew vector (list) param N: length of the GC skew vector param M: length of the template param A: amplitude between positive and negative GC skew vector """ N = len(x) template = get_template(M) + [0] * (N - M) template /= pylab.norm(template) c = abs(np.fft.ifft(np.fft.fft(x) * pylab.conj(np.fft.fft(template)))** 2) / pylab.norm(x) / pylab.norm(template) # shift the SNR vector by the template length so that the peak is at the END of the template c = np.roll(c, M // 2) return x, template, c * 2. / N
def plot_vdif(x, y, e): #e['Z'] = pl.sqrt(e['X']**2 + e['Y']**2) #plot_vfield(x, y, e) pl.figure() pl.gca().set_aspect('equal') pl.pcolor(x, y, e['Z']) pl.colorbar() pl.xlabel(r'$x$') pl.ylabel(r'$y$') print('||e||_2 =', pl.norm(e['Z'])) pl.show()
def planerot(x): ''' return (G,y) with a matrix G such that y = G*x with y[1] = 0 ''' G = zeros((2, 2)) xn = x / norm(x) G[0, 0] = xn[0] G[1, 0] = -xn[1] G[0, 1] = xn[1] G[1, 1] = xn[0] return G, dot(G, x)
def planerot(x): ''' return (G,y) with a matrix G such that y = G*x with y[1] = 0 ''' G = zeros((2,2)) xn = x / norm(x) G[0,0] = xn[0] G[1,0] = -xn[1] G[0,1] = xn[1] G[1,1] = xn[0] return G, dot(G,x)
def PlotVF2D(): Nij = 200 r = linspace(0.2, 2.2, Nij) z = linspace(-1.0, 1.0, Nij) BMagMatrix = zeros((Nij, Nij), float) BZ0 = pl.norm(VF.local(array([0.1, 0, 0]))) for i in range(Nij): print i for j in range(Nij): R = array([r[i], 0, z[j]]) B = VF.local(R) Mag = pl.norm(B) if True: #(Mag < 100.0): BMagMatrix[j, i] = Mag / BZ0 #log(Mag) pl.figure(4) # pl.pcolor(r,z,BMagMatrix); pl.contour(r, z, BMagMatrix, 120) pl.title(r'Magnitude of B-field from VF Coils: |B($r,z$)|/|B($0,0$)|') pl.xlabel('r [m]') pl.ylabel('z [m]') pl.colorbar()
def whatyouwant(paramin): global dir_pri1, dir_pri2, dir_pri3 normW2 = arange(1.4, 2.601, 0.05).tolist() dens_moy = arange(0.02, 0.981, 0.03) for d1 in range(len(dens_moy)): dir_sub1 = dir_pri1 + '/Norm_%.2f_DensMoy_%.2f' % (paramin, dens_moy[d1]) nbpatterns1 = len(os.listdir(dir_sub1)) for p1 in range(nbpatterns1): d_patty1 = dir_sub1 + '/pattern_%.3i.npy' % p1 patty1 = np_load(d_patty1) for w2 in range(len(normW2)): dir_sub2 = dir_pri2 + '/Norm_%.2f' % (normW2[w2]) nbpatterns2 = len(os.listdir(dir_sub2)) / 2 for p2 in range(nbpatterns2): d_patty2 = dir_sub2 + '/pattern_%.3i.npy' % p2 patty2 = np_load(d_patty2) d_patty0 = dir_sub2 + '/states_%.3i.jpeg' % p2 if (corrcoef(patty1, patty2)[0,1] > 0.99) \ and (abs(norm(patty1) - norm(patty2)) / norm(patty2) < 0.0005): direction = dir_pri3 + '/C_W%.2fD%.2fP%.3i_D_W%.2fP%.3i' % ( paramin, dens_moy[d1], p1, normW2[w2], p2) cmd = commands.getoutput('cp ' + d_patty2 + " " + direction + '.npy') cmd = commands.getoutput('cp ' + d_patty0 + " " + direction + '.jpeg') print direction, abs(norm(patty1) - norm(patty2)) / norm(patty2) return 1
def whatyouwant(paramin): global dir_pri1, dir_pri2, dir_pri3 dens_moy = arange(0.02, 0.981, 0.03) for d1 in range(len(dens_moy)): dir_sub1 = dir_pri1 + '/Norm_%.2f_DensMoy_%.2f' % (paramin, dens_moy[d1]) nbpatterns1 = len(os.listdir(dir_sub1)) for p1 in range(nbpatterns1): d_patty1 = dir_sub1 + '/pattern_%.3i.npy' % p1 patty1 = np_load(d_patty1) dir_sub2 = dir_pri2 + '/Norm_0.50_DensMoy_0.02' nbpatterns2 = len(os.listdir(dir_sub2)) / 2 for p2 in range(nbpatterns2): d_patty2 = dir_sub2 + '/pattern_%.3i.npy' % p2 patty2 = np_load(d_patty2) d_patty0 = dir_sub2 + '/states_%.3i.jpeg' % p2 if (corrcoef(patty1, patty2)[0,1] > 0.7) \ and (abs(norm(patty1) - norm(patty2)) / norm(patty2) < 10.05): direction = dir_pri3 + '/C_W%.2fD%.2fP%.3i_Pica_%.3i' % ( paramin, dens_moy[d1], p1, p2) cmd = commands.getoutput('cp ' + d_patty2 + " " + direction + '.npy') toimage( array(zip(*reversed(patty2.reshape(1, len( patty2))))).T).save(direction + '.jpeg') print direction, abs(norm(patty1) - norm(patty2)) / norm(patty2) return 1
def lodnplot_mumodebug(di='.', i=0, I=1, nf=8, Nt=16): x, y, u = lod_vfield(di, i) ts = pl.linspace(0, 2 * pi, Nt + 1) up = pl.zeros([len(x), len(ts)]) for i in range(len(ts)): up[:, i] = u['X'][0, :].T print('0 mode: \tnorm:\t' + str(pl.norm(pl.norm(u['X']) + pl.norm(u['Y']) + pl.norm(u['Z'])))) for m in range(nf): x, y, uc = lod_vfield(di, 2 * m + 1 + i) x, y, us = lod_vfield(di, 2 * m + 2 + i) norc = 0 nors = 0 norc += pl.norm(uc['X']) nors += pl.norm(us['X']) for t in range(len(ts)): up[:, i] += uc['X'][:, 0] * cos(m * t) + us['X'][:, 0] * sin(m * t) print('c mode: ' + str(m) + '\tnorm:\t' + str(norc)) print('s mode: ' + str(m) + '\tnorm:\t' + str(nors)) #plot_vfield(x, y, u, I) pl.figure() # pl.plot(x, u['X'][0,:], '.-', label=r'$t='+str(t/pl.pi)+'\pi$') #pl.title(r'$t='+str(t/pl.pi)+'\pi$') pl.xlabel(r'$x$') pl.ylabel(r'$u$') pl.legend(loc=0) return x, y, u
def SunAngle(PositionVector, SimulationTime): """Calculates angle between a position vector and the position vector of the Sun. Simulates a single point in time for the Sun observed from Earth using Skyfield and then calculates the angle between the position vector of the Sun and the given input position vector. Used to determine the eclipse angle of the Sun angle of the position. Arguments: PositionVector (array): Position vector. SimulationTime (:obj:`ephem.Date`): The time of the simulation. Returns: (float): The sun angle [degrees]. """ current_time_datetime = ephem.Date(SimulationTime).datetime() year = current_time_datetime.year month = current_time_datetime.month day = current_time_datetime.day hour = current_time_datetime.hour minute = current_time_datetime.minute second = current_time_datetime.second + current_time_datetime.microsecond / 1000000 current_time_skyfield = timescale_skyfield.utc( year, month, day, hour, minute, second ) Sun = database_skyfield["Sun"] Earth = database_skyfield["Earth"] SunFromEarth = Earth.at(current_time_skyfield).observe(Sun) r_SunFromEarth_km = SunFromEarth.position.km SunAngle = arccos( dot(PositionVector, r_SunFromEarth_km) / (norm(r_SunFromEarth_km) * norm(PositionVector)) ) SunAngle = SunAngle / pi * 180 return SunAngle
def plot_energyspec(di='.', i=0, nf=1): e = pl.empty(nf + 1) x, y, z, u = lod_vfield(di, i) e[0] = pl.sqrt( pl.norm(u['X'])**2 + pl.norm(u['Y'])**2 + pl.norm(u['Z'])**2) for m in range(nf): x, y, z, uc = lod_vfield(di, i=2 * m + 1 + i) x, y, z, us = lod_vfield(di, i=2 * m + 2 + i) norc = 0 nors = 0 for f in ['X', 'Y', 'Z']: norc += pl.norm(uc[f])**2 nors += pl.norm(us[f])**2 e[m + 1] = pl.sqrt(norc + nors) pl.semilogy(e) pl.grid(True) pl.xlabel(r'mode: $k$') pl.ylabel(r'$e=|| \mathbf{\hat{u}}_k||$', ha='left', va='bottom', rotation=0) pl.gca().yaxis.set_label_coords(-0.075, 1.02)