def innerSystem(self, filename): self.readInfo(filename) sun = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/sun') mercury = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mercury') venus = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/venus') earth = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth') mars = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mars') innerBodies = [sun, mercury, venus, earth, mars] innerSystem = AnimatedSystem(innerBodies, self.delta_t) innerSystem.iterateTimeInterval(self.timeInterval) print("Orbital period [Earth days]: ") #prints the number of earth days in an average orbit print("Mercury: " + str(0.000072722 / innerSystem.averageAngVel(1))) print("Venus: " + str(0.000072722 / innerSystem.averageAngVel(2))) print("Earth: " + str(0.000072722 / innerSystem.averageAngVel(3))) print("Mars: " + str(0.000072722 / innerSystem.averageAngVel(4))) print("") #shows that energy is conserved innerSystem.printInfoTimeInterval( 'experiments/innerSolarSystem/outputData/innerSystemEnergyConservation.dat', 0., self.timeInterval, 1000, [-1], [-1, -2, -3]) innerSystem.animateEveryNth(0., self.timeInterval, self.animateEveryNth, self.animationTimeStep)
def planetAlignment(self, filename): self.readInfo(filename) sun = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/sun') mercury = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mercury') venus = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/venus') earth = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth') mars = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mars') system = AnimatedSystem([sun, mercury, venus, earth, mars], self.delta_t) aligned = system.planetsAligned() numIterToTry = 1000000 i = 0 print("Checking alignment") while i < numIterToTry and not (aligned): sys.stdout.write("\r" + str(100 * i / numIterToTry)[0:3] + "%") system.updateSystemFull() aligned = system.planetsAligned() sys.stdout.flush() i += 1 print("\n") print(str(self.delta_t * i)) system.animateEveryNth(0.98 * self.delta_t * i, self.delta_t * i, self.animateEveryNth, self.animationTimeStep)
def setup(self, reset=0): self.start_state = demake(BLANK_STATE) ## Assiging Objects Start Positions # Agents a1x, a1y = 5, 3 if (not reset): self.agent1 = Body("agent1", "A", [a1x, a1y]) self.start_state[a1x][a1y] = self.agent1.symbol self.agent1.location = [a1x, a1y] a2x, a2y = 7, 8 if (not reset): self.agent2 = Body("agent2", "B", [a2x, a2y]) self.start_state[a2x][a2y] = self.agent2.symbol self.agent2.location = [a2x, a2y] # Non Agents self.start_state[5][8] = "0" self.start_state[10][3] = "*" self.start_state[3][10] = "*" ## self.state = self.start_state
def meteorRisk(self, filename): self.readInfo(filename) sun = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/sun') mercury = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mercury') venus = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/venus') earth = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth') mars = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mars') LeastSepToEarth = [] meteor = Meteor( 'experiments/innerSolarSystem/infoFiles/bodyInfo/meteor') meteorSystem = AnimatedSystem( [sun, mercury, venus, earth, mars, meteor], self.delta_t) meteorSystem.iterateTimeInterval(self.timeInterval) meteorSystem.animateEveryNth(0., self.timeInterval, self.animateEveryNth, self.animationTimeStep) closestDisp, time = meteorSystem.closestApproach([3, 5]) closestDist = np.linalg.norm(closestDisp) print("Closest approach to Earth: " + str(closestDist)) '''
def energyConservationSolarSystem(self, filename): self.readInfo(filename) sun = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/sun') mercury = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mercury') venus = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/venus') earth = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth') mars = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mars') systemOfBodies = [sun, mercury, venus, earth, mars] energyData = [] for i in range(990, 1000): delta_t = i * 1000. system = AnimatedSystem(copy.deepcopy(systemOfBodies), delta_t) system.iterateTimeInterval(self.timeInterval) minEnergy, maxEnergy = system.mimMaxSystemEnergy() energyDataElement = [delta_t, minEnergy, maxEnergy] energyData.append(energyDataElement) fileout = open( 'experiments/innerSolarSystem/outputData/minMaxEnergyData.dat', 'w') for data in energyData: fileout.write( str(data[0]) + "\t" + str(data[1]) + "\t" + str(data[2]) + "\n") fileout.close()
def threeBodies(self): delta_t = 0.01 timeInterval = 5.0 timewarp = 1. fps = 50 bodyA = Body(True, 'experiments/3Bodies/infoFiles/bodyA') bodyB = Body(True, 'experiments/3Bodies/infoFiles/bodyB') bodyC = Body(True, 'experiments/3Bodies/infoFiles/bodyC') threeSystem = AnimatedSystem([bodyA, bodyB, bodyC], delta_t) threeSystem.iterateTimeInterval(timeInterval) #threeSystem.dataDump('experiments/3Bodies/data/3bodyDump.dat') #threeSystem.printInfoTimeInterval('experiments/3Bodies/data/3bodydata.dat', 0., timeInterval, 0.1, [0,1,2], [0,1,8]) threeSystem.animateTimeInterval(0., timeInterval, fps, timewarp)
def walk(tree, parent): for key in tree: if key in System.reservedWords: continue if not self._checkSpec(key, tree[key]): continue dia = self._formatNumber(tree[key]["dia"]) mass = self._formatNumber(tree[key]["mass"]) rad = self._formatNumber(tree[key]["rad"]) if "color" in tree[key]: color = self._evalExpr(tree[key]["color"]) else: color = self._evalExpr("WHITE") if "vel" in tree[key]: vel = [ 0, self._evalExpr(tree[key]["vel"]) + parent.Velocity[1] ] elif parent: vel = [ 0, math.sqrt(G * (parent.Mass**2) / (rad * (mass + parent.Mass))) + parent.Velocity[1] ] else: vel = [0, 0] b = Body(key, parent, dia, mass, vel, rad, color) self._index[key] = b if not parent: self._roots.append(b) walk(tree[key], b)
def calc_exzentri_orbit(self, override_pos=True): body = self.bd s = body.orbit s.calc_kb() dist = (1 + s.exzentritaet) * s.ga # for inkl = 0 # positioning on x-axis with inklination (2D -> 3D) if body.orbit.inklination is not 0: xp = dist * np.sin(np.pi / 2 + body.orbit.inklination) yp = 0 zp = dist * np.cos(body.orbit.inklination) npos = np.array([xp, yp, zp]) else: npos = np.array(s.mother.pos) + np.array([1, 0]) * dist sw = np.array(self.calc_schwerpunkt(s.mother, bbody2=Body(s.bd.mass, npos.tolist(), ''))) a = s.ga b = s.kb t = Symbol('t') term = "" if len(npos.tolist()) is 2: term = sw + np.array([a * cos(t), b * sin(t)]) elif len(npos.tolist()) is 3: c = np.dot((npos - sw), np.array([0, 0, 1])) # z-offset term = sw + np.array([a * cos(t), b * sin(t), c * cos(t)]) # dy = np.array([[np.cos(body.orbit.inklination), 0, np.sin(body.orbit.inklination)], [0, 1, 0], # [-np.sin(body.orbit.inklination), 0, np.cos(body.orbit.inklination)]]) s.track = term if override_pos: body.pos = npos.tolist() body.orbit.sp = sw.tolist() return term
def __init__(self, filename, timestep, maxIterations, probeExists): # Recieves a datafile and generates a list of Body type objects. self.system = [] datafile = open(filename, "r") for line in datafile.readlines(): tokens = line.split(", ") self.system.append( Body(str(tokens[0]), float(tokens[1]), float(tokens[2]), str(tokens[3]), [float(i) for i in tokens[4].split(",")], [float(i) for i in tokens[5].split(",")], [float(i) for i in tokens[6].split(",")])) datafile.close() # Sets some initial parameters for the simulation and constants energy and animation methods. self.elapsedTime = 0.0 self.timestep = timestep self.maxIterations = maxIterations self.probeExists = probeExists self.hasLaunched = False
def simpleOrbit(self): delta_t = 0.001 timeInterval = 5. timewarp = 1. fps = 50 mars = Body(True, 'experiments/simpleOrbit/infoFiles/marsInfo') phobos = Body(True, 'experiments/simpleOrbit/infoFiles/phobosInfo') marsAndMoon = AnimatedSystem([mars, phobos], delta_t) marsAndMoon.iterateTimeInterval(timeInterval) marsAndMoon.printInfoTimeInterval( 'experiments/simpleOrbit/data/test1.dat', 0., timeInterval, 0.01, [1], [0, 1, 8]) marsAndMoon.animateTimeInterval(0., timeInterval, fps, timewarp)
def init_bodies(self): self.body = Body(1., .1, 1., np.array([.0, .0, .0]), np.array([0., 0., 0.]), 10) self.ring_1 = Ring(np.array([0, 0, 10]), 10, 320) self.ring_2 = Ring(np.array([0, 0, -10]), 10, 320) self.E = np.array([0., 0., 0.]) self.F = (0., 0., 0.)
def handle_sim_space_click(self, mouse_pos): # Check if a body was clicked pos = Render.convert_to_renderer(mouse_pos) body_clicked = None # check for a collision with any body for body in self.allBodies: if body.click_point(pos): body_clicked = body break if body_clicked is not None: # If a body is clicked, select/deselect it if body_clicked in self.selected_bodies: self.selected_bodies.remove(body_clicked) else: self.selected_bodies.append(body_clicked) if len(self.selected_bodies) > 0: self.details_bar.selected_objects = self.selected_bodies else: self.details_bar.selected_objects = [] else: # If no body is clicked, either deselect all, or create new body if len(self.selected_bodies) != 0: self.selected_bodies = [] else: o = Body(pos) self.allBodies.append(o) self.selected_bodies.append(o) self.paths_calculated = False self.do_when_selected_bodies_changed() self.details_bar.update(True)
def add_body(self, obj_id, obj_mass, obj_position, obj_velocity): """ Add a Body Object to the list. This method call Body() obtects to creater a new and append to this list. Parameters ---------- obj_id : str Body name obj_mass : float Body mass obj_position : array_like Position in x (float) and y (float). [x, y] obj_velocity : array_like velocity in x (float) and y (float). [V_x, V_y] """ # All dimensions are scaled mass = float(obj_mass)*self.convert_m position = [pos*self.convert_r for pos in obj_position] velocity = [vel*self.convert_v for vel in obj_velocity] new_Body = Body(obj_id,mass,position,velocity) self.bodies.append( new_Body ) self.lookup[obj_id] = new_Body print('*** Body = ',obj_id, obj_mass, obj_position, obj_velocity,' added ***',sep='\t')
def init_bodies(self): Q = 100 self.l_bodies = [] # Body(self, b_id, b_radius, b_mass, b_pos, b_vel, b_charge): # Init controlled body self.controlled_body = Body(0, 0.1, 1., np.array([.0, .0, 0.]), np.array([0., 0., 0.]), Q * 0.01) self.E = np.array([0., 0., 0.]) self.F = (0., 0., 0.) # Init bodies self.body_1 = Body(1, .5, 1., np.array([.0, .0, 5.]), np.array([0., 0., 0.]), -Q) self.body_2 = Body(2, .5, 1., np.array([.0, .0, -5.]), np.array([0., 0., 0.]), Q) self.l_bodies.append(self.body_1) self.l_bodies.append(self.body_2)
def __init__(self): self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(config.window_size) Render.set_surface(pygame.display.get_surface()) self.allBodies = [ Body(name="Star_1", position=(0, 0), mass=500, colour=(255, 255, 186)), Body(name="Star_2", position=(-40, 0), mass=500, velocity=(0, -4.84), colour=(255, 255, 186)), Body(name="Earth", position=(-250, 0), mass=10, velocity=(0, -4.5), colour=(186, 255, 255)), Body(name="Moon", position=(-265, 0), mass=1, velocity=(0, -5.39), colour=(255, 255, 255)) ] self.KeyPressDict = {} self.init_key_press_dict() self.focus_point = None self.focus_bodies = [self.allBodies[0], self.allBodies[1]] self.set_focus_point() self.paths_calculated = False self.isPaused = True self.details_bar = None self.create_details_sidebar() self.is_in_input_mode = False self.selected_bodies = [] self.selected_input_obj = None
def test_constructor1(self): b = Body("A", -2, [3, 2], [1.0, -1.0]) self.assertEqual(b.obj_id, "A") # we have to protect the value of the mass from negative or zero # In this case the mass is negative self.assertEqual(b.obj_mass, -2) self.assertEqual(b.obj_position, [3, 2]) self.assertEqual(b.obj_velocity, [1.0, -1.0])
def __init__(self): self.elements = [ Wheel("front left"), Wheel("front right"), Wheel("back left"), Wheel("back right"), Body(), Engine() ]
def pickle(self, body): from Body import Body if isinstance(body, Body): return body handle = body.identify(self) return Body(handle)
def start(self): self.system.centralBody = Body("Default Central Body", 10, 1) self.syncAndRun() try: self.syncAndRun() except Exception as e: print "Exception detected! Terminating the program..." print e self.shutdown(None, None)
def handleConsoleInput(self, input): input = input.lower() print "Received console-style input from Unity:", input # Creating a new body if input[:3] == "new": try: input = input[input.index("(") + 1:] name = input[:input.index(",")].strip() input = input[input.index(",") + 1:] mass = float(input[:input.index(",")].strip()) input = input[input.index(",") + 1:] rad = float(input[:input.index(",")].strip()) input = input[input.index(",") + 1:] speed = float(input[:input.index(",")].strip()) input = input[input.index(",") + 1:] orbitRad = float(input[:input.index(")")].strip()) except ValueError: print "Error: Incorrect format for adding a new planet!" return b = Body(name, mass, rad) b.setSpeed(speed) b.setOrbitRadius(orbitRad) self.system.addBody(b) # Need to edit an existing body else: bodyName = input[:input.index(".")].strip() fieldToEdit = input[input.index(".") + 1:input.index("=")].strip() newValue = input[input.index("=") + 1:].strip() body = self.system.getBodyWithName(bodyName) if body == False: print "Error: Body with name", bodyName, "is not in the system." if fieldToEdit == "name": body.name = newValue else: try: floatVal = float(newValue) except ValueError: print "Error: Cannot change a numerical field to a non-numerical value.", newValue return if fieldToEdit == "mass": body.mass = floatVal elif fieldToEdit == "radius": body.setBodyRadius(floatVal) elif fieldToEdit == "speed": body.setSpeed(floatVal) elif fieldToEdit == "orbitradius": body.setOrbitRadius(floatVal) else: print "Error: Unrecognized field to edit:", fieldToEdit
def __init__(self): super().__init__() check_license_and_variables_exist() self.body = Body() self.confidence_threshold = 0.5 self.skp_output_path = "skp_output" self.api = Api(default_license_dir()) self.model_path = os.path.join( os.environ["CUBEMOS_SKEL_SDK"], "models", "skeleton-tracking", "fp32", "skeleton-tracking.cubemos" ) self.api.load_model(CM_TargetComputeDevice.CM_CPU, self.model_path)
def __init__(self, topleft, botright): self._root = QuadTree._Node( None, [None]*4, (0, topleft), (botright, 0), Body(0,0,[botright/2,topleft/2],[0,0]) ) self._root._body.live = False self.topleft = topleft self.botright = botright
def mesh(self, body): from Pickler import Pickler pickler = Pickler() body = pickler.pickle(body) import acis properties = self.inventory meshed = acis.mesh(body.handle(), properties) from Body import Body return Body(meshed)
def jsonToSystem(jsonObjs): sysObj = str(jsonObjs[0]) sysLoadStr = sysObj.replace("u'", '"').replace("'", '"').replace("L,", ",") systemDict = json.loads(sysLoadStr) system = GravitySystem() system.G = systemDict["gravityConstant"] system.scale = systemDict["scale"] system.timeScale = systemDict["timeScale"] system.bodyScale = systemDict["bodyScale"] system.centralBodyScale = systemDict["centralBodyScale"] system.elasticity = systemDict["elasticity"] system.systemRadius = systemDict["boundary"] system.handMass = systemDict["handMass"] centralBody = None for i in range(len(jsonObjs) - 1): bodyObj = str(jsonObjs[i + 1]) bodyLoadStr = bodyObj.replace("u'", '"').replace("'", '"').replace("L,", ",") dict = json.loads(bodyLoadStr) body = Body(dict["name"], dict["mass"], dict["radius"]) if (body.name == systemDict["centralBodyName"]): centralBody = body system.centralBody = body centralBody.setScale(system.scale) centralBody.setBodyScale(system.bodyScale * system.centralBodyScale) print "Central body found:", centralBody.name if (centralBody != None): body.centralBody = centralBody else: print body.name, "has no central body" body.setLocation( Vector(dict["locationX"], dict["locationY"], dict["locationZ"]), False) if (body.name != systemDict["centralBodyName"]): body.orbitDirection = Vector(dict["directionX"], dict["directionY"], dict["directionZ"]) body.setSpeed(dict["orbitSpeed"]) body.setOrbitRadius(dict["orbitRadius"]) system.addBody(body) return system
def sateliteToJupiter(self, filename): self.readInfo(filename) sun = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/sun') mercury = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mercury') venus = Body( True, 'experiments/innerSolarSystem/insystem.animateEveryNth(0., self.timeInterval, self.animateEveryNth, self.animationTimeStep)foFiles/bodyInfo/venus' ) earth = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth') mars = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mars') jupiter = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/jupiter') satelite = Satelite( 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth', 'experiments/innerSolarSystem/infoFiles/bodyInfo/jupiterSatelite') systemOfBodies = [sun, mercury, venus, earth, mars, jupiter, satelite] system = AnimatedSystem(systemOfBodies, self.delta_t) system.iterateTimeInterval(self.timeInterval) print(system.averageAngVel(5)) system.animateEveryNth(0., self.timeInterval, self.animateEveryNth, self.animationTimeStep)
def generate_bodies(self): self.bodies_v = [] n = 0 while n < self.n_bodies: pos = [ self.r_pos[0] + self.r_radius * math.cos(n * self.ds), self.r_pos[1] + self.r_radius * math.sin(n * self.ds), self.r_pos[2] ] self.bodies_v.append( Body(n, self.r_bodies, self.d_mass, pos, [0, 0, 0], self.q_bodies)) n += 1
def __init__(self, filename): with open(filename) as univ: # lines = univ.read().split('\n') n = int(next(univ)) self._radius = float(next(univ)) self._bodies = [None] * n for i, line in enumerate(univ): if i >= n: break x, y, vx, vy, m = [ float(x) for x in re.split(r'\s+', line) if x != '' ] self._bodies[i] = Body(Vector([x, y]), Vector([vx, vy]), m)
def read_input_data(self): # TODO: add actual size representations to CSV with open(self.file_name) as csv_file: df = read_csv(csv_file) for row in df.itertuples(): body = Body(*row[1:-1], self) self.body_list.append(body) # TODO: add name to these values self.animation_data[-1].append(body.position) self.patch_list.append( Circle(xy=body.position, radius=10e9, color=row[-1], animated=True))
def __init__(self, battle, stratName): ''' Robots have arms, wheels, and a body by default. Sensors or add-ons can be appended later and are visible for attack ''' self.body = Body() self.wheels = Wheels() self.addOns = [Arm(), Arm()] self.stratName = stratName self.battle = battle p, m = 'robot.' + self.stratName, 'strat' mod = import_module(p) self.strategy = getattr(mod, m) self.id = uuid.uuid4().hex
def sateliteToMars(self, filename): self.readInfo(filename) sun = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/sun') mercury = Body( True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mercury') venus = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/venus') earth = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth') mars = Body(True, 'experiments/innerSolarSystem/infoFiles/bodyInfo/mars') satelite = Satelite( 'experiments/innerSolarSystem/infoFiles/bodyInfo/earth', 'experiments/innerSolarSystem/infoFiles/bodyInfo/marsSatelite') innerBodies = [sun, mercury, venus, earth, mars, satelite] innerSystem = AnimatedSystem(innerBodies, self.delta_t) innerSystem.iterateTimeInterval(self.timeInterval) closestSatMarsDisp, closestAprproachTime = innerSystem.closestApproach( [5, 4]) #innerSystem.printInfoTimeInterval('experiments/innerSolarSystem/outputData/sateliteEnergy.dat', 0., self.timeInterval, 1000., [-1], [-1,-2,-3]) print("Closest approach displacement: " + str(closestSatMarsDisp)) print("Closest approach distance: " + str(np.linalg.norm(closestSatMarsDisp))) print("Closest approach time: " + str(closestAprproachTime)) print("") #innerSystem.printInfoTimeInterval('experiments/innerSolarSystem/data/sateliteInfo.dat', 0, self.timeInterval, self.delta_t, [3,5], [0,1,2]) innerSystem.animateEveryNth(0., self.timeInterval, self.animateEveryNth, self.animationTimeStep)