def __set_g(self, g): self.__g = array(g) self.gnorm = Physics.norm(g) self.gnormalized = Physics.normalize(g) # angular coordinates (azimuth and colatitude) of the g versor self.gtheta = math.acos(self.gnormalized[2]) self.gphi = Physics.atan2(g[1], g[0])
def electric_field_test_4(): env = [ Physics.Particle([0, 0], float("-3.65E-7"), 0), Physics.Particle([0.218, 0], float("3.65E-7"), 0), ] assert str(Physics.Point( [0.109, 0]).find_electric_field(env)) == "[-552983.7555761299, 0.0]"
def draw(self, screen): #~ pos = Physics.to_pygame(self.body.position) #~ screen.blit(self.image, (pos[0], pos[1]-self.height)) # Draw at bottom left self.v1 = Physics.to_pygame(Vec2d(self.p1[0], self.p1[1])) self.v2 = Physics.to_pygame(Vec2d(self.p2[0], self.p2[1])) pygame.draw.line(screen, self.color, self.v1, self.v2, 20)
def analyzeMRU(mru, pt): n = 0 total = 0 for i, t in enumerate(mru): velocity = physics.averageVelocity(t, x) print("Movimento Uniforme, Experimento", i + 1, "\n======") print("Tempos:", t) print("Velocidade média:", velocity, "m/s") analyticPositions = list( map(lambda time: physics.positionUniform(0, velocity, time), t)) errors = [abs(x - a) for (x, a) in zip(x, analyticPositions)] print("Erros experimentais:", errors) total += velocity n += 1 input("Aperte Enter para exibir o gráfico de s(t)") plot.scatter(t, x, color="green", label="Posição (experimental)") plot.scatter(t, errors, color="red", label="Erro (posição)") plot.plot(t, analyticPositions, label="Posição (modelo)") plot.plot(pt[i][0], pt[i][1], color="cyan", label="Força (acelerômetro)") plot.xlabel('segundos', fontsize=18) plot.ylabel('metros', fontsize=16) plot.legend() plot.show() print("") print("Velocidade média de todos os experimentos:", total / n, "m/s\n\n")
def __init__(self): application = self #global initialization pyxel.init(255, 255, caption="Nearym Quest", scale=3) self.debugOverlay = False self.camera = Camera() self.streamingArea = Box() self.streamingArea.size = Vector2f(512, 512) self.streamingArea.center = Vector2f(0, 0) self.renderer = Renderer() self.physics = Physics() random.seed(0) # Event Manager self.inputManager = InputManager() self.inputManager.addInput( Input(InputType.BUTTON, InputNotify.PRESSED, [pyxel.KEY_F1], 'debug')) # world and player self.LoadMap() self.draw_count = 0 # has to be completely at the end of init pyxel.run(self.update, self.draw)
def electric_field_test_1(): env = [ Physics.Particle([3, 0], float("3.20E-19"), 0), Physics.Particle([-3, 0], float("-3.20E-19"), 0) ] assert list(Physics.Point([0, 3]).find_electric_field(env).vector) == [ -2.2627416997969528e-10, 0.0 ]
def _createCylinder(proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh): """ Private function. Use createCylinder() or createArticulatedCylinder() instead. """ if axis != 0 and axis != 1 and axis != 2: raise ValueError('Axis must be 0 for x, 1 for y or 2 for z.') # Mesh and cdps will be set manually proxy.meshes = None proxy.cdps = None # Compute box moi moi = [0, 0, 0] height = math.fabs(tipPos - basePos) for i in range(3): if i == axis: moi[i] = proxy.mass * radius * radius / 2.0 else: moi[i] = proxy.mass * (3 * radius * radius + height * height) / 12.0 ### HACK! moi[i] = max(moi[i], 0.01) proxy.moi = PyUtils.toVector3d(moi) * moiScale cylinder = proxy.createAndFillObject() basePoint = [0, 0, 0] tipPoint = [0, 0, 0] basePoint[axis] = basePos tipPoint[axis] = tipPos basePoint3d = PyUtils.toPoint3d(basePoint) tipPoint3d = PyUtils.toPoint3d(tipPoint) baseToTipVector3d = Vector3d(basePoint3d, tipPoint3d) if baseToTipVector3d.isZeroVector(): raise ValueError( 'Invalid points for cylinder: base and tip are equal!') baseToTipUnitVector3d = baseToTipVector3d.unit() if height <= radius * 2.0: cdp = Physics.SphereCDP() cdp.setCenter(basePoint3d + baseToTipVector3d * 0.5) cdp.setRadius(height / 2.0) else: cdp = Physics.CapsuleCDP() cdp.setPoint1(basePoint3d + baseToTipUnitVector3d * radius) cdp.setPoint2(tipPoint3d + baseToTipUnitVector3d * -radius) cdp.setRadius(radius) cylinder.addCollisionDetectionPrimitive(cdp) if withMesh: mesh = Mesh.createCylinder(basePoint, tipPoint, radius, colour) cylinder.addMesh(mesh) return cylinder
def electric_field_test_3(): pos = [[-1, 0], [1, 0], [0, 1], [0, 2]] charge_e = [4, 4, 2, -8] charge = [e * float("1.6E-19") for e in charge_e] env = [ Physics.Particle([p[0] * float("4.56E-6"), p[1] * float("4.56E-6")], q, 0) for p, q in zip(pos, charge) ] assert np.linalg.norm( Physics.Point([0, 0]).find_electric_field(env).vector) == 0
def __set_k(self, k): self.__k = array(k) self.knorm=Physics.norm(k) self.knormalized = Physics.normalize(k) # Calculates wavelength and energy of the photon if self.knorm==0.: self.__e, self.__lam=0., '+inf' else: self.__lam=2.*pi/self.knorm self.__e=Booklet.hc/self.__lam
def electric_field_test_2(): env = [ Physics.Particle([0, 0.045], float("7.3E-9"), 0), Physics.Particle([0.045, 0.045], float("-17.5E-9"), 0), Physics.Particle([0.045, 0], float("17.5E-9"), 0), Physics.Particle([0, 0], float("-7.3E-9"), 0), ] assert np.linalg.norm( Physics.Point( [0.0225, 0.0225]).find_electric_field(env).vector) == 128222.02965516063
def deleteAllObjects(self): """Delete all objects: characters, rigid bodies, snapshots, etc.""" if self._followedCharacter is not None: self._followedCharacter = None self._cameraFollowCharacter = False self._cameraObservable.notifyObservers() self._characters = [] self._controllerList.clear() import Physics Physics.world().destroyAllObjects() self.deleteAllSnapshots()
def sigma(self, keV, OFFSET=0., order=1, distribution="gaussian"): """Replacement for Physics.sigma function.""" tB = self.keV2Bragg(keV, order) Q = self.mat_facs[order]*Physics.angular_factor(tB) Dtheta = self.getDelta(tB, OFFSET) if distribution=="hat": weight=Physics.hat(Dtheta, Physics.eta2fwhm(self.eta)) elif distribution=="gaussian": weight=Physics.gaussian(Dtheta, self.eta) else: return 0. return Q*weight/math.cos(tB)
def deleteAllObjects(self): """Delete all objects: characters, rigid bodies, snapshots, etc.""" if self._followedCharacter is not None : self._followedCharacter = None self._cameraFollowCharacter = False self._cameraObservable.notifyObservers() self._characters = [] self._controllerList.clear() import Physics Physics.world().destroyAllObjects() self.deleteAllSnapshots()
def janskyPQ(Jy): """ jansky unit (Jy) as a PhysicalQuantity() class instance @param Jy : quantity expressed in Jy @type Jy : float @return: PhysicalQuantity instance """ return Physics.pq(Jy*1e-26,"W") \ /Physics.pq(1,'m')/Physics.pq(1,'m') \ /Physics.pq(1,'Hz')
def addCharacter(self, character): """Adds a character to the application and the world""" import Physics if PyUtils.sameObjectInList(character, self._characters) : raise KeyError ('Cannot add the same character twice to application.') Physics.world().addArticulatedFigure( character ) self._characters.append( character ) if self._followedCharacter is None : self._followedCharacter = character self._cameraFollowCharacter = True self._cameraObservable.notifyObservers() self._characterObservable.notifyObservers()
def addCharacter(self, character): """Adds a character to the application and the world""" import Physics if PyUtils.sameObjectInList(character, self._characters): raise KeyError( 'Cannot add the same character twice to application.') Physics.world().addArticulatedFigure(character) self._characters.append(character) if self._followedCharacter is None: self._followedCharacter = character self._cameraFollowCharacter = True self._cameraObservable.notifyObservers() self._characterObservable.notifyObservers()
def g_needed(self, order=1): ############################################### local_xtal_g = self.change_the_g(self.xtal.g) #lgn=Physics.normalize(local_xtal_g) local_xtal_gphi = Physics.atan2(local_xtal_g[1], local_xtal_g[0]) ############################################### """Calculates the reciprocal lattice vector that a photon needs to be scattered by a known crystal with planes oriented in a particular direction that is already known""" #When the energy is too low the returned value is None. if self.photon.knorm < self.xtal.gnorm*order: return None # For the calculation see the notes of 09/07/2004 modified the 12/07/04 A = (self.photon.k[0]*math.cos(local_xtal_gphi)+self.photon.k[1]*math.sin(local_xtal_gphi)) B = self.photon.k[2] C = self.xtal.gnorm/2. #A = (self.photon.k[0]*math.cos(self.xtal.gphi)+self.photon.k[1]*math.sin(self.xtal.gphi)) #B = self.photon.k[2] #C = self.xtal.gnorm/2. if abs(A)<=EPSILON: # B can't be 0 together with A unless gnorm=0, so this function should be almost safe # The result can be otained with the calculation in the else block # but this is faster and common (is the case of paraxial photons). if abs(C/B)>1.: return None else: theta=math.acos(-C/B) else: A2B2=A**2+B**2 BC=B*C # Two solutions, but only one satisfies the Laue equation Mean=-BC/A2B2 try: Delta=A*math.sqrt(A2B2-C**2)/A2B2 except ValueError: return None cosp, cosm = Mean+Delta, Mean-Delta thp, thm = math.acos(cosp), math.acos(cosm) sinp, sinm = math.sin(thp), math.sin(thm) checkp = abs(A*sinp + B*cosp + C) checkm = abs(A*sinm + B*cosm + C) # Da ricontrollare if checkp<checkm: theta=thp else: theta=thm return Physics.spherical2cartesian(self.xtal.gnorm, local_xtal_gphi, theta)
def sigma(self, G=False, order=1, distribution="gaussian"): """Interface to the sigma function from Physics.""" tB = self.xtal.keV2Bragg(self.photon.e) ang_fac = Physics.angular_factor(tB) Q = self.xtal.mat_facs[order]*ang_fac if G is None: G=self.g_needed(order) Dtheta = Physics.anglebetween(G, self.xtal.g) if distribution=="hat": weight=Physics.hat(Dtheta, Physics.eta2fwhm(self.xtal.eta)) elif distribution=="gaussian": weight=Physics.gaussian(Dtheta, self.xtal.eta) else: return 0. cosine = abs(self.photon.k[2]/self.photon.knorm) return Q*weight/cosine
def load(self): assert not self._loaded, "Cannot load scenario twice!" self._loaded = True # Create the rigid bodies for the main staircase orientation = PyUtils.angleAxisToQuaternion( (self._angle,(0,1,0)) ) size = MathLib.Vector3d( self._staircaseWidth, self._riserHeight, self._threadDepth ) pos = PyUtils.toPoint3d( self._position ) + MathLib.Vector3d( 0, -self._riserHeight/2.0, 0 ) delta = MathLib.Vector3d(size) delta.x = 0 delta = orientation.rotate( delta ) for i in range(self._stepCount): box = PyUtils.RigidBody.createBox( size, pos = pos + delta * (i+1), locked = True, orientation=orientation ) Physics.world().addRigidBody(box) # Create the rigid bodies for both ramps rampHeights = ( self._leftRampHeight, self._rightRampHeight ) deltaRamp = MathLib.Vector3d(self._staircaseWidth/2.0,0,0) deltaRamp = orientation.rotate( deltaRamp ) deltaRamps = (deltaRamp, deltaRamp * -1) for deltaRamp, rampHeight in zip( deltaRamps, rampHeights ): if rampHeight is None: continue deltaRamp.y = rampHeight/2.0 box = PyUtils.RigidBody.createBox( (0.02,rampHeight,0.02), pos = pos + deltaRamp + delta , locked = True, orientation=orientation ) Physics.world().addRigidBody(box) box = PyUtils.RigidBody.createBox( (0.02,rampHeight,0.02), pos = pos + deltaRamp + (delta * self._stepCount) , locked = True, orientation=orientation ) Physics.world().addRigidBody(box) deltaRamp.y = rampHeight rampOrientation = orientation * PyUtils.angleAxisToQuaternion( (math.atan2(self._riserHeight, self._threadDepth), (-1,0,0)) ) rampLen = self._stepCount * math.sqrt( self._riserHeight*self._riserHeight + self._threadDepth*self._threadDepth ) box = PyUtils.RigidBody.createBox( (0.04,0.02,rampLen), pos = pos + deltaRamp + (delta * ((self._stepCount+1) * 0.5)) , locked = True, orientation=rampOrientation ) Physics.world().addRigidBody(box)
def run_sim(input_file, out_file, time_step, center, iter): system = Parsers() objects = system.parse_geo(input_file) fields = Force_Field() physics_env = Physics() position = fields.init_position(center, objects) with open(out_file, "w") as out_file: out_file.write("Python Molecular Mechanics \n") for i in range(0, iter): potential = fields.bq_potential(objects, position) field = fields.field(potential, position) physics_env.update_accel(field, objects) physics_env.update_velocity(time_step, objects) physics_env.update_position(time_step, objects) position = fields.update_position(objects) #Outputs out_file.write("\n") out_file.write("Iteration: " + str(i) + "\n") for obj in objects: out_file.write(obj.name + " coordinates: " + str(obj.x) + " " + str(obj.y) + "\n")
def __set_g(self, g): self.__g = array(g) self.gnorm = Physics.norm(g) self.gnormalized = Physics.normalize(g) # angular coordinates of the reciprocal lattice vector g # gtheta is the polar angle (the angle between z axis and g vector) # gphi is the azimuthal angle (in the plane xy, from the x axis) self.gtheta = math.acos(self.gnormalized[2]) self.gphi = Physics.atan2(g[1], g[0])
def local_eranges(self, Emin=1., Emax=1000., sphi=0., stheta=pi, deltasource=0): l = math.sqrt(self.photon.r[0]**2 + self.photon.r[1]**2) #stheta = stheta - self.divergence_stheta(l, deltasource) sphi = self.divergence_sphi(self.photon.r) local_xtal_g = self.change_the_g(self.xtal.g) lgn=Physics.normalize(local_xtal_g) local_xtal_gphi = Physics.atan2(local_xtal_g[1], local_xtal_g[0]) local_xtal_gtheta = math.acos(lgn[2]) order, reached_max_order = 0,False factor = 2.5 Darwin_Width = Physics.darwinwidth(self.xtal.Z, self.xtal.hkl, self.photon.e) if self.xtal.structure == "mosaic": Deltatheta = 1.0 * (self.xtal.fwhm/60/180*pi) else: Deltatheta = Darwin_Width + (self.xtal.dim[2] * self.xtal.curvature) / factor Delta_curvature = self.xtal.curvature * self.xtal.dim[0] thetamin, thetamax = local_xtal_gtheta-Deltatheta/2, local_xtal_gtheta+Deltatheta/2 constant=-Booklet.hc/(2.*self.xtal.d_hkl) eranges=[] while not reached_max_order: order+=1 cosdeltaphi=math.cos(sphi-local_xtal_gphi) sinstheta=math.sin(stheta) cosstheta=math.cos(stheta) sinthetamin=math.sin(thetamin) costhetamin=math.cos(thetamin) sinthetamax=math.sin(thetamax) costhetamax=math.cos(thetamax) Eminim_= constant*order/(cosdeltaphi*sinstheta*sinthetamin+cosstheta*costhetamin) Emaxim_= constant*order/(cosdeltaphi*sinstheta*sinthetamax+cosstheta*costhetamax) if Emaxim_ >= Emax: if Eminim_>=Emax: return eranges else: reached_max_order=True Emaxim_=Emax if Eminim_ <= Emin: if Emaxim_ <= Emin: pass else: Eminim_=Emin eranges.append((Eminim_, Emaxim_)) else: eranges.append((Eminim_, Emaxim_)) return eranges
def __init__(self, size, cam, tilePics,itemList,tileCracks,weaponPics,armorPics,over, unit=32, lighting = True,special=True): self.size = size self.unit = unit self.rows = self.size[1] // self.unit self.columns = self.size[0] // self.unit self.cam = cam self.tilePics = tilePics self.startLighting = False self.itemList = itemList self.special = special self.entities = [] self.physics = Physics.physics(self) self.AIOn = True self.tileCracks = tileCracks self.weaponPics = weaponPics self.spawners = [] self.charList = CharacterList.characterList(armorPics) self.over = over self.armorPics = armorPics self.towns = [] self.tileList = TileList.tileList() if lighting == True: self.lighting = Lighting.lighting(self) self.baseLightLevel = 255 else: self.lighting = False self.resetTiles() self.resetMetadata() '''if lighting == True:
def _restore(self, restoreControllerParams=True): """Restores this snapshot, does sets it as active. Should only be called by SnapshotBranch.""" if self._activeIndex >= 0: # Make sure the selected branch is deactivated self._childBranches[self._activeIndex]._deactivate() # Restore the world world = Physics.world() world.setState(self._worldState) # Restore the controllers app = wx.GetApp() assert app.getControllerCount() == len( self._controllers), "Controller list doesn't match snapshot!" for i in range(app.getControllerCount()): controller = app.getController(i) controllerState, wrappedController = self._controllers[i] if restoreControllerParams: controller.beginBatchChanges() try: wrappedController.fillObject(controller) finally: controller.endBatchChanges() controller.setControllerState(controllerState) self.notifyObservers()
def generator(self, Emin=1., Emax=1000., Exp=False, sphi=0., stheta=pi, deltasource=0): '''Generates randomly a photon going onto the xtal. Exp is the powerlaw spectral index -2.1 for Crab ''' # Defines the crystal angles using the angular coordinate of the # reciprocal lattice vector g. The same crystal angles (with -sign) # will be also appplied to the generated photon. l = math.sqrt(self.photon.r[0]**2 + self.photon.r[1]**2) #print "divergenza",self.photon.r[0], self.photon.r[1], l, self.divergence_stheta(l, deltasource) #print "stheta", stheta #stheta = stheta - self.divergence_stheta(l, deltasource) #sphi = self.divergence_sphi(self.photon.r) #print "stheta", stheta # Set the photon intensity equal to 1. This function generate a probability # for the photon, then it will be multplied by the requested intensity set # in the macro if self.photon.i !=1: self.photon.i=1. # wavevector definition from source angular parameters # stheta = pi and sphi = 0 means on-axis source while # off-axis source is simply obtained by changing stheta. # the k value is related to the energy from the relation k = 2 pi/lambda # is the erandom function that make the k from module 1 to the correct module # indeed erandom set the energy and follow that automatically k is set. # Now photon.k has module 1, erandom will give the right normalization. self.photon.k=Physics.makenormalvec(sphi, stheta) # Energy calculation (powerlaw if Exp is False) self.erandom((Emin, Emax), Exp=Exp)
def _createEllipsoid(proxy, radius, colour, moiScale, withMesh): """ Private function. Use createEllipsoid() or createArticulatedEllipsoid() instead. """ # Mesh and cdps will be set manually proxy.meshes = None proxy.cdps = None # Compute box moi moi = [0, 0, 0] for i in range(3): j = (i + 1) % 3 k = (i + 2) % 3 moi[i] = proxy.mass * (radius[j] * radius[j] + radius[k] * radius[k]) / 5.0 proxy.moi = PyUtils.toVector3d(moi) * moiScale ellipsoid = proxy.createAndFillObject() cdp = Physics.SphereCDP() cdp.setCenter(Point3d(0, 0, 0)) cdp.setRadius(min(radius)) ellipsoid.addCollisionDetectionPrimitive(cdp) if withMesh: mesh = Mesh.createEllipsoid((0, 0, 0), radius, colour) ellipsoid.addMesh(mesh) return ellipsoid
def simulateInvSqr(self): '''Uses a while loop to simulate through a trajectory that uses gravity inversely proportional to radius squared. Parameters ----- None Returns ----- t : list The list of times at which the velocities and positions were calculated. f : numpy array An array consisting of a list of velocities and a list of heights in that order. ''' physics = Physics.InverseSquareGravity(self.solver,self.M) while self.stopCondition(self.body.velocity) == False: self.body, self.time = physics.advance(self.body,self.time) self.t.append(self.time) # self.height.append(self.body.height) # self.velocity.append(self.body.velocity) self.bodyList.append(cp.deepcopy(self.body)) return self.t, self.bodyList
def _createBox(proxy, size, colour, moiScale, withMesh): """ Private function. Use createBox() or createArticulatedBox() instead. """ # Mesh and cdps will be set manually proxy.meshes = None proxy.cdps = None # Compute box moi size = PyUtils.toVector3d(size) proxy.moi = MathLib.Vector3d( size.y * size.y + size.z * size.z, size.x * size.x + size.z * size.z, size.x * size.x + size.y * size.y, ) * 1.0 / 12.0 * proxy.mass * moiScale box = proxy.createAndFillObject() cdp = Physics.BoxCDP() halfSize = PyUtils.toVector3d(size) * 0.5 cdp.setPoint1(MathLib.Point3d(halfSize * -1)) cdp.setPoint2(MathLib.Point3d(halfSize)) box.addCollisionDetectionPrimitive(cdp) if withMesh: mesh = Mesh.createBox(size=size, colour=colour) box.addMesh(mesh) return box
def __init__(self, image, x, y, turn, id): pygame.sprite.Sprite.__init__(self) self.location_x = x self.location_y = y self.image = pygame.transform.scale( pygame.image.load(os.path.join("Images", image)), (130, 80)) self.rect = self.image.get_rect() self.turn = turn self.id = id self.tank_pos = 0 self.width = 65 self.power = 50 self.wind = Physics.wind() self.tank_positions1 = [(self.location_x + 27, self.location_y - 2), (self.location_x + 26, self.location_y - 5), (self.location_x + 25, self.location_y - 8), (self.location_x + 23, self.location_y - 12), (self.location_x + 20, self.location_y - 14), (self.location_x + 18, self.location_y - 15), (self.location_x + 15, self.location_y - 17), (self.location_x + 13, self.location_y - 19), (self.location_x + 11, self.location_y - 21)] self.tank_positions2 = [(self.location_x - 27, self.location_y - 2), (self.location_x - 26, self.location_y - 5), (self.location_x - 25, self.location_y - 8), (self.location_x - 23, self.location_y - 12), (self.location_x - 20, self.location_y - 14), (self.location_x - 18, self.location_y - 15), (self.location_x - 15, self.location_y - 17), (self.location_x - 13, self.location_y - 19), (self.location_x - 11, self.location_y - 21)]
def extinction_factor(self, keV, theta_0, order=1): """Wrapper for Physics.extinction_factor function""" if self.microthick==0.: return 1. else: # This part can be speed up by using Xtal facilities!!! return Physics.extinction_factor(keV, self.Z, self.hkls[order], self.microthick, theta_0)
def remove_block(self, position, immediate=True): del self.world[position] self.sectors[Physics.get_sector(position)].remove(position) if immediate: if position in self.shown: self.hide_block(position) self.check_neighbors_loaded(position)
def simulate(self): '''Uses a while loop to simulate through a trajectory. Parameters ----- None Returns ----- t : list The list of times at which the velocities and positions were calculated. f : list A list consisting of snapshots of the GravBody being simulated at every point in the trajectory. ''' physics = Physics.UniformGravity(self.solver,self.a,c=self.c) while self.stopCondition(self.body.position.z) == False: self.body, self.time = physics.advance(self.body,self.time) self.t.append(self.time) # self.height.append(self.body.height) # self.velocity.append(self.body.velocity) self.bodyList.append(cp.deepcopy(self.body)) return self.t, self.bodyList
def ChaseBallBias(s): s.tL, s.tV, s.taV, s.dT = s.ptL, s.ptV, s.ptaV, s.pdT dt = s.bfd / 5300 tPath = PhysicsLib.predictPath(s.ptL, s.ptV, s.ptaV, dt + 1 / 60, 60) tState = tPath.ballstates[min(tPath.numstates - 1, 0)] s.tL = a3(tState.Location) s.tV = a3(tState.Velocity) s.pfL, s.pfV = PhysicsLib.CarStep(s.pfL, s.pfV, dt) s.dT += dt s.fx, s.fy, s.fz = local(s.tL, s.pfL, s.pR) s.fd, s.fa, s.fi = spherical(s.fx, s.fy, s.fz) s.fd2 = dist2d([s.fx, s.fy]) s.fgd2 = dist2d(s.pfL, s.tL) s.tx, s.ty, s.tz = local(s.tL, s.pL, s.pR) s.td, s.ta, s.ti = spherical(s.tx, s.ty, s.tz) s.td2 = dist2d([s.tx, s.ty]) s.r = s.pR[2] / U180 s.tLb = s.tL Cl = Ph.Collision_Model(s.pfL) if s.aerialing and not Cl.hasCollided: n1 = normalize(s.tL - s.pL) v1 = s.pV b1 = v1 - np.dot(v1, n1) * n1 d = s.bd v = max(s.pvd * .5 + .5 * dist3d(s.pfV), 200) t = d / v s.tLb = s.tL - b1 * t s.ax, s.ay, s.az = local(s.tLb, s.pL, s.pR) s.d, s.a, s.i = spherical(s.ax, s.ay, s.az) s.d2 = dist2d([s.ax, s.ay]) s.tLs = s.tL if s.pL[2] > 20 and s.poG and (s.tL[2] < s.az or s.az > 450 + s.pB * 9): s.tLs[2] = 50 s.sx, s.sy, s.sz = local(s.tLs, s.pL, s.pR) s.sd, s.sa, s.si = spherical(s.sx, s.sy + 50, s.sz) s.sd2 = dist2d([s.ax, s.ay]) if not s.offense: s.goal = set_dist(s.tL, s.ogoal, -999) if max(abs(s.fz), abs(s.bz) ) > 130 or s.odT + dist3d(s.otL, s.ofL) / 5300 < s.pdT + 1 or 1: Bias(s, 93) else: aimBias(s, s.goal) s.txv, s.tyv, s.tzv = s.bxv, s.byv, s.bzv s.xv, s.yv, s.zv = s.pxv - s.txv, s.pyv - s.tyv, s.pzv - s.tzv s.vd, s.va, s.vi = spherical(s.xv, s.yv, s.zv) s.vd2 = dist2d([s.xv, s.yv])
def gettB(self, OFFSET=0.): """Calculates Bragg angle for an X-ray source with a certain offset. NOTE: Assumes source azimuthal angle equal to zero!!!""" if OFFSET==0.: return math.pi/2-self.gtheta else: stheta=math.pi*(1.-OFFSET/60./180.) return Physics.anglebetween((math.sin(stheta),0.,math.cos(stheta)), self.gnormalized)-math.pi/2.
def updateForces(self, timestep, maxForce, yaw=0): """ Determines how much force is needed to move the player at the desired speed. If yaw is specified, motion is relative to that angle.""" if not Settings.ApplyPlayerForces: self.moveForce = vec3() return self.moveForce = Physics.DetermineMoveForceForVelocity( self.moveVector, maxForce, self.body, timestep, yaw)
def run_step(self, t, command): if not self.state == State.running: return if Physics.collisionDetection(self.rocket_pos, configs.rocket_size, configs.ground_pos, configs.ground_size): if Physics.checkLanding(self.rocket_velocity, configs.landing_tolerance): self.state = State.landed else: self.state = State.crashed if not Physics.checkInsideBounds(self.rocket_pos, configs.window_size): self.state = State.outOfBounds self.rocket_acceleration = command * 2.0 self.rocket_velocity, self.rocket_pos = \ Physics.calculate_delta(t, self.rocket_velocity, self.rocket_pos, self.rocket_acceleration)
def free_free_absorp_coefPQ(n_e, n_i, T, f): """Returns a physical quantity for the free-free absorption coefficient given the electron density, ion density, kinetic temperature and frequency as physical quantities. From Shklovsky (1960) as quoted by Kraus (1966).""" value = 9.8e-13 * n_e.inBaseUnits().value * n_i.inBaseUnits().value \ * M.pow(T.inBaseUnits().value,-1.5) * M.pow(f.inBaseUnits().value,-2) \ * (19.8 + M.log(M.pow(T.inBaseUnits().value,1.5)/f.inBaseUnits().value)) return P.pq(value, '1/m')
def add_block(self, position, texture, immediate=True): if position in self.world: self.remove_block(position, immediate) self.world[position] = texture self.sectors.setdefault(Physics.get_sector(position), []).append(position) if immediate: if self.is_block_exposed(position): self.show_block(position) self.check_neighbors_loaded(position)
def parse(text, *, friction = 0.2, repulsion = 0.1, spring_length = 0.25, spring_constant = 1, damping = 0.1, radius = 8, attraction = 0.01): bodyNames = set() bodies = list() springs = list() i = 0 # Add all bodies entries = text.split("\n\n") for entry in entries: lines = entry.splitlines() headName = lines[0] if headName not in bodyNames: head = Physics.Body((math.cos(i), math.sin(i)), radius, label=headName) i += 1 bodyNames.add(headName) bodies.append(head) else: head = find_body_by_name(bodies, headName) # Add springs to all dependencies, adding dependency nodes as necessary for line in lines[1:]: tailName = line[1:].lstrip() # Skip past leading dash if tailName not in bodyNames: tail = Physics.Body((math.cos(i), math.sin(i)), radius, label=tailName) i += 1 bodyNames.add(tailName) bodies.append(tail) else: tail = find_body_by_name(bodies, tailName) print(f"Spring between {headName} and {tailName}") springs.append(Physics.Spring((tail, head), spring_length, spring_constant, damping)) # Generate and return the system system = Physics.System(bodies, springs) system.friction_coefficient = friction system.repulsion_coefficient = repulsion system.attraction_coefficient = attraction return system
def main(): display = (800, 600) window = init(display) cube_length = 10 #inicia instancias de Física e esferas physics = Physics(cube_length) list_spheres = create_spheres(physics, 25, 1, 20, 10) timeA = glfw.get_time() print_timer = 0.0 while not glfw.window_should_close(window): timeB = glfw.get_time() dt = timeB - timeA timeA = timeB glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) Cube(cube_length) physics.update() for sphere in list_spheres: sphere.update(dt) for sphere in list_spheres: sphere.rend() #imprime informações sobre conservação print_timer += dt if print_timer > 1.0: kinetic_energy = 0.0 for sphere in list_spheres: kinetic_energy += float(sphere.velocity.norm() ** 2)#assumimos a massa como sendo uma unidade e nao dividimos por 2 para economizar processamento print("Total kinetic energy: {}\n".format(kinetic_energy), end = '\r') print_timer = 0.0 glfw.swap_buffers(window) glfw.poll_events() glfw.swap_interval(1); end(window) quit()
def __init__(self): self.rEarth = vector.Vector(1,0,0) self.vEarth = vector.Vector(0,2*math.pi,0) self.rMars = vector.Vector(1.5,0,0) self.vMars = vector.Vector(0,2*math.pi/math.sqrt(1.5),0) self.max_steps = 10000 self. solver = Solver.RK4(0.01) self.physics = Physics.CentralGravity(self.solver,G=4*math.pi**2,M=1)
def load(self): assert not self._loaded, "Cannot load scenario twice!" self._loaded = True # Create the rigid bodies for the main staircase orientation = PyUtils.angleAxisToQuaternion((self._angle, (0, 1, 0))) size = MathLib.Vector3d(self._staircaseWidth, self._riserHeight, self._threadDepth) pos = PyUtils.toPoint3d(self._position) + MathLib.Vector3d( 0, -self._riserHeight / 2.0, 0) delta = MathLib.Vector3d(size) delta.x = 0 delta = orientation.rotate(delta) for i in range(self._stepCount): box = PyUtils.RigidBody.createBox(size, pos=pos + delta * (i + 1), locked=True, orientation=orientation) Physics.world().addRigidBody(box) # Create the rigid bodies for both ramps rampHeights = (self._leftRampHeight, self._rightRampHeight) deltaRamp = MathLib.Vector3d(self._staircaseWidth / 2.0, 0, 0) deltaRamp = orientation.rotate(deltaRamp) deltaRamps = (deltaRamp, deltaRamp * -1) for deltaRamp, rampHeight in zip(deltaRamps, rampHeights): if rampHeight is None: continue deltaRamp.y = rampHeight / 2.0 box = PyUtils.RigidBody.createBox((0.02, rampHeight, 0.02), pos=pos + deltaRamp + delta, locked=True, orientation=orientation) Physics.world().addRigidBody(box) box = PyUtils.RigidBody.createBox( (0.02, rampHeight, 0.02), pos=pos + deltaRamp + (delta * self._stepCount), locked=True, orientation=orientation) Physics.world().addRigidBody(box) deltaRamp.y = rampHeight rampOrientation = orientation * PyUtils.angleAxisToQuaternion( (math.atan2(self._riserHeight, self._threadDepth), (-1, 0, 0))) rampLen = self._stepCount * math.sqrt( self._riserHeight * self._riserHeight + self._threadDepth * self._threadDepth) box = PyUtils.RigidBody.createBox( (0.04, 0.02, rampLen), pos=pos + deltaRamp + (delta * ((self._stepCount + 1) * 0.5)), locked=True, orientation=rampOrientation) Physics.world().addRigidBody(box)
def __init__(self, window, canvas, timestep=10): Thread.__init__(self) self.canvas = canvas self.daemon = True self.window = window self.core = Physics.PhysicsMotor() self.core.setTimestep(timestep) self.elements = dict() self.dispensers = list() self.running = False
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 error(theta): htarg = 0 r = vector.Vector(0,0,0) v = vector.Vector(r=100,theta=theta,phi=(math.pi/2)) particle = Body.GravBody(5,r,v) solver =Solver.RK4(0.1) physics = Physics.UniformGravity(solver,c=0.1) sim = Simulation.TrajectorySim(stop_maker(htarg),physics,particle) a,b = sim.get_results() y = [p.position.y for p in b] E = particle.position.x - max(y) return E
def is_block_hit(self, position, vector, max_distance=HIT_DISTANCE): m = 8 x, y, z = position dx, dy, dz = vector previous = None for _ in range(max_distance * m): key = Physics.get_block((x, y, z)) if key != previous and key in self.world: return key, previous previous = key x, y, z = x + dx / m, y + dy / m, z + dz / m return None, None
def diffracted_eranges(self, Emin=1., Emax=1000., sphi=0., stheta=pi, deltasource=0): l = math.sqrt(self.photon.r[0]**2 + self.photon.r[1]**2) sphi = self.divergence_sphi(self.photon.r) """Energy ranges that are diffracted by the crystals.""" ################################################################## #local_xtal_g = self.change_the_g(self.xtal.g) #local_xtal_gphi = Physics.atan2(local_xtal_g[1], local_xtal_g[0]) #local_xtal_gtheta = math.acos(local_xtal_g[2]) ################################################################## order, reached_max_order = 0,False factor = 2.5 if self.xtal.structure == "mosaic": Deltatheta = 1.0 * (self.xtal.fwhm/60/180*pi) else: Darwin_Width = Physics.darwinwidth(self.xtal.Z, self.xtal.hkl, self.photon.e) Deltatheta = Darwin_Width + (self.xtal.dim[2] * self.xtal.curvature) / factor Delta_curvature = self.xtal.curvature * self.xtal.dim[0] thetamin, thetamax = self.xtal.gtheta-Deltatheta/2-Delta_curvature/2, self.xtal.gtheta+Deltatheta/2+Delta_curvature/2 constant=-Booklet.hc/(2.*self.xtal.d_hkl) eranges=[] while not reached_max_order: order+=1 cosdeltaphi=math.cos(sphi-self.xtal.gphi) sinstheta=math.sin(stheta) cosstheta=math.cos(stheta) sinthetamin=math.sin(thetamin) costhetamin=math.cos(thetamin) sinthetamax=math.sin(thetamax) costhetamax=math.cos(thetamax) Emin_= constant*order/(cosdeltaphi*sinstheta*sinthetamin+cosstheta*costhetamin) Emax_= constant*order/(cosdeltaphi*sinstheta*sinthetamax+cosstheta*costhetamax) #print "DELTAE", order, Emin_, Emax_, Emax_- Emin_ if Emax_ >= Emax: if Emin_>=Emax: return eranges else: reached_max_order=True Emax_=Emax if Emin_ <= Emin: if Emax_ <= Emin: pass else: Emin_=Emin eranges.append((Emin_, Emax_)) else: eranges.append((Emin_, Emax_)) return eranges
def divergence_sphi(self,r): theta, phi = pi/2-self.xtal.gtheta, self.xtal.gphi rot_in_xtal = lambda x: Physics.rot(x, (('y', -theta), ('z', phi))) drag_in_xtal = lambda x: array(self.xtal.r) - array(x) r=rot_in_xtal(self.photon.r) r=drag_in_xtal(self.photon.r) if self.xtal.source_lens_distance == "inf": return 0.0 else: return math.atan ( r[1] / r[0] )
def sigma(self, G=False, order=1, distribution="gaussian"): local_xtal_g = self.change_the_g(self.xtal.g) #print "g", self.xtal.g, local_xtal_g #lgn=Physics.normalize(local_xtal_g) local_xtal_gphi = Physics.atan2(local_xtal_g[1], local_xtal_g[0]) #local_xtal_gtheta = math.acos(lgn[2]) tB = self.xtal.keV2Bragg(self.photon.e) factor = 2.5 ang_fac = Physics.angular_factor(tB) cosine = abs(self.photon.k[2]/self.photon.knorm) Q = self.xtal.mat_facs[order]*ang_fac if G is None: G=self.g_needed(order) if distribution=="hat": Dtheta = Physics.anglebetween(G, local_xtal_g) # - 2.0 * Physics.anglebetween(self.xtal.g, local_xtal_g) eta = 2.4e-6 + (self.xtal.dim[2] * self.xtal.curvature) / factor weight=Physics.hat1(Dtheta, eta)*cosine/Q elif distribution=="gaussian": Dtheta = Physics.anglebetween(G, local_xtal_g) # - 2.0 * Physics.anglebetween(self.xtal.g, local_xtal_g) weight=Physics.gaussian(Dtheta, self.xtal.eta) else: return 0. return Q*weight/cosine
def generate_position(self): theta, phi = pi/2-self.xtal.gtheta, self.xtal.gphi self.photon.r = self.random_position_on_surface() # lambda functions to: # 1. Convert from the crystal reference frame to the lens reference frame; # 2. Rotate the photon WRT the lens axis till it corresponds to its defined xtal; drag_out_xtal = lambda x: array(x) + array(self.xtal.r) rot_out_xtal = lambda x: Physics.rot(x, (('y', -theta), ('z', -phi))) # Set the photon position in the observer reference frame (rotation + translation) self.photon.r=rot_out_xtal(self.photon.r) self.photon.r=drag_out_xtal(self.photon.r)
def generator(self, Emin=1., Emax=1000., Exp=False, sphi=0., stheta=pi): '''Generates randomly a photon that will go on to xtal. Exp is the powerlaw spectral index (-2.1 for the Crab Nebula). ''' theta, phi = pi/2-self.xtal.gtheta, self.xtal.gphi # lambda functions # drag_out_xtal = lambda x: array(x) + array(self.xtal.r) rot_out_xtal = lambda x: Physics.rot(x, (('y', -theta), ('z', -phi))) # Puts a photon an EPSILON under the xtal surface in a random 2D point random_pos_on_surface=[uniform(-x/2., x/2.) for x in self.xtal.dim[:2]] random_pos_on_surface.append(-EPSILON) self.photon.r=random_pos_on_surface # The photon position in observer reference frame (rotation + translation) self.photon.r=rot_out_xtal(self.photon.r) self.photon.r=drag_out_xtal(self.photon.r) if self.photon.i !=1: self.photon.i=1. # wavevector definition from source angular parameters self.photon.k=Physics.makenormalvec(sphi, stheta) # Energy calculation (powerlaw if Exp is False) self.erandom((Emin, Emax), Exp=Exp)
def simulationStep(self): """Performs a single simulation step""" # TODO Quite hacky if self._kinematicMotion: import KeyframeEditor from MathLib import Trajectory3dv try: pc = self._posableCharacter traj = self._stanceFootToSwingFootTrajectory except AttributeError: pc = self._posableCharacter = KeyframeEditor.PosableCharacter.PosableCharacter(self.getCharacter(0),self.getController(0)) traj = self._stanceFootToSwingFootTrajectory = Trajectory3dv() traj.addKnot(0,Vector3d(-0.13,0,-0.4)) traj.addKnot(0.5,Vector3d(-0.13,0.125,0)) traj.addKnot(1,Vector3d(-0.13,0,0.4)) self._phase = 0 self._stance = Core.LEFT_STANCE stanceToSwing = traj.evaluate_catmull_rom(self._phase) if self._stance == Core.RIGHT_STANCE: stanceToSwing.x = stanceToSwing.x * -1 pc.updatePose( self._phase, stanceToSwing, self._stance, True ) self._phase += 0.00069 if self._phase >= 1.0: self._phase = 0 if self._stance == Core.LEFT_STANCE: self._stance = Core.RIGHT_STANCE else: self._stance = Core.LEFT_STANCE return world = Physics.world() controllers = self._controllerList._objects contactForces = world.getContactForces() for controller in controllers : controller.performPreTasks(self._dt, contactForces) world.advanceInTime(self._dt) contactForces = world.getContactForces() for controller in controllers : if controller.performPostTasks(self._dt, contactForces) : step = Vector3d (controller.getStanceFootPos(), controller.getSwingFootPos()) step = controller.getCharacterFrame().inverseRotate(step); v = controller.getV() phi = controller.getPhase() if self._printStepReport: print "step: %3.5f %3.5f %3.5f. Vel: %3.5f %3.5f %3.5f phi = %f" % ( step.x, step.y, step.z, v.x, v.y, v.z, phi)
def interaction(self): """Interaction between photon and xtal.""" # Lambda function for coordinate transformation theta, phi = pi/2-self.xtal.gtheta, self.xtal.gphi drag_in_xtal = lambda x: x-self.xtal.r drag_out_xtal = lambda x: x+self.xtal.r rot_in_xtal = lambda x: Physics.rot(x, (('z', phi), ('y', theta))) rot_out_xtal = lambda x: Physics.rot(x, (('y', -theta), ('z', -phi))) in_xtal = lambda x: rot_in_xtal(drag_in_xtal(x)) out_xtal= lambda x: drag_out_xtal(rot_out_xtal(x)) # Changing reference frame for photon and xtal self.photon.k=rot_in_xtal(self.photon.k) self.photon.r = in_xtal(self.photon.r) self.xtal.g=rot_in_xtal(self.xtal.g) self.int_history=[] # History init # Photon adventure begins... while self.isinside(): interaction_type=self.which_interaction() self.interact(interaction_type) if interaction_type==0: break # Photoabsorption: the photon dies in to xtal # Photon adventure is over... if interaction_type==0: pass # Dead photon (photo-absorption) elif self.photon.knormalized[2]<=0.: # photon points towards focal plane... (no backscattering) # Back to the original reference frame self.photon.k=rot_out_xtal(self.photon.k) self.photon.r=out_xtal(self.photon.r) # transport the photon to the focal plane self.photon.travelz(0.) else: pass # Photon is backscattered and thus lost # anyway the xtal goes backs to the previous reference frame self.xtal.g=rot_out_xtal(self.xtal.g)
def draw(self): """Draw the content of the world""" world = Physics.world() glEnable(GL_LIGHTING) if self._drawCollisionVolumes: world.drawRBs(Physics.SHOW_MESH|Physics.SHOW_CD_PRIMITIVES) else: world.drawRBs(Physics.SHOW_MESH|Physics.SHOW_COLOURS) # world.drawRBs(Physics.SHOW_MESH|Physics.SHOW_CD_PRIMITIVES) glDisable(GL_LIGHTING); if self._drawShadows: self._glCanvas.beginShadows() world.drawRBs(Physics.SHOW_MESH) self._glCanvas.endShadows()
def which_interaction(self): '''Decide the interaction of the photon that interacts after a path t.''' CSs= self.CSs() # Calculate interaction point and move the photon there mu = sum(CS*self.xtal.rho for CS in CSs) t = Physics.free_path(mu) self.photon.travel(t) # If the photon exits return -1 (No interaction) else evaluate interaction type if not self.isinside(): return -1 else: partial_sums, total_sum = [0.], sum(CSs) # Random variable to discriminate the interaction rnd=uniform(0., total_sum) for i, CS in enumerate(CSs): partial_sums.append(partial_sums[-1]+CS) if rnd < partial_sums[-1]: return i
def divergence_stheta(self, r): source_extension = 0.035 if self.xtal.source_lens_distance == "inf": return 0.0 else: theta, phi = pi/2-self.xtal.gtheta, self.xtal.gphi rot_in_xtal = lambda x: Physics.rot(x, (('y', -theta), ('z', phi))) drag_in_xtal = lambda x: array(self.xtal.r) - array(x) r=rot_in_xtal(self.photon.r) r=drag_in_xtal(self.photon.r) if r[0] <= 0: s = math.sqrt(r[0]**2 + r[1]**2) else: s = -math.sqrt(r[0]**2 + r[1]**2) deltas = uniform (-source_extension/2 , source_extension/2 ) return math.atan(( s + deltas) / self.xtal.source_lens_distance)
def update(self): for object in Entities.ACTIVE_OBJECTS: #Physics.apply_gravity(object) #Collision checks for object_b in Entities.ACTIVE_OBJECTS: if object == object_b: continue if Physics.colliding(object, object_b): Physics.handle_circle_collision(object, object_b) Physics.simulate(object) if object.position.x+object.size < 0 or object.position.x+object.size > self.size_x: object.velocity.x = 0 if object.position.y+object.size < 0 or object.position.y+object.size > self.size_y: object.velocity.y = 0 Physics.move_object(object)
def getDelta(self, tB, OFFSET=0.): """Function to get the angle between the most probable planes and the planes that scatter photons with a certain Bragg angle. Contains the obvious answer for in axis photons and the more complex calculatin when photons are off axis""" if OFFSET==0.: return pi/2-self.gtheta-tB else: ktheta=pi - Physics.arcmin2rad(OFFSET) stk, ctk = math.sin(ktheta), math.cos(ktheta) stB = math.sin(tB) # All starts from a 2nd order equ # A=1. Bhalf=(math.cos(self.gphi)*stk)/(stB-ctk) C=(stB+ctk)/(stB-ctk) Delta = Bhalf**2-C # In case there are non solutions (energy too low, return None) # if Delta<0.: return None sqrtDelta = math.sqrt(Delta) Ts= (-Bhalf - sqrtDelta, -Bhalf + sqrtDelta) Deltas = [abs(2.*math.atan(T) - self.gtheta) for T in Ts] return min(Deltas)
def __init__(self, parentBranch): """Takes a shot of a world, add it to the specified branch.""" super(Snapshot,self).__init__() self._time = time.localtime() # Save the world world = Physics.world() self._worldState = Utils.DynamicArrayDouble() world.getState( self._worldState ) # Save the controllers app = wx.GetApp() self._controllers = [] for i in range(app.getControllerCount()): controller = app.getController(i) controllerState = Core.SimBiControllerState() controller.getControllerState( controllerState ) self._controllers.append( (controllerState, PyUtils.wrapCopy( controller )) ) self._parentBranch = parentBranch self._childBranches = [] self._activeIndex = -1
def _restore(self, restoreControllerParams = True): """Restores this snapshot, does sets it as active. Should only be called by SnapshotBranch.""" if self._activeIndex >= 0 : # Make sure the selected branch is deactivated self._childBranches[self._activeIndex]._deactivate() # Restore the world world = Physics.world() world.setState( self._worldState ) # Restore the controllers app = wx.GetApp() assert app.getControllerCount() == len(self._controllers), "Controller list doesn't match snapshot!" for i in range(app.getControllerCount()): controller = app.getController(i) controllerState, wrappedController = self._controllers[i] if restoreControllerParams : controller.beginBatchChanges() try: wrappedController.fillObject(controller) finally: controller.endBatchChanges() controller.setControllerState( controllerState ) self.notifyObservers()