Esempio n. 1
0
    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()
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
Esempio n. 3
0
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
Esempio n. 4
0
	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 )
Esempio n. 5
0
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()
Esempio n. 6
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")
Esempio n. 7
0
    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 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)
Esempio n. 9
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
Esempio n. 10
0
    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
Esempio n. 11
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
Esempio n. 12
0
    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, :]
Esempio n. 13
0
    def run(self):
        self.universe = Universe()
        self.universe.level_one()

        self.pygame_main_loop()
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
Esempio n. 15
0
with open("../../assets/data/ships/destroyer.json", 'r') as shipConfFile:
    shipConf = json.load(shipConfFile)
with open("../data/weapons.json", 'r') as missileConfFile:
    missileConf = json.load(missileConfFile)
missileConf = missileConf['weapons']['nuke']
size = width, height = 6400, 4800

if "-v" in sys.argv:
    import pygame
    pygame.init()
    basicFont = pygame.font.SysFont(None, 24)
    SCALEFACTOR = 640 / width
    screen = pygame.display.set_mode(
        (int(width * SCALEFACTOR), int(height * SCALEFACTOR)))

universe = Universe.Universe(size)
universe.id = 0

network = NetworkServer.NetworkServer({}, universe)

api = ClientAPI.ClientAPI(ClientAPI.GlobalContext([universe], network))

# Register ALL the classes!
api.register(Universe.Universe)
api.register(Entity.Entity)
api.register(Ship.Ship)
api.register(Component.Component)
api.register(Component.Drive)
api.register(Component.WeaponsStation)
api.register(Component.ShieldGenerator)
api.register(SharedClientDataStore.SharedClientDataStore)
plt.style.use('ggplot')

# ================================================== Local Packages
import sys
sys.path.insert(0, './Objs/')
import Universe

# ================================================== Main Simulation Script

if __name__ == '__main__':
    log.info("Main script for 02Drv_GraphStruct.py has begun")

    # parameters
    trueThetas = np.array([1, -1.45])
    W = np.array([[1, 0, trueThetas[0]], [0, 0, trueThetas[0]],
                  [0, trueThetas[1], 0]])
    t = np.arange(9)

    R3HwOne = Universe.Universe()
    R3HwOne.initFromMatrix(W)
    R3HwOne.simulateUniverse(t)

    Measure = Universe.Measurement()
    Measure.simulateNodeMeasurement(R3HwOne, 2, 0.1)

    # paramater estimation
    WlowerBound = np.array([[1, 0, 0], [0, 0, 0], [0, -1.45, 0]])
    WupperBound = np.array([[1, 0, 2], [0, 0, 2], [0, -1.45, 0]])
    Est = Universe.ParticleEstimator()
    Est.estimateParameters(R3HwOne, Measure, WlowerBound, WupperBound)
Esempio n. 17
0
# @route('/<path>',method = 'GET')
# def process(path):
# 	return subprocess.check_output(['python',path+'.py'],shell=True)
# run(host='localhost', port=8080, debug=True)

@hook('after_request')
def enable_cors():
    """
    You need to add some headers to each request.
    Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

uni = Universe(30)

@route('/')
def main():
	from bottle import response
	from json import dumps
	uni.printUniverse()
	starData = uni.getStarData()
	coordinates = uni.getCoordinates()
	response.content_type = 'application/json'
	return dumps({"starData": starData, "coordinates": coordinates})

@route('/search')
def searhIndex():
	from bottle import response
	from json import dumps
Esempio n. 18
0
        return(self.universe + ":("+ str(self.fromx) + "," + str(self.fromy) + \
               ") -> " + self.to_universe + ":(" + "{:.0f}".format(self.to_x)+ \
               "," + "{:.0f}".format(self.to_y) + ")")


if __name__ == "__main__":
    #take in inputs file
    fname = input("Input file => ")
    print(fname)
    data = json.loads(open(fname).read())

    #read universe related information
    universes = []
    for i in range(len(data)):
        universe = (data[i])['universe_name']
        universe = Universe(None, None, universe)
        universes.append(universe)

    #read reward lated information
    rewards = []
    for j in range(len(data)):
        for i in range(len((data[j])['rewards'])):
            reward = (data[j])['rewards'][i]
            reward = Rewards(reward[3], (data[j])['universe_name'], reward[0], \
                             reward[1], reward[2])
            rewards.append(reward)
    if rewards == []:
        rewards = None

    #read portals related information
    portals = []
Esempio n. 19
0
    def __init__(self, c=(0, 0, 0), s=(0, 0, 0)):

        if __debug__:
            print("# Vision3D constructor #")

        # data
        self.univ = Universe()

        #  dico Points3D <-> Pixel
        self.dicoPointPixel = {}

        self.c = c
        self.s = s

        # pixel expressed in unit of frame reference
        self.pixelInUnit = 1

        # pixels half-size of screen on Y
        self.winHalfSizeY = 192

        # pixels half-size of screen on X
        self.winHalfSizeX = 280

        # compute vector w

        # create SC vector
        sc = Vector3D(c, s)

        self.d = sc.norm()  # compute norm of SC

        # vectors defining screen frame

        # vector w
        # normalize w
        w = sc / self.d

        # vector u

        # arbitrary taking negative solution for orientation
        u = Vector3D()
        u.x = 0
        u.y = -(w.x / math.sqrt(w.x * w.x + w.y * w.y))
        u.z = -w.y * u.y / w.x

        # vector v
        v = w ^ u

        # change of basis matrix

        # cf. C++ version for comments
        # da1 = v.y * w.z - v.z * w.y
        # da2 = v.z * w.x - v.x * w.z
        # da3 = v.x * w.y - v.y * w.x

        da = v ^ w
        db = w ^ u
        dc = u ^ v

        # dot products - produits scalaires
        dau = u * da
        dbv = v * db
        dcw = w * dc

        daqu = da / dau
        dbqv = db / dbv
        dcqw = dc / dcw

        self.m3x3 = Matrix3x3(daqu, dbqv, dcqw)
Esempio n. 20
0
    def OpenFile(self, e):
        dlg = wx.FileDialog(self,
                            message="Open an EMTG file",
                            defaultDir=self.dirname,
                            defaultFile="",
                            wildcard="*.emtgopt;*.emtg_universe;*.emtg;",
                            style=wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()

            fileparts = self.filename.split(".")

            #before we actually open the new file, we need to clear memory associated with whatever file we currently have open
            if self.mode == "options":
                self.missionoptions = []
                self.optionsnotebook.Destroy()

            elif self.mode == "mission":
                self.mission = []
                self.missionpanel.Destroy()

            elif self.mode == "universe":
                self.universe = []
                self.universenotebook.Destroy()

            elif self.mode == "archive":
                self.archive = []
                self.archivepanel.Destroy()

            self.mode = ""

            #next open the new file
            if fileparts[1] == "emtgopt":

                import sys
                import inspect
                currentdir = os.path.dirname(
                    os.path.abspath(inspect.getfile(inspect.currentframe())))
                sys.path.append(currentdir + "/" + 'Converters')
                from Convert_emtgopt_v1_to_v2 import Convert_emtgopt_v1_to_v2

                self.missionoptions = Convert_emtgopt_v1_to_v2(
                    os.path.join(self.dirname, self.filename))

                if self.missionoptions.success == 1:
                    self.mode = "options"
                    self.lblWelcome.Show(False)
                    self.InitializeMissionOptionsEditor()
                    self.fileMenu.Enable(wx.ID_SAVE, True)
                    self.fileMenu.Enable(wx.ID_EDIT, True)

            elif fileparts[1] == "emtg":
                self.mission = Mission.Mission(
                    os.path.join(self.dirname, self.filename))
                if self.mission.success == 1:
                    self.mode = "mission"
                    self.lblWelcome.Show(False)
                    self.missionpanel = MissionPanel.MissionPanel(
                        self, self.mission)
                    self.missionpanel.SetSize(self.GetSize())
                    self.fileMenu.Enable(wx.ID_EDIT, True)

            elif fileparts[1] == "emtg_universe":
                self.universe = Universe.Universe(
                    os.path.join(self.dirname, self.filename))
                if self.universe.success == 1:
                    self.mode = "universe"
                    self.lblWelcome.Show(False)
                    self.InitializeUniverseOptionsEditor()
                    self.fileMenu.Enable(wx.ID_SAVE, True)
                    self.fileMenu.Enable(wx.ID_EDIT, True)

            elif fileparts[1] == "emtg_archive":
                self.archive = Archive.Archive(
                    os.path.join(self.dirname, self.filename))
                if self.archive.success == 1:
                    self.mode = "archive"
                    self.lblWelcome.Show(False)
                    self.InitializeArchiveProcessor()
                    self.fileMenu.Enable(wx.ID_EDIT, True)
                    self.fileMenu.Enable(wx.ID_SAVE, False)

            else:
                errordlg = wx.MessageDialog(self, "Unrecognized file type.",
                                            "EMTG Error", wx.OK)
                errordlg.ShowModal()
                errordlg.Destroy()

        dlg.Destroy()
Esempio n. 21
0
import Universe, sys, pyglet, signal, time, json
from AsyncFIFORead import AsyncFIFORead

f = AsyncFIFORead(sys.stdin)

def readInput(dx):
    line = f.readline()
    if line == None: return
    try:
        print eval(line, globals(), globals())
    except:
        try:
            exec line in globals(), globals()
        except Exception as e:
            print e
    print '___DONE___'

pyglet.clock.schedule_interval(readInput, 0.1) # TODO - change this

def ctrl_c_handler(signal, frame):
    pass
signal.signal(signal.SIGINT, ctrl_c_handler)

u = universe = Universe.Universe(sys.argv[1], json.loads(sys.argv[2][1:-1]))
w = universe.world
pyglet.app.run()
Esempio n. 22
0
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:
Esempio n. 23
0
    #people will be used to store information on each person in file
    people = []
    #universe dictionary will be used to store information on each universe
    universe = dict()
    print('All universes')
    print("----------------------------------------")
    #for loop to set universe keys to the universe name and the values to information on rewards, portals, and individuals in that universe
    #for loop also prints information about universe using Universe class
    for i in range(len(data)):
        uname = data[i]['universe_name']
        rewards = data[i]['rewards']
        portals = data[i]['portals']
        individuals = data[i]['individuals']
        universe[uname] = rewards, portals, individuals
        print(Universe(uname, rewards, portals))
        print()

        #for loop goes through each individual in the currently specified universe and assigns each piece of information about the individual to a variable which is then put into the Person class, then each class object is appended to the people list
        for o in range(len(data[i]['individuals'])):
            name = data[i]['individuals'][o][0]
            radius = data[i]['individuals'][o][1]
            current = uname
            x = data[i]['individuals'][o][2]
            y = data[i]['individuals'][o][3]
            dx = data[i]['individuals'][o][4]
            dy = data[i]['individuals'][o][5]
            people.append(Person(name, radius, uname, x, y, dx, dy))

    print('All individuals')
    print("----------------------------------------")
Esempio n. 24
0
import numpy as np
import time

# Setup the satellite model
time_init = dt.datetime.now()
mass_prop = {'mass': 1500.0,
             'cog': vt.Vector([0.5, 0.5, 1.5]),
             'moi': vt.Matrix(1375, 0, 0, 0, 1375, 0, 0, 0, 275)}
p_init = vt.Vector([7155.27304548, 0.0, 0.0])
v_init = vt.Vector([0.0, 0.46957258, 7.45043721])
att_init = vt.Vector([0.0, 0.0, 1.0])
ang_vel_init = vt.Vector([0.0, 0.06, 0.0])
satellite = SatModel.SatModel(time_init, mass_prop, p_init, v_init, att_init, ang_vel_init)

# Make universe
universe = Universe.Universe(satellite, time_init)

# Make plotting variables
x_sat = np.array([p_init.x])
y_sat = np.array([p_init.y])
z_sat = np.array([p_init.z])

# Initialize the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plotting.add_earth_sphere()
# ax.plot(x_sat, y_sat, z_sat, label='Orbit')
# ax.legend()

# plt.ion()
# plt.show()
Esempio n. 25
0
            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 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
Esempio n. 27
0
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()
Esempio n. 28
0
    infile = input("Input file => ")
    print(infile)

    # initialize list of universe and people
    data = json.loads(open(infile).read())
    U = []
    P = []

    # for every json dictionary record
    for u in data:

        # append the universe name, rewards, and portals ro the Universe class
        uname = u['universe_name']
        urewards = u['rewards']
        uportals = u['portals']
        U.append(Universe(uname, urewards, uportals))

        # append every individual's info to the super person class
        for p in u['individuals']:

            P.append(
                SPerson(name=p[0],
                        radius=p[1],
                        home_universe=uname,
                        x=p[2],
                        y=p[3],
                        dx=p[4],
                        dy=p[5]))

    # print all universes
    print("All universes")
Esempio n. 29
0
	def setUp( self ):
		self.u = Universe.Universe()
		if self.uid is None:
			self.uid = id( self.u )
Esempio n. 30
0
def game_loop():
    # Initialisation
    universe = Universe.Universe()
    display = Display.View(universe, (1800, 1000), (0, 0))
    elements = []

    if False:
        tests(universe, elements)

    universe.setup_start_area(elements, display)

    # Main loop
    keepGoing = True
    iterationCount = 0

    selected = {}
    targeted = {}
    mousepos = -999, -999  # Default
    while keepGoing:
        # DEBUG - Increment the scaling factor to test the various co-ordinate system mappings
        if iterationCount % 1000 == 0:
            print "Number of ships", len(elements)
        #    display.set_scale(display.scale+scalechange)
        #    if abs(display.scale) >= 10:
        #        scalechange = -scalechange
        iterationCount += 1

        # Tick the world
        newElements = []
        for e in elements:
            if e.mass.alive:
                e.update()
                newElements.append(e)
        elements = newElements

        # Draw the world
        display.draw(elements)

        for event in display.update():
            if event.type == pygame.QUIT:
                return False
            elif event.type == pygame.MOUSEMOTION:
                mousepos = event.pos
            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:  # 1 == Left
                    for e in elements:
                        if e.mass.alive:
                            if (e.handle_click(event.pos, True)):
                                selected[e.get_id(
                                )] = e  # Keep a record of who is selected. Overwrite duplicates.
                                break
                elif event.button == 2:  # 2 == Centre - Pick
                    for e in elements:
                        if e.mass.alive:
                            if (e.handle_pickclick(event.pos, False)):
                                display.focus_object = e
                if event.button == 3:  # 3 == Right
                    for e in elements:
                        if e.mass.alive:
                            if (e.handle_rightclick(event.pos, True)):
                                targeted[e.get_id(
                                )] = e  # Keep a record of who is selected. Overwrite duplicates.
                                break
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_p:  # Pick
                    print "Pick"
                    for e in elements:
                        if e.mass.alive:
                            if (e.handle_click(mousepos, False)):
                                display.focus_object = e
            else:
                print event  # Placeholder

        # Handle AI commands

        #  We've been given a bunch of selected entities, and a bunch of targeted entities.
        #  Check if there's a new command to be added to the selected and targeted lists
        #  After processing, clear the lists

        clear_targets = False
        for key in selected:
            e = selected[key]
            if isinstance(e, Ship.Ship):
                for key_tgt in targeted:
                    t = targeted[key_tgt]
                    if isinstance(t, Planet.World) or isinstance(
                            t, Station.Station):
                        if t not in e.trade_targets:
                            e.move_target_current = t

                            # e.trade_targets.append(t)
                            clear_targets = True
                            e.mass.selected = False
                            t.mass.targeted = False
                    elif isinstance(t, Ship.Ship):
                        e.move_target_current = t
                        clear_targets = True
                        e.mass.selected = False
                        t.mass.targeted = False
                # print e.mass.id, e.trade_targets
        if clear_targets:
            targeted = {}
            selected = {}