def testNormalizeHardcoded(self): v1 = 1/2.**(1./2)*np.array([[1., 1., 0.]]) v2 = normalize(v1) self.assertTrue(is_float_equal(v1[0, :], v2[0, :])) v3 = normalize(np.array([[5., 0., 0.]])) v4 = np.array([[1., 0., 0.]]) self.assertTrue(is_float_equal(v3[0, :], v4[0, :]))
def __init__(self, filename, input_length=None, num_classes=None, delimiter="\t", lower=False, normalized=False): self.index = 0 self.input_length = input_length self.num_classes = num_classes self.vocab = load_vectors(filename, delimiter, lower) if normalized: normalize(self.vocab) self.embedding_dim = self.vocab["UNK"].shape[0] self.x = [] self.y = []
def setUp(self): self.N = 17 # Number of rows to create -- esssentially arbitrary # Random complex matrix of unit-length vectors self.psi = random_array((self.N, 2), iscomplex=True) self.psi = normalize(self.psi) # Random real matrix of unit length vectors self.X = random_array((self.N, 3)) self.X = normalize(self.X)
def bind(self, *nodes, composition=None): if self.HIERARCHICAL: children = nodes else: children = self._concatenate_children(nodes) if composition is None: composition = self.COMPOSITION row_vecs = {} if composition: # gen_vec is the weighted average of all other blobs with # the same number of children. gen_vecs = {row: self.vector_model.zeros() for row in self.rows} comparable = (n for n in self.nodes if len(n.children) == len(children)) for node in comparable: child_sims = [my_child.similarity(other_child) for my_child, other_child in zip(children, node.children)] total_sim = stats.gmean(child_sims) for row, vec in gen_vecs.items(): vec += vectors.normalize(node.row_vecs[row]) * total_sim row_vecs = {row: vec * composition for row, vec in gen_vecs.items()} assert not np.isnan(np.sum(list(row_vecs.values()))) id_string = self._id_string(children) return VectorNode(self, id_string, children=children, row_vecs=row_vecs)
def testNormalizeReal(self): X_normalized = normalize(self.X) for i in xrange(0, self.N): row = self.X[i, :] row /= np.linalg.norm(row) self.assertTrue(is_float_equal(row, X_normalized[i,:]))
def testNormalizeComplex(self): psi_normalized = normalize(self.psi) for i in xrange(0, self.N): row = self.psi[i, :] row /= np.linalg.norm(row) self.assertTrue(is_float_equal(row, psi_normalized[i,:]))
def execute(self, obj): pos = V.vector(obj.rect.center) targpos = obj.target.rect.center traveltime = V.length(pos-targpos)/obj.maxspeed targvel = obj.target.velocity futurepos = targpos + targvel*traveltime desired_velocity = obj.maxspeed*V.normalize(futurepos - pos) obj.steering = desired_velocity - obj.velocity V.truncate(obj.steering, obj.maxforce)
def update(self): self.prevpos = V.vector(self.rect.center).copy() self.state.execute(self) ## Add a tiny force toward the center of the field if False: #self.state != S.Wait(): center = V.vector(pygame.display.get_surface().get_rect().center) towardcenter = center - self.rect.center V.normalize_ip(towardcenter) self.steering += 0.5 * towardcenter self.velocity += FORCE_PER_TICK * self.steering / (self.mass) V.truncate(self.velocity, self.maxspeed) speed = V.length(self.velocity) if speed > 0.001: self.heading = V.normalize(self.velocity) self.rect.center += self.velocity self.depth = -self.rect.centery #determine which image direction to use, based on heading and velocity: if speed >= 0.001: small = 0.382 # sin(22.5 degrees) big = 0.923 # cos(22.5 degrees) x, y = self.heading if y >= big: self.dir = 's' elif small <= y: if x > 0: self.dir = 'se' else: self.dir = 'sw' elif -small <= y: if x > 0: self.dir = 'e' else: self.dir = 'w' elif -big <= y: if x > 0: self.dir = 'ne' else: self.dir = 'nw' else: self.dir = 'n' else: self.velocity[0] = self.velocity[1] = 0.0 #image action: stopped or moving? if speed < 0.001: self.aspeed = 0.5 action = 'looking' else: self.aspeed = 0.2 * speed action = 'walking' self.images = Images.get(self.name)[self.dir][action] self.nframes = len(self.images) #advance animation frame self.frame = self.aspeed + self.frame while self.frame >= self.nframes: self.frame -= self.nframes self.image = self.images[int(self.frame)]
def execute(self, obj): pos = V.vector(obj.rect.center) targpos = obj.target.rect.center traveltime = V.length(pos - targpos) / obj.maxspeed targvel = obj.target.velocity futurepos = targpos + targvel * traveltime desired_velocity = obj.maxspeed * V.normalize(pos - futurepos) obj.steering = desired_velocity - obj.velocity V.truncate(obj.steering, obj.maxforce)
def update(self): self.prevpos = V.vector(self.rect.center).copy() self.state.execute(self) ## Add a tiny force toward the center of the field if False:#self.state != S.Wait(): center = V.vector(pygame.display.get_surface().get_rect().center) towardcenter = center - self.rect.center V.normalize_ip(towardcenter) self.steering += 0.5*towardcenter self.velocity += FORCE_PER_TICK*self.steering/(self.mass) V.truncate(self.velocity, self.maxspeed) speed = V.length(self.velocity) if speed > 0.001: self.heading = V.normalize(self.velocity) self.rect.center += self.velocity self.depth = -self.rect.centery #determine which image direction to use, based on heading and velocity: if speed >= 0.001: small = 0.382 # sin(22.5 degrees) big = 0.923 # cos(22.5 degrees) x,y = self.heading if y >= big: self.dir = 's' elif small <= y: if x > 0: self.dir = 'se' else: self.dir = 'sw' elif -small <= y: if x > 0: self.dir = 'e' else: self.dir = 'w' elif -big <= y: if x > 0: self.dir = 'ne' else: self.dir = 'nw' else: self.dir = 'n' else: self.velocity[0] = self.velocity[1] = 0.0 #image action: stopped or moving? if speed < 0.001: self.aspeed = 0.5 action = 'looking' else: self.aspeed = 0.2*speed action = 'walking' self.images = Images.get(self.name)[self.dir][action] self.nframes = len(self.images) #advance animation frame self.frame = self.aspeed+self.frame while self.frame >= self.nframes: self.frame -= self.nframes self.image = self.images[int(self.frame)]
def collision(particle1: Particle, particle2: Particle): xrel = particle2.position - particle1.position # We shift the impulse space to give the particle2 zero impulse and save particle 1 in p1. impulseShift = particle2.getImpulseVector() p1 = particle1.getImpulseVector() - impulseShift p2neu = normalize(xrel) * np.dot(p1, xrel) / magnitude(xrel) particle1.speed, particle1.direction = combilize( (p1 - p2neu + impulseShift) / particle1.mass) particle2.speed, particle2.direction = combilize( (p2neu + impulseShift) / particle2.mass) particle1.numberOfCollisions += 1 particle2.numberOfCollisions += 1
def execute(self, obj): maxforward = obj.maxspeed * obj.heading * 0.5 pressed = pygame.key.get_pressed() if pressed[K_LEFT]: desired_velocity = V.rotate(maxforward, -5) elif pressed[K_RIGHT]: desired_velocity = V.rotate(maxforward, 5) else: desired_velocity = obj.velocity obj.steering = 0.0 obj.velocity = desired_velocity obj.heading = V.normalize(obj.velocity)
def execute(self, obj): pos = obj.rect.center wp = obj.wanderpoint hd = obj.heading angle = math.atan2(wp[1], wp[0]) angle += random.uniform(-0.5, 0.5) wp[0] = math.cos(angle) wp[1] = math.sin(angle) seekvec = WANDER_OFFSET * hd + WANDER_RADIUS * wp desired_velocity = obj.maxspeed * V.normalize(seekvec) obj.steering = desired_velocity - obj.velocity V.truncate(obj.steering, obj.maxforce)
def execute(self, obj): maxforward = obj.maxspeed*obj.heading*0.5 pressed = pygame.key.get_pressed() if pressed[K_LEFT]: desired_velocity = V.rotate(maxforward, -5) elif pressed[K_RIGHT]: desired_velocity = V.rotate(maxforward, 5) else: desired_velocity = obj.velocity obj.steering = 0.0 obj.velocity = desired_velocity obj.heading = V.normalize(obj.velocity)
def execute(self, obj): pos = obj.rect.center wp = obj.wanderpoint hd = obj.heading angle = math.atan2(wp[1], wp[0]) angle += random.uniform(-0.5,0.5) wp[0] = math.cos(angle) wp[1] = math.sin(angle) seekvec = WANDER_OFFSET*hd + WANDER_RADIUS*wp desired_velocity = obj.maxspeed * V.normalize(seekvec) obj.steering = desired_velocity - obj.velocity V.truncate(obj.steering, obj.maxforce)
def update(self): #self.rect.y -= 1 target_vector = v.sub(self.target, self.pos) move_vector = [c * self.speed for c in v.normalize(target_vector)] self.x, self.y = v.add(self.pos, move_vector) self.rect.x = self.x self.rect.y = self.y for wall in walls: if self.rect.colliderect(wall.rect): if self.rect.x > 0: # Moving right; Hit the left side of the wall self.rect.right = wall.rect.left if self.rect.x < 0: # Moving left; Hit the right side of the wall self.rect.left = wall.rect.right if self.rect.y > 0: # Moving down; Hit the top side of the wall self.rect.bottom = wall.rect.top if self.rect.y < 0: # Moving up; Hit the bottom side of the wall self.rect.top = wall.rect.bottom
def bump_edge(self, node, edge='default', factor=1): """Increases the weight of an edge to another node.""" assert edge in self.graph.edges # If each edge has its own row vector, we use that vector, # otherwise we use the single row vector. row = edge if self.graph.EDGE_ROWS else '_row' # Add other node's id_vec to this node's row_vec labeled_id = self.graph.vector_model.label(node.id_vec, edge) self.row_vecs[row] += labeled_id * factor if self.graph.DYNAMIC: # This node's dynamic row vectors point to nodes that # other nodes that point to target node point to. self.dynamic_row_vecs[row] += \ vectors.normalize(node.dynamic_id_vecs[row]) * factor # The target node learns that this node points to it. node.dynamic_id_vecs[row] += self.row_vecs[row] * factor
def execute(self, obj): pos = V.vector(obj.rect.center) endpos = obj.target.rect.center desired_velocity = obj.maxspeed*V.normalize(pos - endpos) obj.steering = desired_velocity - obj.velocity V.truncate(obj.steering, obj.maxforce)
def parse_line(line, frequency): tokens = line.split() word = tokens[0] vector = v.normalize([float(x) for x in tokens[1:]]) return Word(word, vector, frequency)
def _collide(e1, e2): # orthogonally project the polygons onto the normal of each face. if all intersect, # the polygons intersect v = [e1.vertices(), e2.vertices()] col = True # currently colliding colfuture = False # will collide within one step minstep = 999999 # for a collision this frame, 0 <= step <= 1 # cut some corners if both objects are rectangular and axis-aligned aa = False if len(v[0]) == 4 and len( v[1] ) == 4 and False: # two boxes. remove the False when code is fixed a = sorted(v[0]) b = sorted(v[1]) for i in [a, b]: if i[0][0] != i[1][0] or a[2][0] != a[3][ 0]: # should be two unique x values (lists sorted by x val) break elif i[0][1] != i[2][1] or i[1][1] != i[3][ 1]: # should be two unique y values break else: # axis aligned xs1 = ys1 = xs2 = ys2 = [] for i in a: xs1 += i[0] ys1 += i[1] for i in b: xs2 += i[0] ys2 += i[1] coords = [(xs1, ys1), (xs2, ys2)] overx = False if min(xs1) > max(xs2): maxx, minx = xs1, xs2 maxxe, minxe = e1, e2 elif min(xs2) > max(xs1): maxx, minx = xs2, xs1 maxxe, minxe = e2, e1 else: # they're overlapping on x. what if the shape moves right past? overx = True overy = False if min(ys1) > max(ys2): maxy, miny = ys1, ys2 maxye, minye = e1, e2 elif min(ys2) > max(ys1): maxy, miny = ys2, ys1 maxye, minye = e2, e1 else: # they're overlapping on y overy = True if overx and overy: col = True colfuture = True minstep = 0 aa = True else: #needs work tx = (minxe.pos[0] - maxxe.pos[0]) / (maxxe.vel[0] - minxe.vel[0]) ty = (minye.pos[1] - maxye.pos[1]) / (maxye.vel[1] - maxye.vel[1]) # generic stuff j = 0 while j < 2 and not aa: i = 0 while i < len(v[j]): axis = vectors.normalize( (-(v[j][i][1] - v[j][i - 1][1]), v[j][i][0] - v[j][i - 1][0])) # axis of projection / normal # first poly min1 = max1 = vectors.dot( axis, v[0][0] ) # the magnitude of a projection onto a unit vector is just their dot product #min1p = max1p = v[0][0] n = 0 while n < len(v[0]): proj = vectors.dot(axis, v[0][n]) if proj > max1: max1 = proj #max1p = v[0][n] elif proj < min1: min1 = proj #min1p = v[0][n] n += 1 #off = vectors.dot(axis, e1.pos) #min1 += off #max1 += off # second poly min2 = max2 = vectors.dot(axis, v[1][0]) #min2p = max2p = v[1][0] n = 0 while n < len(v[1]): proj = vectors.dot(axis, v[1][n]) if proj > max2: max2 = proj #max2p = v[1][n] elif proj < min2: min2 = proj #min2p = v[1][n] n += 1 #off = vectors.dot(axis, e2.pos) #min2 += off #max2 += off #print "j:", j, "i:", i #print "axis:", axis, "normal of:", v[j][i], "and", v[j][i - 1] #print "\tmin1:", min1, "max2:", max2, "min2:", min2, "max1:", max1 #print "\tmin1:", min1p, "max2:", max2p, "min2:", min2p, "max1:", max1p if min1 > max2 or min2 > max1: # potential for collision!! col = False # they are not overlapping, so both values of one projection (a) are larger than both values for the other (b) if (min1 > max2): # min1 will touch max2 on collision a, b = min1, max2 ae, be = e1, e2 elif (min2 > max1): # min2 will touch max1 on collision a, b = min2, max1 ae, be = e2, e1 # multiply the axis' unit vector by the vector magnitudes to find their coordinates maxp, minp = (axis[0] * a, axis[1] * a), (axis[0] * b, axis[1] * b) #print "collision anticipated at step =" # prevent division by zero error. they are not moving or are moving at the same speed #if be.vel[1] - ae.vel[1]: # step = (axis[0] - maxp[1] + minp[1]) / (be.vel[1] - ae.vel[1]) # print "\t", step # if 0 <= step < minstep: # minstep = step #if ae.vel[0] - be.vel[0]: # step = (axis[1] - minp[0] + maxp[0]) / (ae.vel[0] - be.vel[0]) # print "\t", step # if 0 <= step < minstep: # minstep = step # N7NN # ~N77777D. # .D77777777.. # 8777777777$. # ,7$7777777777N. # NONNNND7777778$NNND... # .ONNNN.ND777M8$7777777N.. # NNN===++NIN777777777777M. # N=======N7777777777777777N # .D$N=+===ZN==777===I~$7777777$NNNN. # N$ND=+===+N7777=877N777777777777777N. # .O==++==+D7?=7=+777N7777777777777777. # .$NNNDNN77?=7==77N+===+?N777N777777+ # D7777777777?=77=$7D+++=====NO7777777. # .+777777N7777?=777=I:::====++N7777777D. # .777777N7777777777NNN=====+NN7777777M.. # N777777D777777777N. ..NNNNNNN777777. #.7777777N77777777N. 8N7777ZN777777N. #NZ777777D77777777 .NN777N77777$N #D$NO78NN777777777. .8==N7?+NN77$7DM. #M==N=MDN$777777N N~?N=+N=I=IZ+++?. #+=+N+N+=+N77Z7N. .ON. N+==++NN #.....N=D+==+N ... .D.NN. # .NN+==+N # ...: denom = (axis[0] * (ae.vel[0] - be.vel[0])) + (axis[1] * (ae.vel[1] - be.vel[1])) if denom: # "eggs"-planation: the magnitude of the step factor is the parameter value that brings two objects from different points on the # projection axis to the same point. the sign of the step factor is determined by the object whose projection is largest in # magnitude, as this object is always bound to 'a' and 'ae'. if this object lies below the point of intersection, # the step factor will be positive, as its value needs to increase to reach the point. likewise, if it lies below, # the movement is downwards, and the step factor will be negative. so we take the absolute value of the whole thing if we just # want the step size step = math.fabs((axis[0] * (minp[0] - maxp[0])) + (axis[1] * (minp[1] - maxp[1])) / denom) #print "\t", step if step < minstep: minstep = step if minstep <= 1: # who cares if the collision isn't happening this turn colfuture = True i += 1 j += 1 # if col: # print "axis:", axis # print "\tmin1:", min1, "max2:", max2, "min2:", min2, "max1:", max1 # print "\tmin1:", min1p, "max2:", max2p, "min2:", min2p, "max1:", max1p if col: minstep = 0 return (col, colfuture, minstep)
def _collide(e1, e2): # orthogonally project the polygons onto the normal of each face. if all intersect, # the polygons intersect v = [e1.vertices(), e2.vertices()] col = True # currently colliding colfuture = False # will collide within one step minstep = 999999 # for a collision this frame, 0 <= step <= 1 # cut some corners if both objects are rectangular and axis-aligned aa = False if len(v[0]) == 4 and len(v[1]) == 4 and False: # two boxes. remove the False when code is fixed a = sorted(v[0]) b = sorted(v[1]) for i in [a, b]: if i[0][0] != i[1][0] or a[2][0] != a[3][0]: # should be two unique x values (lists sorted by x val) break elif i[0][1] != i[2][1] or i[1][1] != i[3][1]: # should be two unique y values break else: # axis aligned xs1 = ys1 = xs2 = ys2 = [] for i in a: xs1 += i[0] ys1 += i[1] for i in b: xs2 += i[0] ys2 += i[1] coords = [(xs1, ys1), (xs2, ys2)] overx = False if min(xs1) > max(xs2): maxx, minx = xs1, xs2 maxxe, minxe = e1, e2 elif min(xs2) > max(xs1): maxx, minx = xs2, xs1 maxxe, minxe = e2, e1 else: # they're overlapping on x. what if the shape moves right past? overx = True overy = False if min(ys1) > max(ys2): maxy, miny = ys1, ys2 maxye, minye = e1, e2 elif min(ys2) > max(ys1): maxy, miny = ys2, ys1 maxye, minye = e2, e1 else: # they're overlapping on y overy = True if overx and overy: col = True colfuture = True minstep = 0 aa = True else: #needs work tx = (minxe.pos[0] - maxxe.pos[0]) / (maxxe.vel[0] - minxe.vel[0]) ty = (minye.pos[1] - maxye.pos[1]) / (maxye.vel[1] - maxye.vel[1]) # generic stuff j = 0 while j < 2 and not aa: i = 0 while i < len(v[j]): axis = vectors.normalize((-(v[j][i][1] - v[j][i-1][1]), v[j][i][0] - v[j][i-1][0])) # axis of projection / normal # first poly min1 = max1 = vectors.dot(axis, v[0][0]) # the magnitude of a projection onto a unit vector is just their dot product #min1p = max1p = v[0][0] n = 0 while n < len(v[0]): proj = vectors.dot(axis, v[0][n]) if proj > max1: max1 = proj #max1p = v[0][n] elif proj < min1: min1 = proj #min1p = v[0][n] n += 1 #off = vectors.dot(axis, e1.pos) #min1 += off #max1 += off # second poly min2 = max2 = vectors.dot(axis, v[1][0]) #min2p = max2p = v[1][0] n = 0 while n < len(v[1]): proj = vectors.dot(axis, v[1][n]) if proj > max2: max2 = proj #max2p = v[1][n] elif proj < min2: min2 = proj #min2p = v[1][n] n += 1 #off = vectors.dot(axis, e2.pos) #min2 += off #max2 += off #print "j:", j, "i:", i #print "axis:", axis, "normal of:", v[j][i], "and", v[j][i - 1] #print "\tmin1:", min1, "max2:", max2, "min2:", min2, "max1:", max1 #print "\tmin1:", min1p, "max2:", max2p, "min2:", min2p, "max1:", max1p if min1 > max2 or min2 > max1: # potential for collision!! col = False # they are not overlapping, so both values of one projection (a) are larger than both values for the other (b) if(min1 > max2): # min1 will touch max2 on collision a, b = min1, max2 ae, be = e1, e2 elif(min2 > max1): # min2 will touch max1 on collision a, b = min2, max1 ae, be = e2, e1 # multiply the axis' unit vector by the vector magnitudes to find their coordinates maxp, minp = (axis[0] * a, axis[1] * a), (axis[0] * b, axis[1] * b) #print "collision anticipated at step =" # prevent division by zero error. they are not moving or are moving at the same speed #if be.vel[1] - ae.vel[1]: # step = (axis[0] - maxp[1] + minp[1]) / (be.vel[1] - ae.vel[1]) # print "\t", step # if 0 <= step < minstep: # minstep = step #if ae.vel[0] - be.vel[0]: # step = (axis[1] - minp[0] + maxp[0]) / (ae.vel[0] - be.vel[0]) # print "\t", step # if 0 <= step < minstep: # minstep = step # N7NN # ~N77777D. # .D77777777.. # 8777777777$. # ,7$7777777777N. # NONNNND7777778$NNND... # .ONNNN.ND777M8$7777777N.. # NNN===++NIN777777777777M. # N=======N7777777777777777N # .D$N=+===ZN==777===I~$7777777$NNNN. # N$ND=+===+N7777=877N777777777777777N. # .O==++==+D7?=7=+777N7777777777777777. # .$NNNDNN77?=7==77N+===+?N777N777777+ # D7777777777?=77=$7D+++=====NO7777777. # .+777777N7777?=777=I:::====++N7777777D. # .777777N7777777777NNN=====+NN7777777M.. # N777777D777777777N. ..NNNNNNN777777. #.7777777N77777777N. 8N7777ZN777777N. #NZ777777D77777777 .NN777N77777$N #D$NO78NN777777777. .8==N7?+NN77$7DM. #M==N=MDN$777777N N~?N=+N=I=IZ+++?. #+=+N+N+=+N77Z7N. .ON. N+==++NN #.....N=D+==+N ... .D.NN. # .NN+==+N # ...: denom = (axis[0] * (ae.vel[0] - be.vel[0])) + (axis[1] * (ae.vel[1] - be.vel[1])) if denom: # "eggs"-planation: the magnitude of the step factor is the parameter value that brings two objects from different points on the # projection axis to the same point. the sign of the step factor is determined by the object whose projection is largest in # magnitude, as this object is always bound to 'a' and 'ae'. if this object lies below the point of intersection, # the step factor will be positive, as its value needs to increase to reach the point. likewise, if it lies below, # the movement is downwards, and the step factor will be negative. so we take the absolute value of the whole thing if we just # want the step size step = math.fabs((axis[0] * (minp[0] - maxp[0])) + (axis[1] * (minp[1] - maxp[1])) / denom) #print "\t", step if step < minstep: minstep = step if minstep <= 1: # who cares if the collision isn't happening this turn colfuture = True i += 1 j += 1 # if col: # print "axis:", axis # print "\tmin1:", min1, "max2:", max2, "min2:", min2, "max1:", max1 # print "\tmin1:", min1p, "max2:", max2p, "min2:", min2p, "max1:", max1p if col: minstep = 0 return (col, colfuture, minstep)
def execute(self, obj): pos = V.vector(obj.rect.center) endpos = obj.target.rect.center desired_velocity = obj.maxspeed * V.normalize(endpos - pos) obj.steering = desired_velocity - obj.velocity V.truncate(obj.steering, obj.maxforce)