Пример #1
0
def createAndAnimate():
    ss = SolarSystem(2, 2)

    sun = Sun("SUN", 10)
    ss.addSun(sun)

    m = Planet("Mercury", 1000, 0.2, 1, 0, 2, "orange")
    ss.addPlanet(m)

    e = Planet("Earth", 5000, 0.3, 1.3, 0, 2, "blue")
    ss.addPlanet(e)

    ma = Planet("Mars", 9000, 0.5, 1.2, 0, 1.63, "red")
    ss.addPlanet(ma)

    p = Planet("Pluto", 500, 0.9, .5, 0, .5, "gray")
    ss.addPlanet(p)

    # a = Planet("Asteroid", 500, 1.0, 0, .75, "cyan")
    # ss.addPlanet(a)

    numCycles = 10000
    for i in range(numCycles):
        ss.movePlanets()

    # while True:
    #     ss.movePlanets()
    #     # You can add functionality to break away from the loop given some condition
    #     # use the keyword break
    #     break


    ss.freeze()
Пример #2
0
    def checkPlanetConstructor(self):
        print("Checking Planet constructor...")

        xxPos = 1.0
        yyPos = 2.0
        xxVel = 3.0
        yyVel = 4.0
        mass = 5.0

        imgFileName = "jupiter.gif"

        p = Planet(xxPos, yyPos, xxVel, yyVel, mass, imgFileName)

        self.checkEquals(xxPos, p.xxPos, "x")
        self.checkEquals(yyPos, p.yyPos, "y")
        self.checkEquals(xxVel, p.xxVel, "xVelocity")
        self.checkEquals(yyVel, p.yyVel, "yVelocity")
        self.checkEquals(mass, p.mass, "mass")
        self.checkStringEquals(imgFileName, p.imgFileName, "path to image")

        pCopy = Planet().PlanetCopy(p)

        self.checkEquals(p.xxPos, pCopy.xxPos, "x")
        self.checkEquals(p.yyPos, pCopy.yyPos, "y")
        self.checkEquals(p.xxVel, pCopy.xxVel, "xVelocity")
        self.checkEquals(p.yyVel, pCopy.yyVel, "yVelocity")
        self.checkEquals(p.mass, pCopy.mass, "mass")
        self.checkStringEquals(p.imgFileName, pCopy.imgFileName,
                               "path to image")
Пример #3
0
 def extractInfos(self, request=None, darkMatter=False, planets=True):
     if request == None:
         request = self.lastRequest
     if (request.response != None):
         content = request.content
         soup = BeautifulSoup(content, "html.parser")
         if darkMatter:
             self.darkMatter = int(
                 soup.find(id="current_darkmatter").attrs['data-real'])
             self.lastExtracedInfosDate = time.time()
         if planets:
             ps = soup.find(id="planetSelector").find_all("option")
             self.planets = []
             for p in ps:
                 planet = self.ia.planetNameParser.findall(str(p))
                 id = int(p.attrs['value'])
                 name = planet[0][0]
                 position = [int(x) for x in planet[0][1].split(":")]
                 if "Lune" in name:
                     position.append(3)
                 else:
                     position.append(1)
                 pl = Planet(id, name, position, self)
                 self.planets.append(pl)
                 pl.scan()
Пример #4
0
    def checkCalcDistance(self):
        print("Checking calcDistance...")

        p1 = Planet(1.0, 1.0, 3.0, 4.0, 5.0, "jupiter.gif")
        p2 = Planet(2.0, 1.0, 3.0, 4.0, 5.0, "jupiter.gif")
        p3 = Planet(4.0, 5.0, 3.0, 4.0, 5.0, "jupiter.gif")

        self.checkEquals(p1.calcDistance(p2), 1.0, "calcDistance()", 0.01)
        self.checkEquals(p1.calcDistance(p3), 5.0, "calcDistance()", 0.01)
Пример #5
0
def loadAll(load_name):
	global system_list
	global planet_list
	global ship_list
	global crew_list
	global game_folder

	makePartsList()
	path_to_load = game_folder + '/' + 'Save' + '/' + str(load_name)

	file_to_read = open(path_to_load + '/' + 'system', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'state':
			system = System()
			system.load(tmp)
			system_list.append(system)
			tmp = []
	file_to_read.close()

	file_to_read = open(path_to_load + '/' + 'planet', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'resourse':
			planet = Planet()
			planet.load(tmp)
			planet_list.append(planet)
			tmp = []
	file_to_read.close()

	file_to_read = open(path_to_load + '/' + 'ship', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'spot':
			ship = Ship()
			ship.load(tmp)
			ship_list.append(ship)
			tmp = []
	file_to_read.close()

	file_to_read = open(path_to_load + '/' + 'crew', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'weapon':
			crew = Crew()
			crew.load(tmp)
			crew_list.append(crew)
			tmp = []
	file_to_read.close()

	gui.paintWindowGalaxy()
    def calcNetForceExertedByXY(self):
        print("Checking setNetForce...")

        p1 = Planet(1.0, 1.0, 3.0, 4.0, 5.0, "jupiter.gif")
        p2 = Planet(2.0, 1.0, 3.0, 4.0, 4e11, "jupiter.gif")

        p3 = Planet(4.0, 5.0, 3.0, 4.0, 5.0, "jupiter.gif")
        p4 = Planet(3.0, 2.0, 3.0, 4.0, 5.0, "jupiter.gif")

        planets = [p2, p3, p4]

        xNetForce = p1.calcNetForceExertedByX(planets)
        yNetForce = p1.calcNetForceExertedByY(planets)
        print(xNetForce, yNetForce)

        self.checkEquals(133.4, self.round(xNetForce, '.01'),
                         "calcNetForceExertedByX()")
        self.checkEquals(0.0, self.round(yNetForce, '.01'),
                         "calcNetForceExertedByY()")

        print(
            "Running test again, but with array that contains the target planet."
        )

        planets = [p1, p2, p3, p4]

        xNetForce = p1.calcNetForceExertedByX(planets)
        yNetForce = p1.calcNetForceExertedByY(planets)

        self.checkEquals(133.4, self.round(xNetForce, '.01'),
                         "calcNetForceExertedByX()")
        self.checkEquals(0.0, self.round(yNetForce, '.01'),
                         "calcNetForceExertedByY()")
Пример #7
0
	def checkUpdate(self):
		print("Checking update...")

		p1 = Planet(1.0, 1.0, 3.0, 4.0, 5.0, "jupiter.gif")

		p1.update(2.0, 1.0, -0.5)

		self.checkEquals(7.8, p1.xxPos, "update()", 0.01)
		self.checkEquals(8.6, p1.yyPos, "update()", 0.01)
		self.checkEquals(3.4, p1.xxVel, "update()", 0.01)
		self.checkEquals(3.8, p1.yyVel, "update()", 0.01)
Пример #8
0
def demo():
    planet = Planet(J=0.00, rp_over_rs=0.1, rsum_over_a=1.0/20.0, cosi=0.000, q=0.000, period=1.58, t0=2456000.0, esinw=0.0, ecosw=0.0)
    star = Star(u1=0.3, u2=0.3, gd=0.32, albedo=0)
    tm = TM(planet=planet, star=star)
    (p1, p4, s1, s4) = planet.contacts()
    print planet.contacts()
    duration = (p4 - p1 + 1)*planet.period.value
    t = np.linspace(planet.t0.value - duration, planet.t0.value + duration, 1000)
    uncertainty = 0.003*np.ones_like(t)
    tlc = TLC(t, tm.model(t) + np.random.normal(len(t))*uncertainty, uncertainty)
    tlc.plot()
Пример #9
0
 def makePlanets(self):
     self.mars = Planet(self.width / 5, self.height / 5, "mars")
     self.marsGroup = pygame.sprite.Group(self.mars)
     self.collPlanet = None
     self.neptune = Planet(4 * self.width / 5, self.height / 5, "neptune")
     self.neptunegroup = pygame.sprite.Group(self.neptune)
     self.uranus = Planet(self.width / 5, 4 * self.height / 5, "uranus")
     self.uranusgroup = pygame.sprite.Group(self.uranus)
     self.mercury = Planet(4 * self.width / 5, 4 * self.height / 5,
                           "mercury")
     self.mercurygroup = pygame.sprite.Group(self.mercury)
Пример #10
0
    def __load_positions(self):
        for data in self.level_data:
            name, x, y = self.__break_data(data)

            if name == 'earth':
                self.earth = Planet(x, y)
            if name == 'black_hole':
                self.black_hole = Black_Hole(x, y)
            if name == 'star':
                self.stars.append(Star(x, y))
            if name == 'neutron_star':
                self.neutron_stars.append(Neutron_Star(x, y))
Пример #11
0
 def __init__(self, x, y, z, description):
     """
     Konstruktor der Klasse
     :param x: x-Position
     :param y: y-Position
     :param z: z-Position
     :param description: Beschreibung
     """
     Planet.__init__(self, x, y, z, description)
     self.orbit = render.attachNewNode('orbit_root_sun')
     self.dayscale = 25 * 24
     self.tspeed = 0
     self.__init__texture()
Пример #12
0
def main():
    # < x = -9, y = 10, z = -1 >
    # < x = -14, y = -8, z = 14 >
    # < x = 1, y = 5, z = 6 >
    # < x = -19, y = 7, z = 8 >
    io = Planet(pos_x=-9, pos_y=10, pos_z=-1)
    europa = Planet(pos_x=-14, pos_y=-8, pos_z=14)
    ganymede = Planet(pos_x=1, pos_y=5, pos_z=6)
    callisto = Planet(pos_x=-19, pos_y=7, pos_z=8)

    # < x = -1, y = 0, z = 2 >
    # < x = 2, y = -10, z = -7 >
    # < x = 4, y = -8, z = 8 >
    # < x = 3, y = 5, z = -1 >
    # io = Planet(pos_x=-1, pos_y=0, pos_z=2)
    # europa = Planet(pos_x=2, pos_y=-10, pos_z=-7)
    # ganymede = Planet(pos_x=4, pos_y=-8, pos_z=8)
    # callisto = Planet(pos_x=3, pos_y=5, pos_z=-1)

    # < x = -8, y = -10, z = 0 >
    # < x = 5, y = 5, z = 10 >
    # < x = 2, y = -7, z = 3 >
    # < x = 9, y = -8, z = -3 >
    # io = Planet(pos_x=-8, pos_y=-10, pos_z=0)
    # europa = Planet(pos_x=5, pos_y=5, pos_z=10)
    # ganymede = Planet(pos_x=2, pos_y=-7, pos_z=3)
    # callisto = Planet(pos_x=9, pos_y=-8, pos_z=-3)

    planets = [io, europa, ganymede, callisto]

    for i in range(1000):
        print()
        print('Step ', i)
        for base_planet in planets:
            print('pos=', base_planet.position, ' vel=', base_planet.velocity)
            for planet in planets:
                if planet == base_planet:
                    continue
                base_planet.add_gravity_for_planet(planet)

        for planet in planets:
            planet.apply_velocity_to_position()

    total_energy = 0
    for planet in planets:
        total_energy += planet.calculate_total_energy()

    print(total_energy)
    exit(1)
Пример #13
0
Файл: TM.py Проект: zkbt/transit
	def load(self, directory):
		'''Load parameters from directory.'''
		#self.directory = directory
		self.speak('loading TM from {0}'.format(directory))
		self.planet = Planet(directory=directory)
		self.star = Star(directory=directory)
		self.instrument = Instrument(directory=directory)
Пример #14
0
 def create_planet(self, description: str, x_position:float, y_position:float, x_speed:float, y_speed:float, mass: float):
     """Creates a planet and appends it to the list planetary_objects."""
     if self.validate_position(x_position, y_position) == False:
         raise ValueError("There is already a planet in this position!")
     new_planet = Planet(description, x_position, y_position, x_speed, y_speed, mass)
     self.planetary_objects.append(new_planet)
     return new_planet
Пример #15
0
 def level3init(self):
     self.win = False
     self.screen3 = True
     self.bgColor = (0, 0, 0)
     Ship.init()
     ship = Ship(self.width / 2, self.height / 2)
     self.shipGroup = pygame.sprite.GroupSingle(ship)
     self.earthStage = 1
     planet = Planet(self.width / 2, self.height - 100, "earth")
     self.planetGroup = pygame.sprite.Group(planet)
     self.asteroids = pygame.sprite.Group()
     self.missiles = pygame.sprite.Group()
     self.hitCount = 1
     self.score3 = 0
     self.earthFlag = False
     self.counter = 0
     self.lost = False
     self.bgImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/Lev3.png').convert_alpha(),
             (self.width, self.height)), 0)
     self.closeImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/finish.jpg').convert_alpha(),
             (self.width, self.height)), 0)
Пример #16
0
 def readPlanets(fname):
     data = open(fname)
     numPlanets = int(data.readline())
     radius = float(data.readline())
     planetsList = [
         Planet(*data.readline().split()) for planet in range(numPlanets)
     ]
     return planetsList
Пример #17
0
 def init1(self):
     moon = Moon(self.planetx + self.radCurve, self.planety + self.radCurve)
     planet = Planet(self.planetx, self.planety, "earth", 100)
     ship = Ship(self.planetx + self.r * cos(self.theta),
                 self.planety + self.r * sin(self.theta))
     self.planetGroup = pygame.sprite.Group(planet)  #c
     self.shipGroup = pygame.sprite.Group(ship)  #c
     self.moonGroup = pygame.sprite.Group(moon)  #c
Пример #18
0
 def create(self):
     self.planets = []
     self.planets.append(Planet("Mercury", 3031, 32548000, 0))
     self.planets.append(Planet("Venus", 7521, 66871000, 0))
     self.planets.append(Planet("Earth", 7917, 92009000, 1))
     self.planets.append(Planet("Mars", 4222, 142120000, 2))
     self.planets.append(Planet("Jupiter", 86881, 484260000, 67))
     self.planets.append(Planet("Saturn", 72367, 930450000, 62))
     self.planets.append(Planet("Uranus", 31518, 1841600000, 27))
     self.planets.append(Planet("Neptune", 30599, 2781900000, 14))
Пример #19
0
def transition(player: Color, blue: Planet, red: Planet,
               engineCard: EngineCard):
    if engineCard == EngineCard.SWAP or engineCard == EngineCard.PROBE:
        raise Exception(
            "Handle SWAP and PROBE on your own! They aren't worth my time")

    # For now, the comment "CNOT: flip your ship only if the other ship is on CENTARIOUS ONE" was ignored
    if player == Color.Blue:
        new = blue.get_transition(engineCard, player)
        if isinstance(new, Planet):
            return new
        else:
            return new[red]
    else:
        new = red.get_transition(engineCard, player)
        if isinstance(new, Planet):
            return new
        else:
            return new[blue]
Пример #20
0
 def __systemInit(self):
     self.__bodies = []
     randNum = random.choices([1, 2, 3], weights=(90, 9, 1))[0]
     n = 0
     for s in range(1):
         self.__bodies.append(Star(self, n))
         n += 1
     for p in range(random.randint(self.__minBodies, self.__maxBodies)):
         self.__bodies.append(Planet(self, n))
         n += 1
Пример #21
0
    def update_coords(self, t_struct):
        self.last_update_time_Ms = time.mktime(t_struct)

        p = Planet(planet_enum.SUN, res[planet_enum.SUN][0],
                   res[planet_enum.SUN][1], res[planet_enum.SUN][2])
        self.sun_coords = get_instance(t_struct=t_struct, planet=p)

        ra_dec = radec_get_instance(earth_coord=self.sun_coords,
                                    planet=self.planet,
                                    time=t_struct)
        self.current_coords.update_from_ra_dec(ra_dec.ra, ra_dec.dec)
        for imgsrc in self.image_sources:
            imgsrc.set_up_vector(self.sun_coords)
Пример #22
0
 def generate_planet(self):
     array_len = len(self.planet_names)
     index = random.randint(0, array_len - 1)
     planet_name = self.planet_names[index]
     del self.planet_names[index]  # Removes the used name from the pool
     biome_generator = BiomeGen()
     number_of_biomes = random.randint(1, 5)
     biomes = []
     while number_of_biomes >= 1:
         biomes.append(biome_generator.generate_biome())  # Adds another biome to the array
         number_of_biomes -= 1
     planet = Planet(planet_name, biomes)
     return planet
    def checkCalcForceExertedByXY(self):
        print("Checking calcForceExertedByX and calcForceExertedByY...")

        p1 = Planet(1.0, 1.0, 3.0, 4.0, 5.0, "jupiter.gif")
        p2 = Planet(2.0, 1.0, 3.0, 4.0, 4e11, "jupiter.gif")
        p3 = Planet(4.0, 5.0, 3.0, 4.0, 5.0, "jupiter.gif")

        self.checkEquals(p1.calcForceExertedByX(p2), 133.4,
                         "calcForceExertedByX()", 0.01)
        self.checkEquals(p1.calcForceExertedByX(p3), 4.002e-11,
                         "calcForceExertedByX()", 0.01)
        self.checkEquals(p1.calcForceExertedByY(p2), 0.0,
                         "calcForceExertedByY()", 0.01)
        self.checkEquals(p1.calcForceExertedByY(p3), 5.336e-11,
                         "calcForceExertedByY()", 0.01)
Пример #24
0
def create_planets():
    """
	This functions creates mock planets.

	Returns:
		list: List of mock planets.
	"""
    planets = []

    earth = Planet("Earth", BLUE, 10, 1, (width // 2, 200), velocity=(1, 0))
    sun = Planet("Sun", (255, 255, 0), int(696340 // SCALE), 1000,
                 (width // 2, height // 2))
    mars = Planet("MARS",
                  RED,
                  int(300000 // SCALE),
                  10, (width // 3, height // 2),
                  velocity=(0, 1))

    planets.append(earth)
    planets.append(mars)
    planets.append(sun)

    return planets
Пример #25
0
def get_planets_list():
    planetas = []
    for planet in planets:
        new_planet = planets[planet]
        planetas.append(
            Planet(name=planet,
                   epsilon=new_planet['epsilon'],
                   period=new_planet['p'],
                   semimajor_axis=new_planet['a'],
                   i=new_planet['i'],
                   capital_omega=new_planet['capital_omega'],
                   omega_bar=new_planet['omega_bar']))

    return planetas
class PlanetTests(unittest.TestCase):
    def setUp(self):
        self.temp = Planet()

    def test_mercury_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(2134835688, "Merkury"),
                         280.88)

    def test_venus_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000, "Wenus"),
                         51.51)

    def test_earth_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000.0, "Ziemia"),
                         31.69)

    def test_mars_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000, "Mars"),
                         16.85)

    def test_jupiter_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000, "Jowisz"),
                         2.67)

    def test_saturn_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000, "Saturn"),
                         1.08)

    def test_uranus_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000, "Uran"),
                         0.38)

    def test_neptune_age_correctly_counted(self):
        self.assertEqual(self.temp.count_age_on_planet(1000000000, "Neptun"),
                         0.19)

    def test_mercury_exception1(self):
        self.assertRaises(ValueError, self.temp.count_age_on_planet,
                          2134835688, "Merkur")

    def test_mercury_exception2(self):
        self.assertRaises(ValueError, self.temp.count_age_on_planet, "",
                          "Merkury")

    def test_mercury_exception3(self):
        self.assertRaises(ValueError, self.temp.count_age_on_planet,
                          "2134835688", "Merkury")
Пример #27
0
def initialize_list(dist_max,
                    nbr_planetes,
                    masse_moyenne,
                    vitesse_moyenne,
                    moment_ang_moyen,
                    masse_terre=5.9722 * (10)**24,
                    rayon_terre=6378.137 * (10)**3):
    densitee_terre = (masse_terre) / ((4 * np.pi * rayon_terre**3) / 3)

    #########################################
    #   Définition de la liste de planètes  #
    #########################################
    # 1) Masse:
    masse = np.array(
        abs_liste(
            np.random.normal(masse_moyenne, masse_moyenne / 3, nbr_planetes)))
    masse = masse * (masse_moyenne / masse.mean())

    # 2) Rayon:
    rayon = [(((3 * m) / (densitee_terre * 4 * np.pi))**(1 / 3)) / 150
             for m in masse]

    # 3) Position
    dist = np.random.rand(nbr_planetes) * dist_max
    angle = np.random.rand(nbr_planetes) * 2 * np.pi

    x = [d * np.cos(theta) for d, theta in zip(dist, angle)]
    y = [d * np.sin(theta) for d, theta in zip(dist, angle)]

    # 4) Vitesse
    vitesse = np.random.normal(vitesse_moyenne, vitesse_moyenne / 3,
                               nbr_planetes)
    vitesse = vitesse * (vitesse_moyenne / vitesse.mean())
    angle2 = np.random.rand(nbr_planetes) * 2 * np.pi

    #Définir les vitesse associées
    vx = [v * np.cos(theta2) for v, theta2 in zip(vitesse, angle2)]
    vy = [v * np.sin(theta2) for v, theta2 in zip(vitesse, angle2)]

    # 6) Création des planètes
    liste_planetes = [
        Planet(masse, rayon, x, y, vx, vy, '{}'.format(i))
        for masse, rayon, x, y, vx, vy, i in zip(masse, rayon, x, y, vx, vy,
                                                 range(1,
                                                       len(masse) + 1))
    ]

    return liste_planetes
Пример #28
0
    def __init__(self,
                 PlanetModel=Planet('Mars'),
                 VehicleModel=EntryVehicle(),
                 Coriolis=False,
                 Powered=False):

        self.planet = PlanetModel
        self.vehicle = VehicleModel
        self.powered = Powered
        self.drag_ratio = 1
        self.lift_ratio = 1

        if Coriolis:
            self.dyn_model = self.__entry_vinhs
        else:
            self.dyn_model = self.__entry_3dof
Пример #29
0
 def __init__(self, parent=None):
     QtWidgets.QWidget.__init__(self, parent)
     self.setPalette(QtGui.QPalette(QtGui.QColor(100, 100, 100)))
     self.setAutoFillBackground(True)
     self.oImage = QtGui.QImage("background.jpg")
     sImage = self.oImage.scaled(QtCore.QSize(self.width(),self.height()))
     palette = QtGui.QPalette()
     palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(sImage))                        
     self.setPalette(palette)
     self.planets =[]
     self.planets.append(Planet('Mercury', 57909175, 56671636.48, 11907903.61, 0.20563069, 0, 4.147727272727273, QtGui.QColor.fromRgb(217, 197, 180), 10))
     self.planets.append(Planet('Venus', 108208930, 108206447.8, 732923.9709, 0.00677323, 0, 1.622222222222222, QtGui.QColor.fromRgb(186, 187, 188), 10))
     self.planets.append(Planet('Earth', 149597890, 149577002.3, 2499813.6534358, 0.01671022, 0, 0.9993428978206111, QtGui.QColor.fromRgb(2, 0, 254), 10))
     self.planets.append(Planet('Mars', 227936640, 226939989.1, 21292092.63, 0.09341233, 0, 0.5312954876273654, QtGui.QColor.fromRgb(255, 0, 0), 10))
     self.planets.append(Planet('Jupiter', 778412020, 777500023.9, 37669428.22, 0.04839266, 0, 0.0843150843150843, QtGui.QColor.fromRgb(204, 153, 102), 20))
     self.planets.append(Planet('Saturn', 1426725400, 1424632080, 77258036.45, 0.05415060, 0, 0.0339503302018417365, QtGui.QColor.fromRgb(229,183,59), 20))
     self.planets.append(Planet('Uranus', 2870972200, 2867776762, 135417184.1, 0.04716771, 0, 0.0119032089746935, QtGui.QColor.fromRgb(31,117,254), 15))
     self.planets.append(Planet('Neptun', 4498252900, 4498087098, 38621414.63, 0.00858587, 0, 0.00606836470040575, QtGui.QColor.fromRgb(0,72,186), 15))
Пример #30
0
    def checkCalcForceExertedBy(self):
        print("Checking calcForceExertedBy...")

        p1 = Planet(1.0, 1.0, 3.0, 4.0, 5.0, "jupiter.gif")
        p2 = Planet(2.0, 1.0, 3.0, 4.0, 4e11, "jupiter.gif")
        p3 = Planet(4.0, 5.0, 3.0, 4.0, 5.0, "jupiter.gif")
        print(Planet.G)

        self.checkEquals(p1.calcForceExertedBy(p2), 133.4,
                         "calcForceExertedBy()", 0.01)
        self.checkEquals(p1.calcForceExertedBy(p3), 6.67e-11,
                         "calcForceExertedBy()", 0.01)
Пример #31
0
    def generate(self):
        #creates a planet
        planet = Planet()

        #adds a random number of humans and robots to the planet object

        for index in range(random.randint(1, 10)):
            robot = Robot(f"Robot{index}")
            planet.add_robot(robot)

        for index in range(random.randint(1, 10)):
            human = Human(f"Human{index}")
            planet.add_human(human)

        # add to list of planets
        self.planets.append(planet)
Пример #32
0
    def run(self,
            InitialState,
            Controllers,
            InputSample=None,
            FullEDL=False,
            AeroRatios=(1, 1)):
        """ Runs the simulation from a given a initial state, with the specified controllers in each phase, and using a chosen sample of the uncertainty space """

        self.reset()

        if InputSample is None:
            InputSample = np.zeros(4)
        CD, CL, rho0, sh = InputSample

        self.sample = InputSample
        self.fullEDL = FullEDL
        if self.fullEDL:
            self.edlModel = System(
                InputSample=InputSample
            )  # Need to eventually pass knowledge error here
        else:
            self.edlModel = Entry(PlanetModel=Planet(rho0=rho0,
                                                     scaleHeight=sh),
                                  VehicleModel=EntryVehicle(CD=CD, CL=CL))
            self.edlModel.update_ratios(LR=AeroRatios[0], DR=AeroRatios[1])
        self.update(np.asarray(InitialState), 0.0, None)
        self.control = Controllers
        while not self.is_Complete():
            temp = self.advance()

        self.history = np.vstack(
            self.history
        )  # So that we can work with the data more easily than a list of arrays
        self.control_history.append(
            self.u
        )  # So that the control history has the same length as the data;
        self.control_history = np.vstack(self.control_history)

        return self.postProcess()
Пример #33
0
 def level1init(self):
     self.marsHit = False
     self.screen1 = True
     self.playing = True
     self.onScreen = True
     self.marsx = self.width * 3 / 5 - 50
     self.marsy = self.height / 2
     self.mars = Planet(self.marsx, self.marsy, "mars", 100, 30)
     self.marsGroup = pygame.sprite.Group(self.mars)
     Ship.init()
     Moon.init()
     self.planetx, self.planety = self.width / 5, self.height - self.height / 3,
     self.r = 120
     self.radCurve = 550
     self.moonAngle = 80
     self.moonx, self.moony = self.width, self.height
     self.init1()
     self.m = 0
     self.gameDisplay = pygame.display.set_mode((self.width, self.height))
     self.starImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/stars.png').convert_alpha(),
             (self.width, self.height)), 0)
Пример #34
0
    def main_loop(self):

        planet = Planet(100, 1, 0)

        pygame.init()

        screen = pygame.display.set_mode((planet.max_row, planet.row_count), HWSURFACE)
        pygame.display.set_caption("Planet")

        background = pygame.Surface(screen.get_size())
        background.fill((128, 128, 128))

        def in_bounds(x, y):
            return x > planet.row_offsets[y] and x < planet.row_offsets[y] + planet.row_lengths[y]

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x, y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x, y), (value, value, value))
        background.unlock()

        screen.blit(background, (0, 0))

        points = pygame.sprite.Group()

        for n in range(20):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10, 10))
            row = random.randint(1, planet.row_count - 1)
            a = array([random.uniform(-1) for i in range(3)])
            point.w = random.uniform(1, 10)
            pygame.draw.circle(point.image, (0, 255 - int(point.w * 16), 0), (5, 5), 5)
            point.p = a / norm(a)
            point.theta = 0 if n == 0 else random.uniform(0, 2 * math.pi)
            point.v = zeros(3)
            point.rect = pygame.Rect((0, 0), point.image.get_size())
            points.add(point)

        midpoints = pygame.sprite.Group()
        midpoint = pygame.sprite.Sprite()
        midpoint.image = pygame.Surface((10, 10))
        pygame.draw.circle(midpoint.image, (0, 0, 255), (5, 5), 5)
        midpoint.rect = pygame.Rect((0, 0), midpoint.image.get_size())

        heatpoint = pygame.sprite.Sprite()
        heatpoint.image = pygame.Surface((10, 10))
        pygame.draw.circle(heatpoint.image, (255, 0, 0), (5, 5), 5)
        heatpoint.rect = pygame.Rect((0, 0), heatpoint.image.get_size())
        midpoints.add(heatpoint)
        midpoints.add(midpoint)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True

            midpoint.p = planet.vector_weighted_average(
                [point.p for point in points.sprites()], [point.w for point in points.sprites()]
            )
            midpoint.rect.topleft = planet.vector_to_xy(midpoint.p, midpoint.image.get_size())

            speed = sum([norm(p.v) for p in points])
            if speed < 0.05:
                heatpoint.p = midpoint.p
                heatpoint.rect.topleft = midpoint.rect.topleft

            for point in points:
                dist = math.acos(dot(heatpoint.p, point.p))
                decay = lambda dist: 0.01 * pow(dist - math.pi, 2)
                v = -planet.project_on_plane(heatpoint.p - point.p, point.p)
                point.v += decay(dist) * v / norm(v) / point.w
                point.p, point.v = planet.apply_velocity(point.p, point.v)
                point.v = 0.75 * point.v
                point.rect.topleft = planet.vector_to_xy(point.p, point.image.get_size())

            merge = dict()
            for point in points:
                for other in points:
                    if point == other:
                        continue
                    if math.acos(dot(point.p, other.p)) < 0.05:
                        if other in merge:
                            if not point in merge[other]:
                                merge[other].append(point)
                        else:
                            merge[point] = [other]

            newpoints = []
            seen = []
            for first, merging in merge.items():
                merging.append(first)
                print "merging", len(merging), [m.w for m in merging], "into", sum([m.w for m in merging])
                for point in merging:
                    seen.append(point)

                point = pygame.sprite.Sprite()
                point.image = pygame.Surface((10, 10))
                point.w = sum([m.w for m in merging]) / len(merging)
                pygame.draw.circle(point.image, (0, 255 - int(point.w * 16), 0), (5, 5), 5)
                point.p = array(planet.vector_weighted_average([m.p for m in merging], [m.w for m in merging]))
                point.v = sum([m.v / m.w for m in merging])
                point.rect = pygame.Rect((0, 0), point.image.get_size())
                newpoints.append(point)

            for point in points:
                if point in seen:
                    continue
                if point.w > 0.5 and norm(point.v) > 0.1:
                    added = []
                    for i in range(2):
                        half = pygame.sprite.Sprite()
                        half.image = pygame.Surface((10, 10))
                        half.w = point.w / 2
                        pygame.draw.circle(half.image, (0, 255 - int(half.w * 16), 0), (5, 5), 5)
                        half.p = point.p
                        theta = -math.pi / 4 + i * math.pi / 2
                        half.v = planet.rotate(point.v, half.p, theta) / 2
                        half.rect = pygame.Rect((0, 0), half.image.get_size())
                        newpoints.append(half)
                        added.append(half)
                    print "splitting", point.w, "into", [a.w for a in added]
                    seen.append(point)

            save = [p for p in points if not p in seen]
            points.empty()
            points.add(newpoints)
            points.add(save)

            points.clear(screen, background)
            points.draw(screen)

            midpoints.clear(screen, background)
            midpoints.draw(screen)

            pygame.display.flip()

            limit.tick()
Пример #35
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()

        for n in range(10):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            pygame.draw.circle(point.image, (255,0,0), (5,5), 5)
            row = random.randint(1, planet.row_count-1)
            column = random.randint(0, planet.row_lengths[row]-1)
            point.raw_coords = planet.get_coordinates(row, column,
                                                      point.image.get_size())
            point.theta = random.uniform(0, 2 * math.pi)
            point.speed = 0
            point.rect = pygame.Rect(point.raw_coords, point.image.get_size())
            points.add(point)

        midpoints = pygame.sprite.Group()
        midpoint = pygame.sprite.Sprite()
        midpoint.image = pygame.Surface((10,10))
        pygame.draw.circle(midpoint.image, (0,255,0), (5,5), 5)
        midpoint.rect = pygame.Rect((0,0), midpoint.image.get_size())
        midpoints.add(midpoint)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True

            midpoint.rect.topleft = planet.weighted_average(
                [s.raw_coords for s in points.sprites()],
                [1 for s in points.sprites()],
                [s.image.get_size() for s in points.sprites()],
                midpoint.image.get_size())
                        
            for point in points:
                x, y = point.raw_coords

                mp_theta = planet.xy_bearing(midpoint.rect.left,
                                             midpoint.rect.top,
                                             midpoint.image.get_size(),
                                             x, y, point.image.get_size())
                if point.speed == 0:
                    point.speed = 0.001
                    point.theta = mp_theta
                else:
                    d = planet.distance(midpoint.rect.left,
                                        midpoint.rect.top,
                                        midpoint.image.get_size(),
                                        x, y, point.image.get_size())
                    xs = (point.speed * math.cos(point.theta) +
                          0.001 * math.cos(d/2) * math.cos(mp_theta))
                    ys = (point.speed * math.sin(point.theta) +
                          0.001 * math.cos(d/2) * math.sin(mp_theta))
                    point.speed = min(1, math.sqrt(xs*xs + ys*ys))
                    point.theta = math.atan2(ys, xs)
                
                theta, x2, y2 = planet.apply_bearing(point.speed, point.theta,
                                                     x, y,
                                                     point.image.get_size())
                point.theta = theta
                point.raw_coords = x2,y2
                point.rect.topleft = point.raw_coords

            points.clear(screen, background)
            points.draw(screen)

            midpoints.clear(screen, background)
            midpoints.draw(screen)
            
            pygame.display.flip()

            limit.tick()
Пример #36
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()

        for n in range(1):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            point.w = 10.#random.uniform(1,10)
            pygame.draw.circle(point.image, (255 - point.w*12,0,0), (5,5), 5)
            a = array([random.uniform(-1,1),
                       random.uniform(-1,1),
                       random.uniform(-1,1)])
            point.p = a / norm(a)
            print point.p
            point.v = zeros(3)
            point.rect = pygame.Rect((0,0), point.image.get_size())
            points.add(point)

        midpoints = pygame.sprite.Group()
        midpoint = pygame.sprite.Sprite()
        midpoint.image = pygame.Surface((10,10))
        pygame.draw.circle(midpoint.image, (0,255,0), (5,5), 5)
        midpoint.rect = pygame.Rect((0,0), midpoint.image.get_size())
        midpoints.add(midpoint)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True

            # join colliding points
            for point in points:
                for other in points:
                    if point == other:
                        continue
                    if math.acos(dot(point.p, other.p)) < 0.1:
                        d = other.p - point.p
                        if (abs(math.acos(dot(d, point.v))) < math.pi /2 and
                            abs(math.acos(dot(d, other.v))) > math.pi / 2):
                            point.p = array(planet.vector_weighted_average(
                                [point.p, other.p], [point.w, other.w]))
                            v = array(planet.vector_weighted_average(
                                [point.v, other.v], [point.w, other.w]))
                            point.v = (norm(point.v) + norm(other.v)) * v
                            point.w = point.w + other.w
                            pygame.draw.circle(point.image, (255 - point.w*12,0,0), (5,5), 5)
                            points.remove(other)

            # identify clusters of nearby points
            clusters = []
            for point in points:
                for other in points:
                    if point == other:
                        continue
                    if math.acos(dot(point.p, other.p)) < 0.5:
                        for c in clusters:
                            if point in c:
                                if not other in c:
                                    c.append(other)
                                break
                            elif other in c:
                                if not point in c:
                                    c.append(point)
                                break
                        else:
                            clusters.append([point, other])

            # repel clustered points from center of cluster
            midpoints.empty()
            seen = []
            for c in clusters:
                cluster = pygame.sprite.Sprite()
                cluster.image = pygame.Surface((10,10))
                pygame.draw.circle(cluster.image, (0,0,255), (5,5), 5)
                cluster.rect = pygame.Rect((0,0), cluster.image.get_size())
                p = planet.vector_weighted_average(
                    [point.p for point in c],
                    [1 for point in c])
                cluster.rect.topleft = planet.vector_to_xy(p,
                                                           cluster.image.get_size())
                midpoints.add(cluster)

                for point in c:
                    if norm(point.v) < 0.05:
                        point.v = 0.1 * planet.repel_from_point(point.p, p) / point.w
                        if norm(point.v > 0.15):
                            point.v = 0.15 * point.v / norm(point.v)
                    seen.append(point)

            # apply velocities 
            newpoints = []
            for point in points:
                # move or split isolated points
                if not point in seen:
                    if norm(point.v) < 0.05:
                        u = zeros(3)
                        u[min(range(len(a)), key=lambda i: abs(point.p[i]))] = 1
                        v = cross(point.p, u)
                        v = 0.01 * planet.rotate(v / norm(v), point.p,
                                                  random.uniform(0, 2*math.pi))
                        
                        if point.w < 0.25:
                            point.v = v / point.w
                        else:
                            point.w /= 2
                            point.v = v / point.w
                            
                            newpoint = pygame.sprite.Sprite()
                            newpoint.image = pygame.Surface((10,10))
                            row = random.randint(1, planet.row_count-1)
                            newpoint.w = point.w
                            pygame.draw.circle(point.image, (255 - point.w*12,0,0), (5,5), 5)
                            pygame.draw.circle(newpoint.image, (255 - newpoint.w*12,0,0), (5,5), 5)
                            newpoint.p = point.p
                            newpoint.v = -point.v
                            newpoint.rect = pygame.Rect((0,0), newpoint.image.get_size())
                            newpoints.append(newpoint)
                            
                point.p, point.v = planet.apply_velocity(point.p, point.v)
                if norm(point.v) < 0.01:
                    point.v = zeros(3)
                else:
                    point.v = 0.99 * point.v
                point.rect.topleft = planet.vector_to_xy(point.p,
                                                         point.image.get_size())

            points.add(newpoints)                

            # calculate overall midpoint
            midpoint.p = planet.vector_weighted_average(
                [point.p for point in points.sprites()],
                [point.w for point in points.sprites()])
            midpoint.rect.topleft = planet.vector_to_xy(midpoint.p,
                midpoint.image.get_size())

            midpoints.add(midpoint)

            points.clear(screen, background)
            points.draw(screen)

            midpoints.clear(screen, background)
            midpoints.draw(screen)
            
            pygame.display.flip()

            limit.tick(25)
Пример #37
0
def generatePlanet(system_intensity, system_id, i):
	global planet_list
	planet = Planet()
	planet.id = system_id + i
	planet.name = 'PLANET NAME ' + str(system_id + i)
	planet.orbit = i
	planet.position = []
	planet.size = random.choice(['small', 'medium', 'giant'])
	planet.setGravity()
	planet.setRadiation(system_intensity)
	planet.setAtmosphere()
	planet.setUsability()
	planet_list.append(planet)
Пример #38
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()

        for n in range(20):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            pygame.draw.circle(point.image, (255,0,0), (5,5), 5)
            row = random.randint(1, planet.row_count-1)
            a = array([random.uniform(-1) for i in range(3)])
            point.p = a / norm(a)
            point.theta = 0 if n == 0 else random.uniform(0, 2 * math.pi)
            point.v = zeros(3)
            point.rect = pygame.Rect((0,0), point.image.get_size())
            points.add(point)

        midpoints = pygame.sprite.Group()
        midpoint = pygame.sprite.Sprite()
        midpoint.image = pygame.Surface((10,10))
        pygame.draw.circle(midpoint.image, (0,255,0), (5,5), 5)
        midpoint.rect = pygame.Rect((0,0), midpoint.image.get_size())
        midpoints.add(midpoint)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True

            midpoint.p = planet.vector_weighted_average(
                [point.p for point in points.sprites()],
                [1 for point in points.sprites()])
            midpoint.rect.topleft = planet.vector_to_xy(midpoint.p,
                midpoint.image.get_size())

            speed = sum([norm(p.v) for p in points])
            for point in points:
                if not speed:
                    point.v = 0.1 * planet.repel_from_point(point.p, midpoint.p)
                point.p, point.v = planet.apply_velocity(point.p, point.v)
                if norm(point.v) < 0.001:
                    point.v = zeros(3)
                else:
                    point.v = 0.9 * point.v
                point.rect.topleft = planet.vector_to_xy(point.p,
                                                         point.image.get_size())

            points.clear(screen, background)
            points.draw(screen)

            midpoints.clear(screen, background)
            midpoints.draw(screen)
            
            pygame.display.flip()

            limit.tick()
Пример #39
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()

        for n in range(5):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            pygame.draw.circle(point.image, (255,0,0), (5,5), 5)
            row = random.randint(1, planet.row_count-1)
            a = array([random.uniform(-1) for i in range(3)])
            point.p = a / norm(a)
            point.theta = 0 if n == 0 else random.uniform(0, 2 * math.pi)
            u = zeros(3)
            u[min(range(len(a)), key=lambda i: abs(point.p[i]))] = 1
            v = cross(point.p, u)
            point.v = 0.01 * planet.rotate(v / norm(v), point.p,
                                           random.uniform(0, 2*math.pi))
            point.rect = pygame.Rect((0,0), point.image.get_size())
            points.add(point)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True
                        
            for point in points:
                point.p, point.v = planet.apply_velocity(point.p, point.v)
                point.rect.topleft = planet.vector_to_xy(point.p,
                                                         point.image.get_size())

            points.clear(screen, background)
            points.draw(screen)
            
            pygame.display.flip()

            limit.tick()
Пример #40
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()

        for n in range(5):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            pygame.draw.circle(point.image, (255,0,0), (5,5), 5)
            row = random.randint(1, planet.row_count-1)
            column = random.randint(0, planet.row_lengths[row]-1)
            point.raw_coords = planet.get_coordinates(row, column,
                                                      point.image.get_size())
            point.theta = random.uniform(0, 2 * math.pi)
            point.rect = pygame.Rect(point.raw_coords, point.image.get_size())
            points.add(point)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True
                        
            for point in points:
                x, y = point.raw_coords
                theta, x, y = planet.apply_heading(0.25, point.theta, x, y,
                                                   point.image.get_size())
                point.theta = theta
                point.raw_coords = x,y
                point.rect.topleft = point.raw_coords

            points.clear(screen, background)
            points.draw(screen)
            
            pygame.display.flip()

            limit.tick()
Пример #41
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()
        orients = pygame.sprite.Group()
        shapes = pygame.sprite.Group()

        for n in range(3):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            pygame.draw.circle(point.image, (255,0,0), (5,5), 5)

            # random location
            a = array([random.uniform(-1) for i in range(3)])
            point.p = a / norm(a)

            # best unit vector
            u = zeros(3)
            u[min(range(len(a)), key=lambda i: abs(point.p[i]))] = 1

            # random velocity vector
            v = cross(point.p, u)
            point.v = 0.01 * planet.rotate(v / norm(v), point.p,
                                           random.uniform(0, 2*math.pi))

            # random orienting point
            (o, ov) = planet.apply_velocity(point.p,
                                            0.05 * planet.rotate(v / norm(v),
                                                                 point.p,
                                                                 random.uniform(0, 2*math.pi)))
            point.o = pygame.sprite.Sprite()
            point.o.p = o
            point.o.image = pygame.Surface((6,6))
            pygame.draw.circle(point.o.image, (0,0,255), (3,3), 3)
            point.o.rect = pygame.Rect((0,0), point.o.image.get_size())
            orients.add(point.o)

            # polygon points
            point.shape = [(.1,.23),(.12,.43),(.13,.52),(.25,.54),
                           (.3,.43),(.43,.48),(.53,.31),(.48,.14),
                           (.5,.1)]
            
            point.rect = pygame.Rect((0,0), point.image.get_size())
            points.add(point)

        def add_shape_coords(coords, cmin, cmax, px, py):
            sprite = pygame.sprite.Sprite()
            sprite.image = pygame.Surface((cmax[0]-cmin[0],cmax[1]-cmin[1]))
            pygame.draw.polygon(sprite.image, (0,255,0),
                                [(c[0]-cmin[0], c[1]-cmin[1])
                                 for c in coords], 1)
            sprite.rect = pygame.Rect((px-sprite.image.get_width()/2,
                                       py-sprite.image.get_height()/2),
                                      sprite.image.get_size())
            shapes.add(sprite)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True

            shapes.empty()
            for point in points:
                point.p, point.v = planet.apply_velocity(point.p, point.v)
                point.o.p, ov = planet.apply_velocity(point.o.p, point.v)
                point.rect.topleft = planet.vector_to_xy(point.p,
                                                         point.image.get_size())
                point.o.rect.topleft = planet.vector_to_xy(point.o.p,
                                                           point.o.image.get_size())

                shape = Polygon(point.shape)
                c = shape.centroid.coords[0]

                coords = []
                for vertex in point.shape:
                    # find distance from centroid
                    d = math.sqrt(sum([(vertex[i]-c[i])*(vertex[i]-c[i])
                                       for i in range(2)]))
                    # find angle from local north
                    th = math.atan2(vertex[0]-c[0],vertex[1]-c[1])

                    # axis of rotation separating point from orientation point
                    u = cross(point.p, point.o.p)
                    u = u / norm(u)

                    # rotate point around it by d
                    p = planet.rotate(point.p, u, d)

                    # and then around point by -theta
                    p = planet.rotate(p, point.p, -th)

                    coords.append(planet.vector_to_xy(p))

                cmin, cmax = ranges(coords)
                px,py = planet.vector_to_xy(point.p)
                inproj = [planet.in_projection(px+x-(cmin[0]+cmax[0])/2,
                                               py+y-(cmin[1]+cmax[1])/2)
                          for (x,y) in coords]
                if all(inproj):
                    add_shape_coords(coords, cmin, cmax, px, py)
                else:
                    left = []
                    right = []
                    for c in coords:
                        (left if c[0] < planet.max_row/2 else right).append(c)
                    if (len(left) > 1):
                        cmin, cmax = ranges(left)
                        add_shape_coords(left, cmin, cmax, px, py)
                    if (len(right) > 1):
                        cmin, cmax = ranges(right)
                        add_shape_coords(right, cmin, cmax, px, py)

            points.clear(screen, background)
            orients.clear(screen, background)
            shapes.clear(screen, background)
            shapes.draw(screen)
            points.draw(screen)
            orients.draw(screen)
            
            pygame.display.flip()

            limit.tick()
Пример #42
0
Файл: TM.py Проект: zkbt/transit
class TM(Talker):
	'''Transit Model object handles generation of model transit light curves.
		(relies heavily on Jonathan Irwin's "eb" code, which is an updated
		implementation of the classic EBOP and JKTEBOP, available at:
			https://github.com/mdwarfgeek'''

	def __init__(self, planet=None, star=None, instrument=None, directory=None,depthassumedforplotting=None, **kwargs):
		'''Initialize the parameters of the model.'''

		# setup the talker
		Talker.__init__(self)

		# create an empty array of parameters for eb
		self.ebparams = np.zeros(eb.NPAR, dtype=np.double)

		# keep track of a depth for plotting, if necessary
		self.depthassumedforplotting=depthassumedforplotting


		# load the model, if possible, and if a directory was given
		self.directory = directory
		if directory is not None and planet is None:
			self.load(directory)
		else:
			# define the subsets of the parameters, maybe by falling to defaults
			if planet is None:
				planet = Planet()
			if star is None:
				star = Star()
			if instrument is None:
				instrument = Instrument()
			self.planet = planet
			self.star = star
			self.instrument = instrument


	def load(self, directory):
		'''Load parameters from directory.'''
		#self.directory = directory
		self.speak('loading TM from {0}'.format(directory))
		self.planet = Planet(directory=directory)
		self.star = Star(directory=directory)
		self.instrument = Instrument(directory=directory)

	def save(self, directory):
		'''Save parameters to directory.'''
		#self.directory = directory
		for x in (self.planet, self.star, self.instrument):
			x.save(directory)

	def linkLightCurve(self, transitlightcurve):
		'''Attach a model to a light curve, defining all the TM and TLC attributes.'''
		self.TLC = transitlightcurve
		self.TM = self
		self.TLC.TM = self
		self.TLC.TLC = self.TLC

	def linkRV(self, rvcurve):
		'''Attach a model to a radial velocity curve, defining all the TM and RVC attributes.'''
		self.RVC = rvcurve
		self.TM = self
		self.RVC.TM  = self
		self.RVC.RVC = self.RVC

	#@profile
	def set_ebparams(self):
		'''Set up the parameters required for eb. '''
		# These are the basic parameters of the model.
		self.ebparams[eb.PAR_J]      =  self.planet.surface_brightness_ratio  # J surface brightness ratio
		self.ebparams[eb.PAR_RASUM]  =  self.planet.rsum_over_a  # (R_1+R_2)/a
		self.ebparams[eb.PAR_RR]     =  self.planet.rp_over_rs  # R_2/R_1
		self.ebparams[eb.PAR_COSI]   =  self.planet.cosi  # cos i

		# Mass ratio is used only for computing ellipsoidal variation and
		# light travel time.  Set to zero to disable ellipsoidal.
		self.ebparams[eb.PAR_Q]      =  0#self.planet.q

		# Light travel time coefficient.
		#ktot = 55.602793  # K_1+K_2 in km/s
		#cltt = 1000*ktot / eb.LIGHT

		# Set to zero if you don't need light travel correction (it's fairly slow
		# and can often be neglected).
		self.ebparams[eb.PAR_CLTT]   =  0#cltt#*(self.planet.q.value == 0.0)      # ktot / c

		# Radiative properties of star 1.
		self.ebparams[eb.PAR_LDLIN1] = self.star.u1.value   # u1 star 1
		self.ebparams[eb.PAR_LDNON1] = self.star.u2.value  # u2 star 1
		self.ebparams[eb.PAR_GD1]    = self.star.gd.value     # gravity darkening, std. value
		self.ebparams[eb.PAR_REFL1]  = self.star.albedo.value      # albedo, std. value

		# Spot model.  Assumes spots on star 1 and not eclipsed.
		self.ebparams[eb.PAR_ROT1]   =  1.0# 0.636539  # rotation parameter (1 = sync.)
		self.ebparams[eb.PAR_FSPOT1] =  0.0       # fraction of spots eclipsed
		self.ebparams[eb.PAR_OOE1O]  =  0.0       # base spottedness out of eclipse
		self.ebparams[eb.PAR_OOE11A] =  0.0#0.006928  # *sin
		self.ebparams[eb.PAR_OOE11B] =  0.0 # *cos

		# PAR_OOE12* are sin(2*rot*omega) on star 1,
		# PAR_OOE2* are for spots on star 2.

		# Assume star 2 is the same as star 1 but without spots.
		self.ebparams[eb.PAR_LDLIN2] = self.ebparams[eb.PAR_LDLIN1]
		self.ebparams[eb.PAR_LDNON2] = self.ebparams[eb.PAR_LDNON1]
		self.ebparams[eb.PAR_GD2]    = self.ebparams[eb.PAR_GD1]
		self.ebparams[eb.PAR_REFL2]  = self.ebparams[eb.PAR_REFL1]

		# Orbital parameters.
		self.ebparams[eb.PAR_ECOSW]  =  self.planet.ecosw.value  # ecosw
		self.ebparams[eb.PAR_ESINW]  = self.planet.esinw.value  # esinw
		self.ebparams[eb.PAR_P]      = self.planet.period.value  # period
		self.ebparams[eb.PAR_T0]     = self.planet.t0.value + self.planet.dt.value # T0 (epoch of primary eclipse), with an offset of dt applied
		# OTHER NOTES:
		#
		# To do standard transit models (a'la Mandel & Agol),
		# set J=0, q=0, cltt=0, albedo=0.
		# This makes the secondary dark, and disables ellipsoidal and reflection.
		#
		# The strange parameterization of radial velocity is to retain the
		# flexibility to be able to model just light curves, SB1s, or SB2s.
		#
		# For improved precision, it's best to subtract most of the "DC offset"
		# from T0 and the time array (e.g. take off the nominal value of T0 or
		# the midtime of the data array) and add it back on at the end when
		# printing self.ebparams[eb.PAR_T0] and vder[eb.PAR_TSEC].  Likewise the period
		# can cause scaling problems in minimization routines (because it has
		# to be so much more precise than the other parameters), and may need
		# similar treatment.

	def stellar_rv(self, rvc=None, t=None):
		self.set_ebparams()

		# by default, will use the linked RVC, but could use a custom one (e.g. high-resolution for plotting), or just times
		if rvc is None:
			rvc = self.RVC

		if t is None:
			t = rvc.bjd

		# make sure the types are okay for Jonathan's inputs
		typ = np.empty_like(t, dtype=np.uint8)
		typ.fill(eb.OBS_VRAD1)

		rv = self.planet.semiamplitude.value*eb.model(self.ebparams, t, typ) + self.star.gamma.value
		assert(np.isfinite(rv).all())
		return rv

	#@profile
	def planet_model(self, tlc=None, t=None):
		'''Model of the planetary transit.'''
		self.set_ebparams()

		# by default, will use the linked TLC, but could use a custom TLC
		# 	 (e.g. a high-resolution one, for plotting)
		if tlc is None:
			tlc = self.TLC

		# if called with a "t=" keyword set, then will use those custom times
		if t is None:
			t = tlc.bjd

		# make sure the types are okay for Jonathan's inputs
		typ = np.empty_like(t, dtype=np.uint8)
		typ.fill(eb.OBS_MAG)

		# work in relative flux (rather than magnitudes) -- why did I do this?
		return 10**(-0.4*eb.model(self.ebparams, t, typ))

	##@profile
	def instrument_model(self, tlc=None):
		'''Model of the instrument.'''

		# by default, use the real TLC
		if tlc is None:
			tlc = self.TLC

		# use the instrument to spit out a corrective model
		return self.instrument.model(tlc)

	##@profile
	def model(self, tlc=None):
		'''Model including both instrument and planetary transit.'''

		# create the complete model, for either real or fake light curve
		return self.planet_model(tlc=tlc)*self.instrument_model(tlc=tlc)

	@property
	def parameters(self):
		'''Return a list of the parameters that are variable.'''
		try:
			assert(len(self._parameters) == len(self.floating))
			return self._parameters
		except:
			self.defineParameterList()
			return self._parameters

	@parameters.setter
	def parameters(self, **kwargs):
		pass

	def defineParameterList(self):
		'''Set up the parameter list, by pulling the variable parameters out of the subsets.'''

		# define a list containing the keys all the parameters that float
		self.floating = []
		list = []
		for x in (self.planet, self.star, self.instrument):
			d = x.__dict__
			for key in d.keys():
				try:
					if d[key].fixed == False:
						self.floating.append(key)
						list.append(d[key])
				except:
					pass
		self._parameters = np.array(list)

	def	fromArray(self, array):
		'''Use an input array to assign the internal parameter attributes.'''
		count = 0
		for parameter in self.parameters:
			parameter.value = array[count]
			count += 1
		#print count
		#print array
		assert(count > 0)

	def toArray(self):
		'''Define an parameter array, by pulling them out of the internal parameter attributes.'''
		list = []
		parinfolist = []
		for parameter in self.parameters:
			list.append(parameter.value)
			parinfolist.append(parameter.parinfo)
		return list, parinfolist

	def plotPhased(self, smooth=None, **kw):
		'''Plot the light curve model, phased with the planetary period.'''
		t_phased = self.planet.timefrommidtransit(self.smooth_phased_tlc.bjd)
		assert(len(t_phased) == len(self.model(self.smooth_phased_tlc)))

		toplot = self.planet_model(self.smooth_phased_tlc)
		if smooth is not None:
			cadence = np.mean(self.smooth_phased_tlc.bjd[1:] - self.smooth_phased_tlc.bjd[:-1])
			n = np.round(smooth/cadence).astype(np.int)
			kernel = np.ones(n)/n
			toplot = np.convolve(toplot, kernel, 'same')
		else:
			toplot = self.planet_model(self.smooth_phased_tlc)
		plt.plot(t_phased, toplot, **kw)
		'''KLUDGED COMMENTED OUT!'''
		#try:
		#	for phased in [self.line_phased[0], self.line_phased_zoom[0]]:
		#		phased.set_data(t_phased, self.model(self.smooth_phased_tlc))
		#except:
		#	self.line_phased = self.TLC.ax_phased.plot(t_phased,self.model(self.smooth_phased_tlc), **self.kw)
		#	self.line_phased_zoom = self.TLC.ax_phased_zoom.plot(t_phased, self.model(self.smooth_phased_tlc), **self.kw)'''

	def plotUnphased(self):
		'''Plot the light curve model, linear in time.'''
		t_unphased = self.smooth_unphased_tlc.bjd - self.planet.t0.value
		assert(len(t_unphased) == len(self.model(self.smooth_unphased_tlc)))
		try:
			for unphased in [self.line_unphased[0], self.line_unphased_zoom[0]]:
				unphased.set_data(t_unphased, self.model(self.smooth_unphased_tlc))
		except:
			self.line_unphased = self.TLC.ax_unphased.plot(t_unphased, self.model(self.smooth_unphased_tlc), **self.kw)
			self.line_unphased_zoom = self.TLC.ax_unphased_zoom.plot(t_unphased, self.model(self.smooth_unphased_tlc), **self.kw)


	def plotDiagnostics(self):
		'''Plot the light curve model, linear in time.'''
		t_unphased = self.smooth_unphased_tlc.bjd - self.planet.t0.value
		assert(len(t_unphased) == len(self.model(self.smooth_unphased_tlc)))

		#try:
		#	self.line_raw.set_data(t_unphased, self.model(self.smooth_unphased_tlc))
		#	self.line_corrected.set_data(t_unphased, self.planet_model(self.smooth_unphased_tlc))
		#	self.line_residuals.set_data(t_unphased, ppm*np.zeros_like(t_unphased))
		#	self.line_instrument.set_data(t_unphased, ppm*self.instrument_model(self.smooth_unphased_tlc))
		#except:
		# NOT USING?!?
		self.line_raw = self.TLC.ax_raw.plot(t_unphased, self.model(self.smooth_unphased_tlc), **kw)[0]
		self.line_corrected = self.TLC.ax_corrected.plot(t_unphased, self.planet_model(self.smooth_unphased_tlc), **kw)[0]
		self.line_residuals = self.TLC.ax_residuals.plot(t_unphased, ppm*np.zeros_like(t_unphased), **kw)[0]
		self.line_instrument = self.TLC.ax_instrument.plot(t_unphased, ppm*self.instrument_model(self.smooth_unphased_tlc), **kw)[0]

	def plot(self):
		'''Plot the model lines over the existing light curve structures.'''
		self.kw = {'color':self.TLC.colors['lines'], 'linewidth':3, 'alpha':1.0}
		self.plotPhased()
		self.plotUnphased()

		if self.depthassumedforplotting is None:
			self.depthassumedforplotting = self.planet.rp_over_rs.value**2

		# need to work on displaying the parameters...
		try:
			xtext = self.planet.duration/2.0*1.1
			posttransit = self.planet.timefrommidtransit(bjd) > self.planet.duration/2.0
			ytext = np.mean(self.model()[posttransit]) - self.planet.rp_over_rs**2/2.0
			instrument_string = "Instrumental Parameters"
			self.TLC.ax_raw.text(xtext, ytext, instrument_string)
		except:
			pass

	##@profile
	def deviates(self, p, fjac=None, plotting=False):
		'''Return the normalized deviates (an input for mpfit).'''

		# populate the parameter attributes, using the input array
		self.fromArray(p)

		# if necessary, plot the light curve along with this step of the deviates calculation
		status =0
		if plotting:
			self.TLC.LightcurvePlots()

		ok = (self.TLC.bad == 0).nonzero()

		devs = (self.TLC.flux[ok] - self.TM.model()[ok])/self.TLC.uncertainty[ok]

		# add limb darkening priors
		try:
			prioru1 = (self.star.u1.value - self.u1prior_value)/self.u1prior_uncertainty
			prioru2 = (self.star.u2.value - self.u2prior_value)/self.u2prior_uncertainty
			devs = np.append(devs, prioru1)
			devs = np.append(devs, prioru2)
			#print '==============================='
			#print 'u1: ({value} - {center})/{uncertainty}'.format(value = self.star.u1.value, center=self.u1prior_value, uncertainty =self.u1prior_uncertainty)
			#print 'u2: ({value} - {center})/{uncertainty}'.format(value = self.star.u2.value, center=self.u2prior_value, uncertainty =self.u2prior_uncertainty)

		except:
			pass

		# mpfit wants a list with the first element containing a status code
		return [status,devs]

	def applyLDpriors(self):
		self.speak('using atmosphere model as prior on LD coefficients')
		self.u1prior_value = self.star.u1.value + 0.0
		self.u2prior_value = self.star.u2.value + 0.0
		self.u1prior_uncertainty = self.star.u1.uncertainty + 0.0
		self.u2prior_uncertainty = self.star.u2.uncertainty + 0.0

	##@profile
	def lnprob(self, p):
		"""Return the log posterior, calculated from the TM.deviates function (which may have included some conjugate Gaussian priors.)"""



		chisq = np.sum(self.deviates(p)[-1]**2)/2.0
		N = np.sum(self.TLC.bad == 0)

		# sum the deviates into a chisq-like thing
		lnlikelihood = -N * np.log(self.instrument.rescaling.value) - chisq/self.instrument.rescaling.value**2
		if np.isfinite(lnlikelihood) == False:
			lnlikelihood = -1e9

		# initialize an empty constraint, which could freak out if there's something bad about this fit
		constraints = 0.0

		# loop over the parameters


		for parameter in self.parameters:

			# if a parameter is outside its allowed range, then make the constraint very strong!
			inside = (parameter.value < parameter.limits[1]) & (parameter.value > parameter.limits[0])
			try:
				assert(inside)
			except AssertionError:
				constraints -= 1e6

		# return the constrained likelihood
		return lnlikelihood + constraints

	def fastfit(self, **kwargs):
		self.fitter = LM(self, **kwargs)
		self.fitter.fit(**kwargs)

	def slowfit(self, **kwargs):
		self.fitter = MCMC(self, **kwargs)
		self.fitter.fit(**kwargs)

	def __repr__(self):
		return self.TLC.__repr__().replace('TLC', 'TM')
Пример #43
0
    def main_loop(self):

        planet = Planet(100,1,0)

        pygame.init()    

        screen = pygame.display.set_mode((planet.max_row,planet.row_count),
                                         HWSURFACE)
        pygame.display.set_caption('Planet')

        background = pygame.Surface(screen.get_size())
        background.fill((128,128,128))

        def in_bounds(x,y):
            return (x > planet.row_offsets[y] and
                    x < planet.row_offsets[y] + planet.row_lengths[y])

        background.lock()
        for y in range(0, screen.get_height()):
            for x in range(0, screen.get_width()):
                if in_bounds(x,y):
                    value = planet.rows[y][x - planet.row_offsets[y]]
                    background.set_at((x,y),(value,value,value))
        background.unlock()

        screen.blit(background, (0,0))

        points = pygame.sprite.Group()

        for n in range(5):
            point = pygame.sprite.Sprite()
            point.image = pygame.Surface((10,10))
            pygame.draw.circle(point.image, (255,0,0), (5,5), 5)
            row = planet.row_count/2
            column = planet.row_lengths[row]/2
            point.raw_coords = planet.get_coordinates(row, column,
                                                      point.image.get_size())
            point.rect = pygame.Rect(point.raw_coords, point.image.get_size())
            point.v = (0,0)
            points.add(point)

        def spread_influence(distance, row, column, limit):
            to_expand = []
            if limit:
                for (nrow,ncolumn) in planet.adjacent(row, column):
                    if not (int(nrow),int(ncolumn)) in distance:
                        distance[(int(nrow),int(ncolumn))] = limit
                        to_expand.append((int(nrow),int(ncolumn)))
                random.shuffle(to_expand)
            return (to_expand, limit-1)

        limit = pygame.time.Clock()

        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        done = True

            # every point contributes to potential
            potential_points = set()
            for point in points:
                x, y = point.raw_coords
                row, column = planet.get_row_column(x, y, point.image.get_size())
                expansion_sets = [([(row,column),], 5)]
                distance = dict()
                while len(expansion_sets) > 0:
                    next_sets = []
                    for (locations,radius) in expansion_sets:
                        for row, column in locations:
                            next_set = spread_influence(distance, row, column, radius)
                            if len(next_set[0]):
                                next_sets.append(next_set)
                    expansion_sets = next_sets
                for (row,column),d in distance.iteritems():
                    planet.rows[row][column] += 1 - 1/math.pow(d,2)
                    potential_points.add((row,column))
                point.raw_coords = x,y
                point.rect.topleft = point.raw_coords

            for row,column in potential_points:
                planet.rows[row][column] = 0

            points.clear(screen, background)
            points.draw(screen)
            
            pygame.display.flip()

            limit.tick()