def intersect(plane, ray_pos, rays): """Returns, as an array of triples, the x-y-z coordinates of the intersections of rays originating at ray_pos with plane. Rays are given as a matrix of column vectors""" nt = plane.normal.T rel = (np.array(rays) * ((nt * (plane.pos - ray_pos))[0, 0] / np.array(nt * rays)[0])).transpose() return np.array(ray_pos.transpose())[0] + rel
def local_trans(self, joint_name, joint_angle): '''calculate local transformation of one joint :param str joint_name: the name of joint :param float joint_angle: the angle of joint in radians :return: transformation :rtype: 4x4 matrix ''' T = identity(4) # YOUR CODE HERE s = sin(joint_angle) c = cos(joint_angle) # X if 'Roll' in joint_name: T = array([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]]) # Y if 'Pitch' in joint_name: T = array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]]) # Z if 'Yaw' in joint_name: T = array([[c, s, 0, 0], [-s, c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) T[0:3, 3] = self.joint_length[joint_name] return T
def findLoudestRegion(segments,tempos): segmentMarkers = [] for segs,tempo in zip(segments,tempos): LOUDNESS_CEILING = .8 LOUDNESS_FLOOR = 1.2 window = int((16.0/tempo)*60.0/(matlib.mean(matlib.array(segs.durations)))) lpf = np.convolve(segs.loudness_max,np.ones(window)/window)[window/2:-(window/2)] lpf[0:window/2] = lpf[window/2] lpf[-(window/2):] = lpf[-(window/2)] mean = matlib.mean(matlib.array(lpf)) marker1 = 0 finalMarkers = (0,0) foundFirstMarker = 0 while((sum([s.duration for s in segs[finalMarkers[0]:finalMarkers[1]]]) < 60.0) and LOUDNESS_FLOOR < 2.0): for i,l in enumerate(lpf): if(foundFirstMarker): if l < mean*LOUDNESS_FLOOR or i == len(lpf)-1: foundFirstMarker = 0 if((i-marker1) > (finalMarkers[1]-finalMarkers[0])): finalMarkers = (marker1,i) elif l > mean*LOUDNESS_CEILING: foundFirstMarker = 1 marker1 = i # adjust thresholds to allow for longer region to be chosen, if necessary LOUDNESS_FLOOR = LOUDNESS_FLOOR + .05 LOUDNESS_CEILING = LOUDNESS_CEILING + .05 segmentMarkers.append(finalMarkers) return segmentMarkers
def fetch_pids_ttol(pnts: MatrixVector, psys: PanelSystem, ztol: float=0.01, ttol: float=0.1): shp = pnts.shape pnts = pnts.reshape((-1, 1)) numpnt = pnts.shape[0] numpnl = len(psys.pnls) pidm = zeros((1, numpnl), dtype=int) wintm = zeros((numpnt, numpnl), dtype=bool) abszm = zeros((numpnt, numpnl), dtype=float) for pnl in psys.pnls.values(): pidm[0, pnl.ind] = pnl.pid wintm[:, pnl.ind], abszm[:, pnl.ind] = pnl.within_and_absz_ttol(pnts[:, 0], ttol=ttol) abszm[wintm is False] = float('inf') minm = argmin(abszm, axis=1) minm = array(minm).flatten() pidm = array(pidm).flatten() pids = pidm[minm] pids = matrix([pids], dtype=int).transpose() indp = arange(numpnt) minz = array(abszm[indp, minm]).flatten() minz = matrix([minz], dtype=float).transpose() chkz = minz < ztol pids[logical_not(chkz)] = 0 pids = pids.reshape(shp) chkz = chkz.reshape(shp) return pids, chkz
def calc_phi_points(points, laserpos, lasertheta): """Given an array of triples points that should be in the plane generated by a laser at laserpos with theta lasertheta, calculate the inclination of the laser plane's normal vector.""" plane_line = ddd.coord(-np.sin(lasertheta), np.cos(lasertheta), 0) normals = np.cross(np.array(plane_line.T)[0], points - np.array(laserpos.T)[0]) return calc_phi_norm(np.average((normals.T / npl.norm(normals, axis = 1)).T, axis = 0), lasertheta)
def local_trans(self, joint_name, joint_angle): '''calculate local transformation of one joint :param str joint_name: the name of joint :param float joint_angle: the angle of joint in radians :return: transformation :rtype: 4x4 matrix ''' #T = array((4,4)) s = sin(joint_angle) c = cos(joint_angle) #x-Rotation if joint_name in ['LShoulderRoll','LElbowRoll','RShoulderRoll','RElbowRoll','LHipRoll','LAnkleRoll','RHipRoll','RAnkleRoll']: T = array([[1,0,0,0], [0,c,-s,0], [0,s,c,0], [0,0,0,0]]) #y-Rotation if joint_name in ['HeadPitch','LShoulderPitch','RShoulderPitch','LHipPitch','RHipPitch','LKneePitch','LAnklePitch','RKneePitch','RAnklePitch']: T = array([[c,0,s,0], [0,1,0,0], [-s,0,c,0], [0,0,0,0]]) #z-Rotation if joint_name in ['HeadYaw','LElbowYaw','RElbowYaw']: T = array([[c,s,0,0], [-s,c,0,0], [0,0,1,0], [0,0,0,0]]) if joint_name in ['RHipYawPitch','LHipYawPitch']: y = array([[c,0,s,0], [0,1,0,0], [-s,0,c,0], [0,0,0,0]]) z = array([[c,s,0,0], [-s,c,0,0], [0,0,1,0], [0,0,0,0]]) T = y.dot(z) #print(joint_name) #print(T) T[3][0] = self.lenJoint.get(joint_name)[0] T[3][1] = self.lenJoint.get(joint_name)[1] T[3][2] = self.lenJoint.get(joint_name)[2] T[3][3] = 1 return T
def eval_perceptron(neg_examples, pos_examples, w): """ %% % Evaluates the perceptron using a given weight vector. Here, evaluation % refers to finding the data points that the perceptron incorrectly classifies. % Inputs: % neg_examples - The num_neg_examples x 3 matrix for the examples with target 0. % num_neg_examples is the number of examples for the negative class. % pos_examples- The num_pos_examples x 3 matrix for the examples with target 1. % num_pos_examples is the number of examples for the positive class. % w - A 3-dimensional weight vector, the last element is the bias. % Returns: % mistakes0 - A vector containing the indices of the negative examples that have been % incorrectly classified as positive. % mistakes1 - A vector containing the indices of the positive examples that have been % incorrectly classified as negative. %% """ #num_neg_examples = size(neg_examples,1); num_neg_examples = neg_examples.shape[0] #num_pos_examples = size(pos_examples,1); num_pos_examples = pos_examples.shape[0] #mistakes0 = []; mistakes0 = array([], dtype=int) #mistakes1 = []; mistakes1 = array([], dtype=int) #for i=1:num_neg_examples for i in range(num_neg_examples): #x = neg_examples(i,:)'; x = neg_examples[i, :] #activation = x'*w; #print(x, w) activation = asscalar(x.dot(w)) #if (activation >= 0) if activation >= 0: #mistakes0 = [mistakes0;i]; mistakes0 = r_[mistakes0, i] #end #end #for i=1:num_pos_examples for i in range(num_pos_examples): #x = pos_examples(i,:)'; x = pos_examples[i, :] #activation = x'*w; #print (w) activation = asscalar(x.dot(w).astype(float32)) #if (activation < 0) if activation < 0: #mistakes1 = [mistakes1;i]; mistakes1 = r_[mistakes1, i] #end #end return mistakes0, mistakes1
def atuliza_matriz_gradientes(self, novos_bias, nova_matriz_greadiente): if self.gradientes is None: self.gradientes = nova_matriz_greadiente self.gradientes_bias = novos_bias else: for index_camada, camada in enumerate(self.gradientes): a = np.array(nova_matriz_greadiente[index_camada]) + np.array( self.gradientes[index_camada]) self.gradientes[index_camada] = a.tolist() b = np.array(novos_bias[index_camada]) + np.array( self.gradientes_bias[index_camada]) self.gradientes_bias[index_camada] = b.tolist()
def calc_rays(xys, view): """Return a matrix of column vectors of the rays corresponding to the pixels xys, given as a list of pairs. view defines the camera. The results are in camera coordinates.""" something = view_number(view) cxys = xys - np.array([view.centerx, view.centery]) return np.mat([np.full(len(xys), something), cxys[:, 0], -cxys[:, 1]], dtype=npfloat)
def generateSegmentGraphs(segments, filenames, segmentMarkers, tempos): # training set timeMarkers = [(26.516,131.312),(4.746,172.450),(41.044,201.012),(82.312,175.997),(15.370,46.003),(122.042,213.469),(30.887,122.294),(0.000,272.304),(37.785,195.357),(15.230,195.357),(37.539,172.498),(67.721,157.716),(37.282,125.899),(147.876,325.127),(14.775,192.008),(213.437,298.800),(29.553,86.022),(238.297,294.371),(21.150,193.356),(41.625,138.350)] # validation set timeMarkers = [(4.0,141.0),(25.0,177.0),(17.0,188.0),(16.0,129.0),(17.0,177.0),(15.0,136.0),(87.0,149.0),(98.0,173.0),(106.0,212.0),(0.0,104.0)] timeMarkers = [(37,125)] myMarkers = [(j.index(min(j.that(selection.start_during_range(i[0], i[0]+1.0)))),j.index(min(j.that(selection.start_during_range(i[1], i[1]+10.0))))) for j,i in zip(segments,timeMarkers)] for i in range(len(segments)): pyplot.figure(i,(16,9)) windowLen3 = int((16.0/tempos[i])*60.0/(matlib.mean(matlib.array(segments[i].durations)))) lpf3 = signal.lfilter(np.ones(windowLen3)/windowLen3,1,segments[i].loudness_max) + signal.lfilter(np.ones(windowLen3)/windowLen3,1,segments[i].loudness_max[::-1])[::-1] lpf3 = np.convolve(segments[i].loudness_max,np.ones(windowLen3)/windowLen3)[windowLen3/2:-(windowLen3/2)] lpf3[0:windowLen3/2] = lpf3[windowLen3/2] lpf3[-(windowLen3/2):] = lpf3[-(windowLen3/2)] pyplot.plot(lpf3) pyplot.xlabel('Segment Number') pyplot.ylabel('Loudness (dB)') #pyplot.vlines(segmentMarkers[i][0], min(lpf3), max(segments[i].loudness_max), 'g') #pyplot.vlines(segmentMarkers[i][1], min(lpf3), max(segments[i].loudness_max), 'g') pyplot.vlines(myMarkers[i][0], min(lpf3), max(segments[i].loudness_max), 'r') pyplot.vlines(myMarkers[i][1], min(lpf3), max(segments[i].loudness_max), 'r') pyplot.legend(["Loudness", #"Autmatically selected start time: " + str(action.humanize_time(segments[i][segmentMarkers[i][0]].start)), #"Automatically selected end time: " + str(action.humanize_time(segments[i][segmentMarkers[i][1]].start)), "Manually selected start time: " + str(action.humanize_time(timeMarkers[i][0])), "Manually selected end time: " + str(action.humanize_time(timeMarkers[i][1]))]) pyplot.title(filenames[i]) pyplot.show()
def forward_kinematics(self, joints): '''forward kinematics :param joints: {joint_name: joint_angle} ''' for chain_joints in self.chains.values(): T = identity(4) for joint in chain_joints: angle = joints[joint] Tl = self.local_trans(joint, angle) T = T.dot(Tl) self.transforms[joint] = T for i in self.transforms: if i == 'RElbowRoll': x = array(self.transforms.get(i))[3][0] y = array(self.transforms.get(i))[3][1] z = array(self.transforms.get(i))[3][2] print "x: " , x , " y: ", y , " z: " , z
def calc_phi(xys, ref_half_plane, view, cameraposor, laserpos, lasertheta): """Given an array of pixel pairs xys from a camera with view and cameraposor and laser with laserpos and lasertheta, calculate the laser inclination based on a known half-plane ref_half_plane. Throws a NoReferenceException if no pixels are in the reference half-plane.""" cref_pos = ddd.unrotate(ref_half_plane.pos - cameraposor.pos, cameraposor) cref_side = ddd.unrotate(ref_half_plane.side, cameraposor) cref_line = np.cross(cref_side, ddd.unrotate(ref_half_plane.normal, cameraposor), axis = 0) # TODO less copy-pasta cpos = np.array([cref_pos[1, 0], -cref_pos[2, 0]]) / cref_pos[0, 0] * ddd.view_number(view) \ + np.array([view.centerx, view.centery]) cline_ = cref_pos / cref_pos[0, 0] - cref_line / cref_line[0, 0] cside_ = np.array([cref_side[1, 0], -cref_side[2, 0]]) cside = np.array([cline_[2, 0], cline_[1, 0]]) if np.dot(cside, cside_) < 0: cside = - cside dxys = xys - cpos dot_products = np.array(np.mat([cside]) * np.mat(dxys).T)[0] good_xys = xys[dot_products >= 0] print("say "+str(np.average(good_xys[:,1]))) if len(good_xys) == 0: raise NoReferenceException() threepoints = ddd.threedize_plane(good_xys, view, cameraposor, ref_half_plane) return calc_phi_points(threepoints, laserpos, lasertheta)
def Intersec(s, o, v): cent = np.array(s[0:3]) rad = s[3] vt = o - cent a = np.dot(v, v) b = 2 * np.dot(v, vt) c = np.dot(vt, vt) - rad * rad sol, t1, t2 = SolveTri(a, b, c) if sol == 2: if t1 < t2: t = t1 else: t = t2 elif sol == 1: t = t1 else: t = HUGE_VAL return t
def Intersec(s,o,v): cent=np.array(s[0:3]) rad=s[3] vt=o-cent a=np.dot(v,v) b=2*np.dot(v,vt) c=np.dot(vt,vt)-rad*rad sol,t1,t2=SolveTri(a,b,c) if sol==2: if t1<t2: t=t1 else: t=t2 elif sol==1: t=t1 else: t=HUGE_VAL return t
h = screen['h'] ratiox = screen['ratiox'] ratioy = screen['ratioy'] if len(sys.argv) > 2: w = int(sys.argv[2]) if len(sys.argv) > 3: h = int(sys.argv[3]) if len(sys.argv) > 4: fnameout = sys.argv[4] if len(sys.argv) > 5: ratiox = float(sys.argv[5]) if len(sys.argv) > 6: ratioy = float(sys.argv[6]) ww = 1. * ratiox hh = ww * h / w * ratioy e = np.array(camera['loc'], dtype=float) f = np.array(camera['front'], dtype=float) u = np.array(camera['up'], dtype=float) sphs = [] for sph in objects: sphs += [np.array(sph['data'], dtype=float)] u /= np.linalg.norm(u) r = np.cross(f, u) u = np.cross(r, f) u /= np.linalg.norm(u) r /= np.linalg.norm(r) def SolveTri(a, b, c): d = b * b - 4 * a * c t1, t2 = 0., 0.
h=screen['h'] ratiox=screen['ratiox'] ratioy=screen['ratioy'] if len(sys.argv) > 2: w=int(sys.argv[2]) if len(sys.argv) > 3: h=int(sys.argv[3]) if len(sys.argv) > 4: fnameout=sys.argv[4] if len(sys.argv) > 5: ratiox=float(sys.argv[5]) if len(sys.argv) > 6: ratioy=float(sys.argv[6]) ww=1.*ratiox hh=ww*h/w*ratioy e=np.array(camera['loc'],dtype=float) f=np.array(camera['front'],dtype=float) u=np.array(camera['up'],dtype=float) sphs=[] for sph in objects: sphs += [np.array(sph['data'],dtype=float)] u/=np.linalg.norm(u) r=np.cross(f,u) u=np.cross(r,f) u/=np.linalg.norm(u) r/=np.linalg.norm(r) def SolveTri(a,b,c): d=b*b-4*a*c t1,t2 = 0., 0. sol=0
# coding:utf-8 from matplotlib.pyplot import plot, show, figure from numpy.matlib import randn, array, vstack, where from scipy.cluster.vq import kmeans, vq # 生成正态分布的二维数据 class1 = 1.5 * randn(100, 2) class2 = randn(100, 2) + array([5, 5]) features = vstack((class1, class2)) # 用k=2对这些数据进行聚类 centroids, variance = kmeans(features, 2) # 通过矢量化函数对每个数据点进行归类: code, distance = vq(features, centroids) figure() ndx = where(code == 0)[0] plot(features[ndx, 0], features[ndx, 1], '*') ndx = where(code == 1)[0] plot(features[ndx, 0], features[ndx, 1], 'r.') plot(features[:, 0], features[:, 1], 'go') show()
ww = 1. * ratiox hh = ww * h / w * ratioy if len(sys.argv) > 1: w = int(sys.argv[1]) if len(sys.argv) > 2: h = int(sys.argv[2]) if len(sys.argv) > 3: fnameout = sys.argv[3] if len(sys.argv) > 4: ratiox = float(sys.argv[4]) if len(sys.argv) > 5: ratioy = float(sys.argv[5]) sphs = [] sphs += [np.array([0, -0.1, 0, 0.05, 0.8, 0.8, 0.8], dtype=float)] sphs += [np.array([0, 0, 0, 0.05, 0.8, 0.8, 0.8], dtype=float)] sphs += [np.array([0, 0.1, 0, 0.05, 0.8, 0.8, 0.8], dtype=float)] sphs += [np.array([0.1, -0.05, 0, 0.05, 0.8, 0, 0], dtype=float)] sphs += [np.array([0.1, 0.05, 0, 0.05, 0, 0, 0.8], dtype=float)] sphs += [np.array([0.2, 0, 0, 0.05, 0, 0.8, 0], dtype=float)] sphs += [np.array([0.05, -0.05, 0.1, 0.05, 0.8, 0.8, 0.8], dtype=float)] sphs += [np.array([0.05, 0.05, 0.1, 0.05, 0.8, 0.8, 0.8], dtype=float)] sphs += [np.array([0, -0.5, 0.5, 0.02, 1, 1, 0], dtype=float)] e = np.array([0.4, 0, 0.4], dtype=float) f = np.array([-1, 0, -1], dtype=float) u = np.array([-0.707107, 0, 0.707107], dtype=float) u /= np.linalg.norm(u) r = np.cross(f, u) u = np.cross(r, f)
def softmax(self, y): maxy = np.amax(y) probas = np.exp(y-maxy) probas = probas / probas.sum(axis=0) return np.array(probas)