def generate(): print "simulation with " + str(agentnum.val) + " agents and " + str( buildingnum.val) + " buildings" start = time.clock() Universe.erase() DrawProgressBar(0.0, "Generating buildings ...") randbuilding(buildingnum.val) #genbuilding() DrawProgressBar(1.0, "Finish Generating buildings ...") for i in range(agentnum.val): a = randomagent() DrawProgressBar(i / agentnum.val, "Generating agents ...") while Universe.timeframe < frames.val: Universe.timeframe += 1 Universe.updatebucket() for a in Universe.agent: a.move() a.bmotion.color = a.maingoal.color DrawProgressBar(0.8 + Universe.timeframe / frames.val, "Generating frames ...") draw() stop = time.clock() diff = stop - start print "Time elapsed ", diff print "simulation over"
def generate(): print "simulation with "+str(agentnum.val)+" agents and "+str(buildingnum.val) + " buildings" start = time.clock() Universe.erase() DrawProgressBar(0.0, "Generating buildings ...") randbuilding(buildingnum.val) #genbuilding() DrawProgressBar(1.0, "Finish Generating buildings ...") for i in range(agentnum.val): a = randomagent() DrawProgressBar(i/agentnum.val, "Generating agents ...") while Universe.timeframe<frames.val: Universe.timeframe+=1 Universe.updatebucket() for a in Universe.agent: a.move() a.bmotion.color = a.maingoal.color DrawProgressBar(0.8+Universe.timeframe/frames.val, "Generating frames ...") draw() stop = time.clock() diff = stop-start print "Time elapsed ",diff print "simulation over"
def Down(id: int = 0): """ 每日下载 :param id: 最大递归次数 :return: 下载成功与否 """ try: pivixDownloader.main() t = time.gmtime() h = time.strftime("%H", t) if h[0] == 0: h = eval(h[1]) + 8 if h < 10: h = "0" + str(h) else: h = str(h) getPicList() Universe.set_value("dailyMession", [1]) except: if id < 10: time.sleep(30 + id * 10) id += 1 Down(id) else: Universe.set_value("dailyMession", [-1])
def OnNewUniverse(self, e): if self.mode == "": self.dirname = self.homedir self.filename = "default.emtg_universe" self.universe = Universe.Universe( os.path.join(self.dirname, self.filename)) if self.universe.success == 1: self.mode = "universe" self.fileMenu.Enable(wx.ID_SAVE, True) self.fileMenu.Enable(wx.ID_EDIT, True) self.lblWelcome.Show(False) self.InitializeUniverseOptionsEditor() else: dlg = wx.MessageDialog( self, "Do you really want to create a new universe? This will clear your current GUI settings.", "Confirm New", wx.OK | wx.CANCEL | wx.ICON_QUESTION) result = dlg.ShowModal() dlg.Destroy() if result == wx.ID_OK: #destroy previous options memory block if you have one if self.mode == "options": self.mode = "" self.missionoptions = [] self.optionsnotebook.Destroy() elif self.mode == "mission": self.mode = "" self.mission = [] self.missionpanel.Destroy() elif self.mode == "universe": self.mode = "" self.universe = [] self.universenotebook.Destroy() elif self.mode == "archive": self.mode = "" self.archive = [] self.archivepanel.Destroy() elif self.mode == "NSGAII": self.mode = "" self.NSGAII = [] self.NSGAIIpanel.Destroy() #attempt to open a new universe file self.dirname = self.homedir self.filename = "default.emtg_universe" self.universe = Universe.Universe( os.path.join(self.dirname, self.filename)) if self.universe.success == 1: self.mode = "universe" self.fileMenu.Enable(wx.ID_SAVE, True) self.fileMenu.Enable(wx.ID_EDIT, True) self.lblWelcome.Show(False) self.InitializeUniverseOptionsEditor()
async def eventChecker60(): if Universe.get_value("dailyMession")[0] is 1: sender = Universe.get_value("dailyMession")[1] if type(sender) is Group: await app.sendGroupMessage( sender, MessageChain.create([Plain(f"今日色图更新成功,发送 色图 或者 好图 进行查看")])) elif type(sender) is Friend: await app.sendFriendMessage( sender, MessageChain.create([Plain(f"今日色图更新成功,发送 色图 或者 好图 进行查看")])) elif type(sender) is list: # 只会是自动更新 for ls in sender: await app.sendGroupMessage( ls, MessageChain.create([Plain(f"今日色图更新成功,发送 色图 或者 好图 进行查看")])) await app.sendGroupMessage( ls, MessageChain.create([ Plain("色图一览"), Image.fromLocalFile(Universe.get_value("setuScan")) ])) await app.sendGroupMessage( ls, MessageChain.create([ Plain("好图一览"), Image.fromLocalFile(Universe.get_value("haotuScan")) ])) Universe.set_value("dailyMession", [0, None]) elif Universe.get_value("dailyMession")[0] is -1: sender = Universe.get_value("dailyMession")[1] if type(sender) is Group: await app.sendGroupMessage( sender, MessageChain.create([Plain(f"今日色图更新失败")])) elif type(sender) is Friend: await app.sendFriendMessage( sender, MessageChain.create([Plain(f"今日色图更新失败")])) await app.sendFriendMessage( 775086089, MessageChain.create([Plain(f"今日色图更新失败,请检查网络设置")])) Universe.set_value("dailyMession", [0, None]) global isFresh if not isFresh: if extraEvent.getDate("%H") == "08": isFresh = True await app.sendFriendMessage(775086089, MessageChain.create([Plain(f"开始更新")])) for ls in await app.groupList(): if ls.id in schedulepermission: await app.sendGroupMessage( ls, MessageChain.create([Plain("开始更新每日色图......")])) await app.sendFriendMessage( 775086089, MessageChain.create([Plain(f"群消息发送成功")])) threadDaily = threading.Thread(target=extraEvent.DayilyMission, args=(schedulepermission, 0)) threadDaily.start()
def phiPsi(self, conf=None): "Returns the values of the backbone dihedral angles phi and psi." universe = self.universe() if universe is None: universe = Universe.InfiniteUniverse() C = None for a in self.peptide.N.bondedTo(): if a.parent.parent != self: C = a break if C is None: phi = None else: phi = universe.dihedral(self.peptide.C, self.peptide.C_alpha, self.peptide.N, C, conf) N = None for a in self.peptide.C.bondedTo(): if a.parent.parent != self: N = a break if N is None: psi = None else: psi = universe.dihedral(N, self.peptide.C, self.peptide.C_alpha, self.peptide.N, conf) return phi, psi
def setRigidBodyConstraints(self, universe=None): """ Sets distance constraints that make the object fully rigid. """ if universe is None: universe = self.universe() if universe is None: import Universe universe = Universe.InfiniteUniverse() atoms = self.atomList() if len(atoms) > 1: self.addDistanceConstraint(atoms[0], atoms[1], universe.distance(atoms[0], atoms[1])) if len(atoms) > 2: self.addDistanceConstraint(atoms[0], atoms[2], universe.distance(atoms[0], atoms[2])) self.addDistanceConstraint(atoms[1], atoms[2], universe.distance(atoms[1], atoms[2])) if len(atoms) > 3: for a in atoms[3:]: self.addDistanceConstraint(atoms[0], a, universe.distance(atoms[0], a)) self.addDistanceConstraint(atoms[1], a, universe.distance(atoms[1], a)) self.addDistanceConstraint(atoms[2], a, universe.distance(atoms[2], a))
def savePic(savePicLs, counter, app, sourceid, group, loop): lock = Universe.get_value("SavePicLock") lock.acquire() Universe.set_value("SavePicLock", lock) for ls in savePicLs: print(ls) print(ls.http_to_bytes(ls.url)) direct = "{}/{}/collection".format(pivixDownloader._ROOTDIC, getDate()) if not os.path.exists(direct): os.makedirs(direct) try: response = requests.get(ls.url) img = PILImage.open(BytesIO(response.content)) wid, hght = img.size if wid + hght < 500 and len(savePicLs) < 2: print("表情包") asyncio.run_coroutine_threadsafe( app.sendGroupMessage(group, MessageChain.create([Plain("表情包".format(counter))]), quote=sourceid), loop) lock.release() Universe.set_value("SavePicLock", lock) return 0 img.save(os.path.join(direct, "{}.{}".format(ls.imageId[1:-7], img.format.lower()))) asyncio.run_coroutine_threadsafe( app.sendGroupMessage(group, MessageChain.create([Plain("{}张".format(counter))])), loop) print("saved") except: asyncio.run_coroutine_threadsafe( app.sendGroupMessage(group, MessageChain.create([Plain("{}张保存失败".format(counter))]), quote=sourceid), loop) print("failed") lock.release() Universe.set_value("SavePicLock", lock)
def openfile(l):#a function to import the file and make it into Universe,return a list with universes data=json.loads(open(l).read()) l2=[] for b in data: x=b["universe_name"] y=b['rewards'] z=b['portals'] l2.append(Universe(x,y,z)) return l2
def get_universe(self, filename): w_bodies = self.get_system(filename) uni = [] for body in w_bodies: uni.append(Universe.Bodies.Body( body[0],body[1],body[2],body[3],body[4],body[5],body[6], )) return Universe.Universe( uni )
def getPicList(): """ 获得今日色图的Image列表 :return: none """ global setuList, haotuList date = pivixDownloader.todayDate() rootdir = pivixDownloader._ROOTDIC mode = pivixDownloader._MODE setuList = os.listdir("{}/{}/{}".format(rootdir, date, mode[1])) abspath_setu = os.path.abspath("{}/{}/{}".format(rootdir, date, mode[1])) for i in range(len(setuList)): setuList[i] = os.path.join(abspath_setu, setuList[i]) haotuList = os.listdir("{}/{}/{}".format(rootdir, date, mode[0])) abspath_haotu = os.path.abspath("{}/{}/{}".format(rootdir, date, mode[0])) for i in range(len(haotuList)): haotuList[i] = os.path.join(abspath_haotu, haotuList[i]) Universe.set_value("setuScan", "{}/{}/{}_scan.jpg".format(rootdir, date, mode[1])) Universe.set_value("haotuScan", "{}/{}/{}_scan.jpg".format(rootdir, date, mode[0]))
class Location( object ): universe = Universe.Universe() def __init__( self ): self.coords = None self.reference = None def setLocation( self, coordsIn, refIn = None): """ sets the location of an object takes (x,y,z) tuple and an optional object for reference """ if (coordsIn is None): raise TypeError("coordsIn needs to be a coord type") if (isinstance( coordsIn, (list, tuple) ) ): coordsIn = Coord.Coord(coordsIn) if (not isinstance( coordsIn, Coord.Coord )): raise TypeError("coordsIn needs to be a coord type") if (refIn is None) or (type(refIn) == type( MassObject.MassObject() ) ): self.coords = coordsIn self.reference = refIn if (refIn is not None): self.universe.addObject( refIn ) else: raise TypeError("Invalid reference object given") def getLocation( self, refObj = None ): """ gets the location of an object takes a tuple, a CoordObj, an object for reference, or None Tuple or CoordObj, returns coords based on that coord. Good to calculate a distance from a point None, returns coords based on the original refernce object refObj, returns coords based on the reference Object. """ # use given reference object if refObj is None: return self.coords # use an object as reference elif type(refObj) == type( MassObject.MassObject() ): if (refObj == self.reference): # return same as if given None return self.coords else: #find the coords of the ref object refCoord = refObj.location.getLocation( ) return 0 raise NotImplementedError # use an absolute Coord elif (isinstance( refObj, (list, tuple, Coord.Coord) ) ): # Convert tuple or list to Coord if isinstance( refObj, (list, tuple) ): refObj = Coord.Coord( refObj ) # Will need to compute the obsolute distances.. raise NotImplementedError else: raise TypeError("Invalid reference object given")
class Main(object): universe = None def run(self): self.universe = Universe() self.universe.level_one() self.pygame_main_loop() def pygame_main_loop(self): pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!') while True: # main game loop for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() self.universe.draw(DISPLAYSURF) pygame.display.update()
def main(): starLength = 1024 universe = Universe(starLength) universe.generateStars() universe.printUniverse() print("==========") probe = Probe() # calculating probe distant to stars for i in range(len(universe.StarList)): dist = ((probe._x - universe.StarList[i]._x)**2 + (probe._y - universe.StarList[i]._y)**2 + (probe._z - universe.StarList[i]._z) * 2)**0.5 universe.StarList[i].probeDistant = dist universe.StarList.sort( key=lambda c: c.probeDistant) # to see which star is close to probe counter = 1 x = probe.nextStar(universe.StarList) while (counter != starLength + 1 and x != True): universe.StarList.sort(key=lambda c: c.probeDistant) counter += 1 x = probe.nextStar(universe.StarList) if (counter == 1024 or x == None): print("Could not find a life or there is no life at the universe.") pass
def main(): num = 1025/3 universe = Universe(int(num),int(num),int(num)) universe.generateUniverse() probe = Probe(universe.getStars()) probe.startPoint() probe.path() universe.printData() print() probe.printData()
def createEvent(self): if self.Model in ['kepler', 'integrated']: self.newJourney = JourneyOptions.JourneyOptions() self.newJourney.phase_type = 7 # CoastPhase elif self.Model == 'sundman': self.newJourney = JourneyOptions.JourneyOptions() self.newJourney.phase_type = 8 # SundmanCoastPhase self.newJourney.journey_name = self.originalJourney.missionevents[ 0].Location + 'Launch' self.newJourney.journey_central_body = self.originalJourney.missionevents[ 0].Location self.myUniverse = Universe.Universe( self.UniversePath + '/' + self.newJourney.journey_central_body + '.emtg_universe') #set the left boundary - free point feeding from the previous journey's ephemeris-referenced arrival self.newJourney.departure_class = 3 #periapse self.newJourney.destination_list[ 0] = -1 #really doesn't matter, choose -1 by convention self.newJourney.departure_type = 0 #"launch or impulsive maneuver" self.newJourney.AllowJourneyFreePointDepartureToPropagate = 0 self.newJourney.wait_time_bounds = self.originalJourneyOptions.wait_time_bounds #set the right boundary self.newJourney.arrival_class = 2 #ephemeris-referenced self.newJourney.destination_list[1] = -1 #SOI self.newJourney.arrival_type = 2 #intercept self.newJourney.final_velocity = [1.0e-8, 50.0, 0.0] #lower, upper, null self.newJourney.arrival_ellipsoid_axes = [self.myUniverse.r_SOI] * 3 # set the C3 self.C3 = self.originalJourney.missionevents[0].C3 if self.C3 < 1.0e-07: self.C3 = 1.0e-07 #set the v-infinity self.vMAG = self.C3**0.5 self.computeTOF() #set up the coast phase match point if self.Model == 'sundman': self.newJourney.CoastPhaseMatchPointFraction = 0.5 else: self.newJourney.CoastPhaseMatchPointFraction = 0.1 self.newJourney.CoastPhaseForwardIntegrationStepLength = 60.0 self.newJourney.CoastPhaseBackwardIntegrationStepLength = 600.0
def DayilyMission(group, id: int = 0): lock = Universe.get_value("lock") if not lock.locked(): lock.acquire() Universe.set_value("lock", lock) Universe.set_value("dailyMession", [0, group]) Down() print("每日色图更新完成") lock.release() Universe.set_value("lock", lock) else: print("pass")
def main(): x = 1000 y = 800 try: universe = SaveLoad.load_universe("universe") except: map_size = 5 universe = Universe.Universe() #currently need more things before going over faction size 8 universe.create_map(map_size) universe.create_factions(map_size + 3) #pygame_object = Pygame_Object(1920,1080) pygame_object = Pygame_Object(x,y, universe) error = 0 while (error == 0): pygame_object.game_display.fill(Colour.black) pygame_object.draw_view() pygame_object.draw_ui(universe.factions[universe.turn]) #draw everything, then capture events error = pygame_object.capture_events() #Ui elements selected here if (pygame_object.mouse_down): #mouse button finished clicking button if (pygame_object.ui.ui_element_clicked[0] and pygame_object.current_view == 0): #end turn button clicked universe.turn = (universe.turn + 1) % len(universe.factions) pygame_object.turn_end() pygame_object.clear_ui_elements() pygame_object.turn_start() #update goals for new faction elif (pygame_object.ui.ui_element_clicked[0] and pygame_object.current_view == 1): #return from inner system view pygame_object.current_view = 0 pygame_object.clear_ui_elements() #pygame_object.mouse_released = False # pygame_object.clear_ui_elements() pygame_object.update() SaveLoad.save_universe("universe", universe)
def write(self, object, configuration=None, distance=None): if distance is None: try: distance = object.universe().distanceVector except AttributeError: distance = Universe.InfiniteUniverse().distanceVector if not ChemicalObjects.isChemicalObject(object): for o in object: self.write(o, configuration, distance) else: for bu in object.bondedUnits(): for a in bu.atomList(): self.writeAtom(a, configuration) if hasattr(bu, 'bonds'): for b in bu.bonds: self.writeBond(b, configuration, distance)
def createEvent(self): HighFidelityHalfFlyby.HighFidelityHalfFlyby.createEvent(self) #periapse state is the first periapse of the NEXT journey self.periapseState = self.nextJourney.flyby_periapse_states[0] self.newJourney.journey_name = self.nextJourney.missionevents[0].Location + 'GAi' self.newJourney.journey_central_body = self.nextJourney.missionevents[0].Location self.myUniverse = Universe.Universe(self.UniversePath + '/' + self.newJourney.journey_central_body + '.emtg_universe') #set the left boundary - free point feeding from the previous journey's ephemeris-referenced arrival self.newJourney.departure_class = 1 #free point self.newJourney.destination_list[0] = -1 #doesn't matter, -1 by convention self.newJourney.departure_type = 2 #"free direct departure" self.newJourney.AllowJourneyFreePointDepartureToPropagate = 0 self.newJourney.wait_time_bounds = [0.0, 0.0] #set the right boundary self.newJourney.arrival_class = 3 #periapse self.newJourney.destination_list[1] = -1 #doesn't matter, -1 by convention self.newJourney.arrival_type = 2 #intercept self.newJourney.arrival_elements_type = 0 self.newJourney.arrival_elements_frame = 1#J2000 BCI self.newJourney.arrival_elements = self.periapseState self.newJourney.arrival_elements_reference_epoch = self.nextJourney.missionevents[0].JulianDate #set the v-infinity self.vMAG = self.nextJourney.missionevents[0].C3 ** 0.5 #set the altitude constraint self.newJourney.PeriapseArrival_override_altitude = 1 if self.nextJourneyOptions.override_flyby_altitude_bounds: self.newJourney.PeriapseArrival_altitude_bounds = self.nextJourneyOptions.flyby_altitude_bounds else: self.newJourney.PeriapseArrival_altitude_bounds = [self.myUniverse.minimum_safe_distance - self.myUniverse.central_body_radius, 1.0e+6] self.computeTOF() #set up the coast phase match point if self.Model == 'sundman': self.newJourney.CoastPhaseMatchPointFraction = 0.5 else: self.newJourney.CoastPhaseMatchPointFraction = 0.9 self.newJourney.CoastPhaseForwardIntegrationStepLength = 600.0 self.newJourney.CoastPhaseBackwardIntegrationStepLength = 60.0
def createEvent(self): HighFidelityHalfFlyby.HighFidelityHalfFlyby.createEvent(self) #periapse state is the first periapse of the current journey self.periapseState = self.originalJourney.flyby_periapse_states[0] self.newJourney.journey_name = self.originalJourney.missionevents[ 0].Location + 'GAo' self.newJourney.journey_central_body = self.originalJourney.missionevents[ 0].Location self.myUniverse = Universe.Universe( self.UniversePath + '/' + self.newJourney.journey_central_body + '.emtg_universe') #set the left boundary - free point feeding from the previous journey's ephemeris-referenced arrival self.newJourney.departure_class = 1 #free point self.newJourney.destination_list[ 0] = -1 #really doesn't matter, choose -1 by convention self.newJourney.departure_type = 2 #"free direct departure" self.newJourney.AllowJourneyFreePointDepartureToPropagate = 0 self.newJourney.wait_time_bounds = [0.0, 0.0] #set the right boundary self.newJourney.arrival_class = 2 #ephemeris-referenced self.newJourney.destination_list[1] = -1 #SOI self.newJourney.arrival_type = 2 #intercept self.newJourney.final_velocity = [1.0e-8, 50.0, 0.0] #lower, upper, null self.newJourney.arrival_ellipsoid_axes = [self.myUniverse.r_SOI] * 3 #set the v-infinity self.vMAG = self.originalJourney.missionevents[0].C3**0.5 self.computeTOF() #set up the coast phase match point if self.Model == 'sundman': self.newJourney.CoastPhaseMatchPointFraction = 0.5 else: self.newJourney.CoastPhaseMatchPointFraction = 0.1 self.newJourney.CoastPhaseForwardIntegrationStepLength = 60.0 self.newJourney.CoastPhaseBackwardIntegrationStepLength = 600.0
def _computeImportanceWeights(self, Measurement, tStep): for iParticle in range(0, self.nParticles): Wtrial = self.We[:, :, iParticle] testVerse = Universe() testVerse.initFromMatrix(Wtrial) t = np.arange(tStep + 1) testVerse.simulateUniverse(t) self.log.debug('Measurement') self.log.debug(Measurement.Mhat[tStep]) self.log.debug('test val') self.log.debug(testVerse.M[Measurement.node, tStep]) iw = norm.pdf(Measurement.Mhat[tStep], testVerse.M[Measurement.node, tStep], Measurement.vv) self.importanceWeights[iParticle] = iw
def viewConfigurationVMD(object, configuration = None, format = 'pdb', label = None): format = format.lower() if format != 'pdb': return genericViewConfiguration(object, configuration, format) tempfile.tempdir = tempdir filename = tempfile.mktemp() filename_tcl = filename.replace('\\', '\\\\') script = tempfile.mktemp() script_tcl = script.replace('\\', '\\\\') tempfile.tempdir = None object.writeToFile(filename, configuration, format) file = open(script, 'w') file.write('mol load pdb ' + filename_tcl + '\n') if isCalpha(object): file.write('mol modstyle 0 all trace\n') file.write('color Name 1 white\n') file.write('color Name 2 white\n') file.write('color Name 3 white\n') if Universe.isUniverse(object): # add a box around periodic universes basis = object.basisVectors() if basis is not None: v1, v2, v3 = basis p = -0.5*(v1+v2+v3) for p1, p2 in [(p, p+v1), (p, p+v2), (p+v1, p+v1+v2), (p+v2, p+v1+v2), (p, p+v3), (p+v1, p+v1+v3), (p+v2, p+v2+v3), (p+v1+v2, p+v1+v2+v3), (p+v3, p+v1+v3), (p+v3, p+v2+v3), (p+v1+v3, p+v1+v2+v3), (p+v2+v3, p+v1+v2+v3)]: file.write('graphics 0 line {%f %f %f} {%f %f %f}\n' % (tuple(p1/Units.Ang) + tuple(p2/Units.Ang))) file.write('file delete ' + filename_tcl + '\n') if sys.platform != 'win32': # Under Windows, it seems to be impossible to delete # the script file while it is still in use. For the moment # we just don't delete it at all. file.write('file delete ' + script_tcl + '\n') file.close() subprocess.Popen([viewer['pdb'][1], '-nt', '-e', script])
def phiPsi(self, conf=None): """Returns a list of the (phi, psi) backbone angle pairs for each residue.""" universe = self.universe() if universe is None: universe = Universe.InfiniteUniverse() angles = [] for i in range(len(self)): r = self[i] if i == 0: phi = None else: phi = universe.dihedral(r.peptide.C, r.peptide.C_alpha, r.peptide.N, self[i - 1].peptide.C, conf) if i == len(self) - 1: psi = None else: psi = universe.dihedral(self[i + 1].peptide.N, r.peptide.C, r.peptide.C_alpha, r.peptide.N, conf) angles.append((phi, psi)) return angles
def _computeParamPdf(self, i, j, Measurement): thetaVals = self.thetas[(i, j)] prior = np.ones((self.nSteps, 1)) posterior_t = np.zeros((Measurement.nTimeSteps - 1, self.nSteps)) for iParamStep in range(0, self.nSteps): Wtrial = self.We Wtrial[i, j] = thetaVals[iParamStep] testVerse = Universe() testVerse.initFromMatrix(Wtrial) t = np.arange(Measurement.nTimeSteps) testVerse.simulateUniverse(t) posterior_t[0, iParamStep] = prior[iParamStep] * norm.pdf( Measurement.Mhat[1], testVerse.M[Measurement.node, 1], Measurement.vv) for tStep in range(1, Measurement.nTimeSteps - 1): posterior_t[tStep, iParamStep] = posterior_t[ tStep - 1, iParamStep] * norm.pdf( Measurement.Mhat[tStep + 1], testVerse.M[Measurement.node, tStep + 1], Measurement.vv) # We've learned nothing if the first posterior is beneath tolerance tol = 1e-1 if (np.sum(posterior_t[0, :]) < tol): posterior_t[-1, :] = prior.ravel() for tStep in range(0, Measurement.nTimeSteps - 1): if (np.sum(posterior_t[tStep, :]) / float(self.nSteps)) != 0: posterior_t[tStep, :] = posterior_t[tStep, :] / ( np.sum(posterior_t[tStep, :]) / float(self.nSteps)) else: posterior_t[tStep, :] = posterior_t[tStep - 1, :] #self.log.info('-1-Pdf for w_02') #self.log.info(posterior_t[-1,:]) self.paramPdfs[(i, j)] = posterior_t[-1, :]
rep=False p = vector(uniform(lmin,lmax),0,uniform(wmin,wmax)) for o in positions: if mag(o-p)<5: rep=True if not rep: positions.append(p) break n = randint(0,len(Universe.intentions)-1) nat = Universe.intentions[n] building(pos=p,size=[uniform(ll,lu),uniform(hl,hu),uniform(wl,wu)],nature=nat) if __name__ == '__main__': number =int(sys.argv[1]) buildnum = int(sys.argv[2]) print "crowd simulation with crowd density "+str(number)+" agents, "+str(buildnum)+" buildings" Universe.erase() randbuilding(buildnum) for i in range(number): randomagent() while Universe.timeframe<Universe.numberofframes: Universe.timeframe+=1 Universe.updatebucket() for a in Universe.agent: a.move() print "simulation over"
def CreateInitialGuess(self): #Step 1: construct the old initial guess DecisionVector = [] for Xindex in range(0, len(self.originalMission.DecisionVector)): DecisionVector.append([ self.originalMission.Xdescriptions[Xindex].replace( '\n', '').replace('\r', ''), self.originalMission.DecisionVector[Xindex] ]) controlDV = [] #Step 2: first convert all mentions of the original transcription to PSFB newDecisionVector = [] for entry in DecisionVector: line = copy.deepcopy(entry) line = [ line[0].replace(self.OriginalTranscription[0], 'PSFB'), line[1] ] journeyIndex = int(line[0][1:line[0].find('p')]) stepIndex = [] if 'u_' in line[0]: stepIndex = int( line[0][line[0].find('step'):line[0].find('u')].strip( 'step ')) line[0] = line[0].replace( 'PSFB: step ' + str(stepIndex), 'PSFB_Step' + str(stepIndex) + ': substep0') controlDV.append(line) else: newDecisionVector.append(line) #find the missionevent offset originalJourney = self.originalMission.Journeys[journeyIndex] originalJourneyOptions = self.originalOptions.Journeys[ journeyIndex] eventStartIndex = [] eventMatchPointIndex = [] for event in originalJourney.missionevents: if event.EventType in [ 'coast', 'Scoast', 'SFthrust', 'FBLTthrust', 'SSFthrust', 'FBLTSthrust' ]: eventStartIndex = event.EventNumber break for event in originalJourney.missionevents: if event.EventType in ['match_point']: eventMatchPointIndex = event.EventNumber break originalUniverse = Universe.Universe( self.originalOptions.universe_folder + '/' + originalJourneyOptions.journey_central_body + '.emtg_universe') delta0 = float(originalUniverse.reference_angles[2]) * pi / 180.0 alpha0 = float(originalUniverse.reference_angles[0]) * pi / 180.0 Rx = numpy.matrix( [[1.0, 0.0, 0.0], [0.0, cos(pi / 2.0 - delta0), -sin(pi / 2 - delta0)], [0.0, sin(pi / 2.0 - delta0), cos(pi / 2 - delta0)]]) Rz = numpy.matrix( [[cos(pi / 2 + alpha0), -sin(pi / 2 + alpha0), 0.0], [sin(pi / 2 + alpha0), cos(pi / 2 + alpha0), 0.0], [0.0, 0.0, 1.0]]) R = Rz * Rx #insert step states after u_z if 'Step' in line[0] and 'u_z' in line[0]: eventIndex = eventStartIndex + stepIndex if eventIndex >= eventMatchPointIndex: eventIndex += 1 event = [] for oldEvent in originalJourney.missionevents: if oldEvent.EventNumber == eventIndex: event = copy.deepcopy(oldEvent) break #create the initial guess (note: rotation may be needed later...) position = numpy.matrix([ event.SpacecraftState[0], event.SpacecraftState[1], event.SpacecraftState[2] ]).T velocity = numpy.matrix([ event.SpacecraftState[3], event.SpacecraftState[4], event.SpacecraftState[5] ]).T Rposition = R * position Rvelocity = R * velocity x = float(Rposition[0]) y = float(Rposition[1]) z = float(Rposition[2]) xdot = float(Rvelocity[0]) ydot = float(Rvelocity[1]) zdot = float(Rvelocity[2]) r = (x**2 + y**2 + z**2)**0.5 v = (xdot**2 + ydot**2 + zdot**2)**0.5 RA = atan2(y, x) DEC = asin(z / r) FPA = acos((x * xdot + y * ydot + z * zdot) / r / v) #azimuth is complicated xhat = numpy.matrix( [cos(RA) * cos(DEC), sin(RA) * cos(DEC), sin(DEC)]).T yhat = numpy.matrix( [cos(RA + pi / 2.0), sin(RA + pi / 2.0), 0.0]).T zhat = numpy.matrix( [-cos(RA) * sin(DEC), -sin(RA) * sin(DEC), cos(DEC)]).T R = numpy.hstack([xhat, yhat, zhat]).T V = numpy.matrix([xdot, ydot, zdot]).T Vprime = R * V AZ = atan2(Vprime[1], Vprime[2]) #vRA and vDEC vRA = atan2(ydot, xdot) vDEC = asin(zdot / v) prefix = 'j' + str(journeyIndex) + 'p0PSFB_Step' + str( stepIndex) + ': ' newDecisionVector.append([prefix + 'left state r', r]) newDecisionVector.append([prefix + 'left state RA', RA]) newDecisionVector.append([prefix + 'left state DEC', DEC]) newDecisionVector.append([prefix + 'left state v', v]) if self.originalOptions.ParallelShootingStateRepresentation == 2: #spherical AZFPA newDecisionVector.append([prefix + 'left state AZ', AZ]) newDecisionVector.append([prefix + 'left state FPA', FPA]) else: #spherical RADEC newDecisionVector.append([prefix + 'left state vRA', vRA]) newDecisionVector.append( [prefix + 'left state vDEC', vDEC]) newDecisionVector.append( [prefix + 'left state mass', event.Mass]) newDecisionVector.append( [prefix + 'virtual chemical fuel', 0.0]) newDecisionVector.append( [prefix + 'virtual electric propellant', 0.0]) newDecisionVector += controlDV controlDV = [] return newDecisionVector
class SatModel(AbstractObjectModel.AbstractObjectModel): """Models the satellite. """ force_model = Universe.Gravity() def __init__(self, time_init, mass_prop, pos_init, vel_init, att_init, ang_vel_init): """ :param dt. datetime time_init: :param mass_prop: :param vt.Vector pos_init: :param vt.Vector vel_init: :param vt.Vector att_init: :param vt.Vector ang_vel_init: :return: """ self.time = time_init self.mass = mass_prop['mass'] self.cog = mass_prop['cog'] self.moi = mass_prop['moi'] self.att = Attitude(att_init) self.w = ang_vel_init self.p = pos_init self.v = vel_init self._ode_orbit = dop853.Dop853(SatModel.__orbit_force_model, [self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z], self.time, params=time_init) def update(self, time): delta_time = time - self.time self.att.update(delta_time, self.w) self.__update_orbit(time) self.time = time def __str__(self): time_str = 'Time: %s' % self.time.ctime() att_str = 'Att: %s' % self.att angv_str = 'AngV: %s' % self.w orbit_str = 'Orbit: %s, %s' % (self.p, self.v) return ' '.join([time_str, att_str, angv_str, orbit_str]) def __update_orbit(self, time): self.p, self.v = self._ode_orbit.step(time) @staticmethod def __orbit_force_model(t, y, time_init): x, y, z, v_x, v_y, v_z = y x_dot, y_dot, z_dot = v_x, v_y, v_z v_dot = SatModel.force_model.force(vector_types.Vector(x, y, z), time_init + dt.timedelta(seconds=t)) return [x_dot, y_dot, z_dot, v_dot.x, v_dot.y, v_dot.z] @classmethod def import_sat(cls, filename): single_items = ["name", "shape", "dry_mass", "fuel_mass", "drag_coeff", "rad_coeff"] vector_items = ["length", "cog", "cop", "drag_area", "solar_area", "rad_area"] matrix_items = ["moi"] params = {} try: tree = et.parse(filename) except IOError: print("Unable to open satellite file.") return except et.ParseError: print("Invalid XML file.") return root = tree.getroot() # Single items are defined in text for item in single_items: value = root.find(item).text try: params[item] = float(value) except ValueError: params[item] = value # Vector items are defined in attributes x, y, and z attributes = ['x', 'y', 'z'] for item in vector_items: node = root.find(item) value = [float(node.attrib.get(a, 0)) for a in attributes] params[item] = vector_types.Vector(value) # Matrix items are defined in attributes xx, xy, xz, yx, yy, yz, zx, zy, zz attributes = ['xx', 'xy', 'xz', 'yx', 'yy', 'yz', 'zx', 'zy', 'zz'] for item in matrix_items: node = root.find(item) value = [float(node.attrib.get(a, 0)) for a in attributes] params[item] = vector_types.Matrix(value) return SatModel(params)
def updatestates(self): for i in range(len(self.state)): self.state[i] = Universe.updatestate(i, self.state[i])
The simulation ends either at 100 steps or when there is no individual left moving ''' import json from Universe import * from Person import * import math infile = input('Input file => ').strip() print(infile) u = json.loads(open(infile).read()) universes = [] for c in u: d = list(c.keys()) universes.append(Universe(c[d[0]], c[d[1]], c[d[2]], c[d[3]])) people = [] for uni in universes: for p in uni.individuals: people.append(Person(p[0], p[1], p[2], p[3], p[4], p[5], uni.name)) print('All universes') print('-' * 40) for u in universes: print(u) print('All individuals') print('-' * 40) for p in people: print(p) print()
start_date = "2005-01-01" end_date = "2017-01-01" company_list = "companylist.csv" growth_save = "data/GrowthData.pkl" companies = pd.read_csv(company_list)['Symbol'].tolist() try: data = pickle.load(open(growth_save, "rb")) except FileNotFoundError: features = [ uv.DataTypes.month_growth, uv.DataTypes.week_growth, uv.DataTypes.day_growth ] data = uv.Universe([], start_date, end_date, features=features) pickle.dump(data, open(growth_save, 'wb')) finally: end_collect = -1 for i in range(len(companies)): if companies[i] in data: end_collect = i i = 0 data_modified = False for symbol in companies[end_collect + 1:]: try: print("collecting: " + symbol) data.add_stock(symbol) data_Modified = True except:
newOptions.mission_name = missionFile.replace('.emtg', '') + '_HighFidelity' newOptions.DisassembleMasterConstraintVectors() newOptions.DisassembleMasterDecisionVector() # create a universe object for each central body in the new options central_body_names = [] universe_list = [] for JourneyIndex in range(0, len(newOptions.Journeys)): central_body_name = newOptions.Journeys[ JourneyIndex].journey_central_body if central_body_name not in central_body_names: central_body_names.append(central_body_name) universe_file = central_body_name + ".emtg_universe" universe = Universe.Universe( os.path.join(newOptions.universe_folder, universe_file)) universe.filename = central_body_name universe_list.append(universe) # add all of the bodies in each Journey's central body universe file as perturbers for JourneyIndex in range(0, len(newOptions.Journeys)): central_body_name = newOptions.Journeys[ JourneyIndex].journey_central_body for universe in universe_list: if universe.central_body_name == central_body_name or universe.filename == central_body_name: newOptions.Journeys[ JourneyIndex].perturbation_bodies = [] for bodyIndex in universe.perturbation_indices: if universe.bodies[bodyIndex].mu > 100.0: newOptions.Journeys[
def convert_launch(myJourneyOptions, mu=1.0): import StateConverter #step 1: convert all instances of "PeriapseLaunchOrImpulsiveDeparture" to "PeriapseLaunch" Xindex = 0 has_launch = False X = myJourneyOptions.trialX while Xindex < len(X): if 'PeriapseLaunchOrImpulsiveDeparture' in X[Xindex][0]: X[Xindex][0] = X[Xindex][0].replace('PeriapseLaunchOrImpulsiveDeparture', 'PeriapseLaunch') has_launch = True Xindex += 1 if has_launch: #step 2: step through the decision vector, looking for the spherical state entries and renaming as we go stateSpherical = [0.0]*6 stateSphericalType = 'have not decided yet' Xindices_6state = [] Xindex = 0 while Xindex < len(X): description = X[Xindex][0] value = X[Xindex][1] if 'PeriapseLaunch' in description: if 'event left state r ' in description: stateSpherical[0] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state r ', 'event left state VINFout') elif 'event left state RA' in description: stateSpherical[1] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state RA', 'event left state RHAout') elif 'event left state DEC' in description: stateSpherical[2] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state DEC', 'event left state DHAout') elif 'event left state v ' in description: stateSpherical[3] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state v ', 'event left state BRADIUSout') elif 'event left state vRA' in description: stateSphericalType = 'SphericalRADEC' stateSpherical[4] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state vRA', 'event left state BTHETAout') elif 'event left state vDEC' in description: stateSpherical[5] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state vDEC', 'event left state TAout') elif 'event left state AZ' in description: stateSphericalType = 'SphericalAZFPA' stateSpherical[4] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state AZ', 'event left state BTHETAout') elif 'event left state FPA' in description: stateSpherical[5] = float(value) Xindices_6state.append(Xindex) X[Xindex][0] = X[Xindex][0].replace('event left state FPA', 'event left state TAout') elif 'magnitude of periapse maneuver' in description: stateSpherical[3] += float(value) Xindex += 1 #step 3: convert to outgoingBplane stateOutgoingBplane = [] myStateConverter = StateConverter.StateConverter() if stateSphericalType == 'SphericalRADEC': stateOutgoingBplane = myStateConverter.SphericalRADECtoOutgoingBplane(stateSpherical, mu) else: stateOutgoingBplane = myStateConverter.SphericalAZFPAtoOutgoingBplane(stateSpherical, mu) #step 4: put the new entries in the decision vector for stateIndex in range(0, 6): X[Xindices_6state[stateIndex]][1] = stateOutgoingBplane[stateIndex] #step 5: convert the upper and lower bounds on the journey initial velocity bounds from copy import deepcopy oldBounds = deepcopy(myJourneyOptions.initial_impulse_bounds) r_planet = 6378.1363 try: import Universe myUniverse = Universe.Universe(myJourneyOptions.universe_folder + "/" + myJourneyOptions.journey_central_body + ".emtg_universe") r_planet = myUniverse.central_body_radius except: print("Failed to find " + myJourneyOptions.universe_folder + "/" + myJourneyOptions.journey_central_body + ".emtg_universe" + " Cannot find appropriate mu for decision vector conversion. Using 1.0. Good luck.") periapse_altitude_min = r_planet + myJourneyOptions.PeriapseDeparture_altitude_bounds[0] periapse_altitude_max = r_planet + myJourneyOptions.PeriapseDeparture_altitude_bounds[1] parking_velocity_min_altitude = (mu / periapse_altitude_min) ** 0.5 parking_velocity_max_altitude = (mu / periapse_altitude_max) ** 0.5 if (oldBounds[0] + parking_velocity_min_altitude)**2 - 2*mu/periapse_altitude_min > 1.0e-8: myJourneyOptions.initial_impulse_bounds[0] = ((oldBounds[0] + parking_velocity_min_altitude)**2 - 2*mu/periapse_altitude_min) ** 0.5 else: myJourneyOptions.initial_impulse_bounds[0] = 1.0e-8 if (oldBounds[1] + parking_velocity_max_altitude)**2 - 2*mu/periapse_altitude_max > 1.0e-8: myJourneyOptions.initial_impulse_bounds[1] = ((oldBounds[1] + parking_velocity_max_altitude)**2 - 2*mu/periapse_altitude_max) ** 0.5 else: myJourneyOptions.initial_impulse_bounds[1] = 1.0e-8 return myJourneyOptions
def updatestates(self): for i in range(len(self.state)): self.state[i]=Universe.updatestate(i,self.state[i])