def sampleBackground(direction): theata = math.atan2(direction.x, direction.z) phi = math.acos(direction.y) a = ((theata / math.pi) + 1) / 2 b = phi / math.pi i = math.floor(a*backgroundWidth) j = math.floor(b*backgroundHeight) pixelPosition = i + j * backgroundWidth backgroundColor = backgroundRows[pixelPosition * backgroundPixelByteWidth:(pixelPosition+1)*backgroundPixelByteWidth] return Vector(backgroundColor[0], backgroundColor[1], backgroundColor[2])
def __init__(self, A, b): assert A.row_num() == len( b), "row number of A must be equal to the length of b" self._m = A.row_num() self._n = A.col_num() assert self._m == self._n # 后面可以省略这个限制 #定义增广矩阵, 添加对b是向量还是矩阵的判断 if isinstance(b, Vector): self.Ab = [ Vector(A.row_vector(i).underlying_list() + [b[i]]) for i in range(self._m) ] if isinstance(b, Matrix): self.Ab = [ Vector( A.row_vector(i).underlying_list() + b.row_vector(i).underlying_list()) for i in range(self._m) ]
def __init__(self, x, y, width, height, color="white", image=None): pygame.sprite.Sprite.__init__(self) self.width = width self.height = height self.color = pygame.Color(color) if image: self.image = pygame.image.load(image) else: self.image = pygame.Surface([width, height]) self.image.fill(self.color) self.position = Vector(x, y) self.velocity = Vector(0, 0) self.acceleration = Vector(0, 0) self.rect = self.get_rect_from_pos()
def Mesh(self, t1, t2, N, n=0): dt = (t2 - t1) / (1.0 * (N - 1)) mesh = Mesh(N) t = t1 for i in range(N): mesh[i] = Vector([t, self.df(t, n)]) t += dt return mesh
def __init__(self): self.up = False self.down = False # Uses booleans to check if alternate key is still down after pressing either left/right key self.right = False self.right_is_up = True self.left = False self.left_is_up = True self.accelerationDownwards = Vector(0, 0.5) self.tickTimer = 0
def test_refraction_2(self): r1 = Ray(origin=Vector(0, 0, 0), ray_dir=Vector(1, 0, 0)) intersection_point = Vector(1, 0, 0) surface_normal = Vector(-1, 1, 0) nFrom = 1 nTo = 1.5 r2 = r1.refract(nFrom, nTo, intersection_point, surface_normal) self.assertEqual(r2.origin.x, intersection_point.x) self.assertEqual(r2.origin.y, intersection_point.y) self.assertEqual(r2.origin.z, intersection_point.z) self.assertAlmostEqual(r2.ray_dir.x, 0.3763991) self.assertAlmostEqual(r2.ray_dir.y, 0.2902675) self.assertAlmostEqual(r2.ray_dir.z, 0)
def __init__(self): """ Should do: 1. define the possible classes 2. define features 3. define CPDs 4. define priors """ self.classes = ["+", "-"] self.features = set() feature_list = open("modules/data/features.txt") for line in feature_list: self.features.add(line.strip().lower()) self.cpds = {"+": Vector(), "-": Vector()} for vector in self.cpds.values(): vector.default = 1 self.priors = {"+": 0.6, "-": 0.4}
def __init__(self, A, b): assert A.row_num() == len( b), 'row number of A must be equal to length of b' self._m = A.row_num() self._n = A.col_num() # 增加了两个判断,如果传入向量,则拓展一位;如果传入一个矩阵,则拓展一个向量(列表)。 if isinstance(b, Vector): self.Ab = [ Vector(A.row_vector(i).underlying_list() + [b[i]]) for i in range(self._m) ] # self.Ab 是一个元素为Vector实例的列表 if isinstance(b, Matrix): self.Ab = [ Vector( A.row_vector(i).underlying_list() + b.row_vector(i).underlying_list()) for i in range(self._m) ] self.pivots = [] # 区分主元列与自由列 / 还能计算出非零行数量
def start(self): for i in range(self.agent_num): self.entities.append( Entity("agent", (random.randint( 0, self.size.getX()), random.randint(0, self.size.getY())), random.uniform(0, 2), random.uniform(0, 360), random.uniform(6, 10), "circle", 1, 1, 0.003)) self.desired.append( Vector((random.uniform(0, self.size.getX()), random.uniform(0, self.size.getY()))))
def __init__(self, *largs): if len(*largs) == 4: super(Plane, self).__init__(*largs) elif (len(*largs) == 3) and ([type(largs[0][i]) for i in range(3)] == [Point, Point, Point]): A = largs[0][0] B = largs[0][1] C = largs[0][2] v0 = Vector([B[i] - A[i] for i in range(3)]) v1 = Vector([C[i] - A[i] for i in range(3)]) v = cross(v0, v1) super(Plane, self).__init__( [v[0], v[1], v[2], -(v[0] * A[0] + v[1] * A[1] + v[2] * A[2])]) elif (len(*largs) == 2) and ([type(largs[0][i]) for i in range(2)] == [Point, Vector]): A = largs[0][0] v = largs[0][1] super(Plane, self).__init__( [v[0], v[1], v[2], -(v[0] * A[0] + v[1] * A[1] + v[2] * A[2])])
def calcFollowTarget(self): # call updateTarget with position calculated from pointer print "calcFollowTarget" if not self.activePointer: return followtarget = self.pointerPosition + Vector((0, -0.2, 0)) # print "follow target: (%.3f,%.3f,%.3f)" % (followtarget[0], followtarget[1],followtarget[2]) self.updateTarget(followtarget) return
def getCameraGrid(self): vectors = [] for i in linspace(0, self.vFov, self.vFov / self.density): for j in linspace(0, self.hFov, self.hFov / self.density): v = Vector(i - self.vFov / 2, j - self.hFov / 2, -self.view_distance) v = v.rotate(self.direction).scale(self.view_distance) vectors.append(v) print('done generating grid') return vectors
def set_basepoint(self): n = self.normal_vector c = self.constant_term basepoint_coords = ['0'] * self.dimension initial_index = Line.first_nonzero_index(n) initial_coefficient = n.coordinates[initial_index] basepoint_coords[initial_index] = c / Decimal(initial_coefficient) self.basepoint = Vector(basepoint_coords)
def __init__(self, normal_vector=None, constant_term=None): self.dimension = 2 if not normal_vector: all_zeros = ['0'] * self.dimension normal_vector = Vector(all_zeros) self.normal_vector = normal_vector if not constant_term: constant_term = Decimal('0') self.constant_term = Decimal(constant_term) self.set_basepoint()
def test_normalization_list_vector(): print(">> test_normalization_list_vector") x = np.ones(10) y = np.ones(10) z = np.ones(10) v = Vector(x, y, z) v.normalization() assert_almost_equal(v.x, 1 / np.sqrt(3) * np.ones(10), 15) assert_almost_equal(v.y, 1 / np.sqrt(3) * np.ones(10), 15) assert_almost_equal(v.z, 1 / np.sqrt(3) * np.ones(10), 15)
def get_code(h): elems = [tuple(i) for i in h] + [tuple(i) for i in h * -1] elems = list(set(elems)) C = Matrix.new(n=len(elems), m = len(h)) for i in range(len(elems)): C[i] = Vector([(1-j)/2 for j in elems[i]]) return C
def tovector(self): ''' Convert lines to vectors :return: set of vectors ''' from Vector import Vector ln = copy.deepcopy(self) v = Vector(ln.p1.X, ln.p1.Y, ln.p1.Z, ln.p2.X - ln.p1.X, ln.p2.Y - ln.p1.Y, ln.p2.Z - ln.p1.Z) return v
def __init__(self, array): self.longRow = len(array) self.longColumn = array[0].long self.rows = array.copy() self.columns = [] for j in range(self.longColumn): temp = [] for i in range(len(array)): temp.append(array[i].numbers[j]) (self.columns).append(Vector(temp))
def getVect(self, point): if self.inCircle(point): velocity = self.repulse * ( self.getCircleRadius() - self.getDistanceFromCenter(point)) / self.bound return Vector(self.getAngleFromCenter(point), velocity) elif self.inBound(point, self.bound): velocity = self.alpha * ( (self.bound + self.getCircleRadius() - self.getDistanceFromCenter(point)) / self.bound) + 10 return Vector(self.getAngleTangentToCenter(point, self.clockwise), self.alpha) elif self.inBound(point, self.bound * 2): velocity = self.attract * ( (self.bound * 2 + self.getCircleRadius() - self.getDistanceFromCenter(point)) / self.bound) return Vector(self.getAngleToCenter(point), velocity) else: return Vector(0, 0)
def handleEvents(self): """ Handle events. """ while self.dataReady("events"): event = self.recv("events") if event.type == pygame.KEYDOWN: if event.key == self.key: activate = True if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1 and self.identifier in event.hitobjects: self.grabbed = event.button self.scaling = Vector(0.9, 0.9, 0.9) if event.type == pygame.MOUSEBUTTONUP: if event.button == 1: self.grabbed = 0 self.scaling = Vector(1, 1, 1) #activate if self.identifier in event.hitobjects: self.send(self.eventMsg, "outbox") self.activated = True
def lens_output_direction(self, beam): gamma = np.arctan(beam.x / self.fx) alpha = np.arctan(-beam.y / self.fz) velocity = Vector(beam.vx, beam.vy, beam.vz) velocity.rotation(gamma, "y") velocity.rotation(alpha, "x") [beam.vx, beam.vy, beam.vz] = [velocity.x, velocity.y, velocity.z]
def mirror_output_direction(self, beam): if self.type == "Surface conical mirror": normal_conic = self.ccc_object.get_normal( np.array([beam.x, beam.y, beam.z])) elif self.type == "My hyperbolic mirror": normal_conic = self.ccc_object.get_normal( np.array([beam.x, beam.y, beam.z])) elif self.type == "Surface conical mirror 2": normal_conic = self.ccc_object.get_normal( np.array([beam.x, beam.y, beam.z])) normal = Vector(normal_conic[0, :], normal_conic[1, :], normal_conic[2, :]) velocity = Vector(beam.vx, beam.vy, beam.vz) vperp = velocity.perpendicular_component(normal) v2 = velocity.sum(vperp) v2 = v2.sum(vperp) [beam.vx, beam.vy, beam.vz] = [v2.x, v2.y, v2.z]
def Step(self, direction, generate=False): global snake, applePos, snakeDir for i in reversed(range(1, len(snake))): self.snake[i] = self.snake[i - 1] self.snakeDir = self.RelativeDir(direction) self.snake[0] += self.snakeDir if self.snake[0] == self.applePos: self.olddist = 99999999 while True: self.applePos = Vector(randrange(0, areaSize.x, 1), randrange(0, areaSize.y, 1)) if not applePos in snake: break self.snake.append(snake[-1]) alive = not self.snake[0] in self.snake[1:] and self.WithinArea( self.snake[0]) left = self.snake[0] + self.RelativeDir( -1) in self.snake or not self.WithinArea(self.RelativeDir(-1)) right = self.snake[0] + self.RelativeDir( 1) in self.snake or not self.WithinArea(self.RelativeDir(1)) forward = self.snake[0] + self.RelativeDir( 0) in self.snake or not self.WithinArea(self.RelativeDir(0)) angle = math.atan2(self.applePos.x - self.snake[0].x, self.applePos.y - self.snake[0].y) - math.atan2( self.snakeDir.x, self.snakeDir.y) angle /= 3.14 if angle > 1: angle -= 2 elif angle < -1: angle += 2 length = Vector(self.applePos.x - self.snake[0].x, self.applePos.y - self.snake[0].y).mag if not alive: self.Death(direction, not generate, not generate) self.oldState = (left, right, forward, angle, length) return alive, left, right, forward, angle, length
def __init__(self, areaSize=Vector(10, 10), cellSize=30): self.snake = [ Vector(areaSize.x // 2, areaSize.y // 2), Vector(areaSize.x // 2, areaSize.y // 2 - 1), Vector(areaSize.x // 2, areaSize.y // 2 - 2), Vector(areaSize.x // 2, areaSize.y // 2 - 3), Vector(areaSize.x // 2, areaSize.y // 2 - 4) ] self.snakeDir = Vector(0, 1) self.applePos = Vector(2, 8) self.areaSize = areaSize self.cellSize = cellSize
def __init__(self, filePath): self.filePath = filePath # Input text file self.bodies = [] # List of celestial bodies self.rawInfo = [] self.dataText = open(self.filePath, "r") # Read in text file to construct system of celestial bodies timeInfo = eval(self.dataText.readline()) # First line specifies number of iterations and the time-step self.numTimeSteps = int(timeInfo[0]) self.dt = timeInfo[1] for line in self.dataText: inputs = line.split(", ") if len(inputs) > 3: self.rawInfo.append((inputs[0], eval(inputs[1]), Vector(eval(inputs[2])))) else: self.rawInfo.append((inputs[0], eval(inputs[1]), Vector([eval(inputs[2]), 0]))) self.bound = 0 # Number to keep track of graph size self.dataText = open(self.filePath, "r") self.dataText.readline() for line in self.dataText: inputs = line.split(", ") # Interpret input name = inputs[0] mass = eval(inputs[1]) initPos = [0, 0] initVel = [0, 0] if len(inputs) > 3: # Input type of: name, mass, initial position, initial velocity initPos = eval(inputs[2]) dist = Vector(initPos).magnitude() initVel = eval(inputs[3]) else: # Input type of: name, mass, orbital radius radius = eval(inputs[2]) initPos = [radius, 0] dist = radius initVel = [0, self.initVelocity(name, self.rawInfo)] # Initial velocity calculated with sqrt( G * mass1 / radius ) based on Mars self.bodies.append(Celestial(name, mass, initPos, initVel)) # Add celestial with input parameters if dist > self.bound: # Setting bound to enlarge graph size self.bound = dist self.initialBodies = self.deepCopyCelests(self.bodies) # Set up a list representing the initial states of the bodies
def __init__(self): super(Entity, self).__init__() # Load the impact and boom sounds if they haven't already been. global impactSound if impactSound == None: impactSound = pygame.mixer.Sound("Content/impact.wav") impactSound.set_volume(0.15) self.impactSound = impactSound global boomSound if boomSound == None: boomSound = pygame.mixer.Sound("Content/boom.wav") boomSound.set_volume(0.15) self.boomSound = boomSound # As a superclass, do not specify a sprite yet. That is the job of subclasses. self.sprite = None # Set a default forward direction (the orientation of the kinematic) self.forward = Vector(1, 0) # Set a default maximum rotation per update. self.maxRotation = 0.1 # Set a default position self.position = Vector(500, 500) # Set a default maximum speed self.maxSpeed = 1 # Don't set an actuator (movement constraint): that is the job of subclasses self.actuator = None # Create a list to hold multiple steering behaviors self.steerings = [] # Set a default health for the entity self.health = 50 # Alive by default self.alive = True
def computeSeparation(self, herd): separation = Vector(0, 0) for sheep in self.neighbors: separation += self.center - sheep.center # if there were no neighbors if (self.neighborCnt == 0): return separation else: return separation.scale(1 / self.neighborCnt)
def computeCohesion(self, herd): cohesion = Vector(0, 0) for sheep in self.neighbors: cohesion += sheep.center if self.neighborCnt > 0: cohesion = cohesion.scale(1 / self.neighborCnt) - self.center # if there were no neighbors return cohesion
def computeAlignment(self, herd): alignment = Vector(0, 0) for sheep in self.neighbors: alignment += sheep.velocity # if there were no neighbors if (self.neighborCnt == 0): return alignment else: return alignment.scale(1 / self.neighborCnt)
def __init__(self, position=Vector(0, 0), velocity=Vector(0, 0), linear=Vector(0, 0), orientation=0, rotation=0, angular=0, maxSpeed=0, maxAccleration=0, offset=0): self.position = position self.velocity = velocity self.linear = linear self.orientation = orientation self.rotation = rotation self.angular = angular self.maxSpeed = maxSpeed self.maxAcceleration = maxAccleration self.offset = offset