Exemplo n.º 1
0
Arquivo: main.py Projeto: Clyff/sw-api
def planets_get(action):
    """Handles the access via GET Methods.

    Returns
    ------
    Response
        JSON Response of the planets. Or a message.
    """

    actions = ['view', 'list']

    if (action in actions):
        model = Planet()

        # JSON Response of the planets. Or A message in case there is any.
        if (action == 'list'):
            result = model.list()

            if (result is not None):
                return result, 200

            return "No Planets Stored", 200

        # JSON Response of the planet. Or a message if not found.
        elif (action == 'view'):
            data = request.args
            result = model.view(data)

            if (result is not None):
                return result, 200

            return "Planet not found", 404

    # A message if route not allowed.
    return "Action {} not allowed".format(action), 405
Exemplo n.º 2
0
 def test_coord(self):
     p = Planet(dist = 100, mov = 1)
     self.assertPairAlmostEqual(p.coord(), (0, 100))
     p.advance(90)
     self.assertPairAlmostEqual(p.coord(), (100, 0))
     p.advance(180)
     self.assertPairAlmostEqual(p.coord(), (-100, 0))
Exemplo n.º 3
0
def map_system(orbits_array):
    planets_dict = {}

    for parent, child in map(lambda x: x.split(')'), orbits_array):
        if parent not in planets_dict:
            planets_dict[parent] = Planet(parent, [])
        if child not in planets_dict:
            planets_dict[child] = Planet(child, [])

        planets_dict[child].parent = planets_dict[parent]
        planets_dict[parent].planets.append(planets_dict[child])

    return list(filter(lambda p: p.parent is None,
                       planets_dict.values())), planets_dict
Exemplo n.º 4
0
Arquivo: main.py Projeto: Clyff/sw-api
def planets_post(action):
    """Handles the access via POST Methods.

    Returns
    ------
    Response, None
        JSON Response of the planets. Or a message.
    """

    actions = ['create', 'update', 'delete']

    if (action in actions):
        model = Planet()
        data = request.form

        # JSON Response of the planet created. Or a message in case of error.
        if (action == 'create'):
            result = model.create(data)

            if (isinstance(result, str)):
                return result, 400

            return result, 200

        # JSON Response of the planet updated. Or a message in case of error.
        elif (action == 'update'):
            result = model.update(data)

            if (result is not None):
                return result, 200

            return "Planet {} not found".format(data.get("nome")), 404

        # A message whether the deletion succeed or not.
        elif (action == 'delete'):
            result = model.delete(data)

            if (result is not None):
                return result, 200

            return "Planet {} not found".format(data.get("nome")), 404

    # A message if route not allowed.
    return "Action {} not allowed".format(action), 405
Exemplo n.º 5
0
 def test_moves(self):
     mov = 23
     p = Planet(dist = 100, mov = mov)
     p.advance()
     self.assertEqual(p.angle, mov)
     p.advance(3)
     self.assertEqual(p.angle, mov*4)
Exemplo n.º 6
0
 def weather(self):
     if self.collinearWithSun():
         return Drought()
     elif Planet.collinear(self.planets[0], self.planets[1],
                           self.planets[2]):
         return Optimal()
     elif self.includeSun():
         dists = [
             distance(self.planets[i].coord(),
                      self.planets[(i + 1) % 3].coord()) for i in range(3)
         ]
         return Rainy(sum(dists))
     else:
         return Unknown()
Exemplo n.º 7
0
 def __init__(self):
     self.planets = [
         Planet(1000, -5),  # Vulcano
         Planet(2000, 3),  # Betasoide
         Planet(500, 1)
     ]  # Ferengi
# color scheme where 3 colors are necessary
colors3 = ['#002fa7','deepskyblue','#C1DBE6']

# set up dry and normal (wet) Earths
# dry atm composition
f_o2 = 0.2095 # [vmr] O2
f_co2 = 400.e-6 # [vmr] #CO2
# to ensure atm components add up to 1
f_n2 = 1. - f_o2 - f_co2 # [vmr] N2
# composition array X [H2, He, N2, O2, CO2]
X = np.array([0.,0.,f_n2,f_o2,f_co2])
T_strat = 200 # [K]
p_surf_earth = 1.01325e5 # [Pa]
RH_earth = 0.77 # []
# wet Earth
Earth = Planet(1,T_earth,T_strat,p_surf_earth,X,1)
Earth_atm = atm_pro.Atm(Earth,RH_earth)
# integrate to get atmospheric profile
Earth_atm.set_up_atm_pro()
# dry Earth
Earth_dry = Planet(1,T_earth,T_strat,p_surf_earth,X,1)
Earth_atm_dry = atm_pro.Atm(Earth_dry,0.)
# integrate to get atmospheric profile
Earth_atm_dry.set_up_atm_pro()

################################################################
# MIE SCATTERING
# Figure 2 & methods in Section 3.2
################################################################

print('\n-----------------------------------------------\n'
Exemplo n.º 9
0
 def __init__(self, dist, angle):
     Planet.__init__(self, dist, 0)
     self.angle = angle
Exemplo n.º 10
0
    def test_collinear(self):
        p1 = PlanetDummyCoord((10, 0))
        p2 = PlanetDummyCoord((10, 3))
        p3 = PlanetDummyCoord((10, 10))

        self.assertTrue(Planet.collinear(p1, p2, p3))
Exemplo n.º 11
0
 def __init__(self, coord):
     d = distance(coord, (0, 0))
     angle = degrees(atan2(coord[0], coord[1]))
     Planet.__init__(self, d, 0)
     self.angle = angle
Exemplo n.º 12
0
def user_run(R_p,M_p,T_surf,T_strat,p_surf,f_h2,f_he,f_n2,f_o2,f_co2,
             RH_surf,type_obs,is_best_params,is_limiting_params,
             tau_for_obs,r,w,t_mix,t_convert,alpha,is_G,is_M,m_aero,lambda_stell,
             u_so2_for_obs,pH,oc_mass,S_outgass,name):

    # tell user what's up
    print('\nALIEN SULFUR CYCLE INITIATED.')
    print('calculating critical decay timescale of S(IV) (t_SIV*) for observable sulfur.\n')

    # confirm inputs are correct
    if is_best_params==True and is_limiting_params==True:
        raise Exception('You have set both is_best_params & is_limiting_params as True. You can only set up to one of these booleans as True.')
    if is_G==True and is_M==True:
        raise Exception('You have set both is_G & is_M as True. You can only set up to one of these booleans as True.')

    # now proceed
    # make Planet instance
    atm_comp = np.array([f_h2,f_he,f_n2,f_o2,f_co2]) # do not adjust this ordering
    planet = Planet(R_p,T_surf,T_strat,p_surf,atm_comp)
    # make Atm instance
    atm = atm_pro.Atm(planet,RH_surf)
    # set up atmosphere structure
    atm.set_up_atm_pro()

    # add outgassing as planet mass dependent
    # set up sulfur model parameters
    if is_best_params:
        # vertical optical depth for aerosol observation
        tau_for_obs = 0.1 # []
        # average H2SO4-H2O aerosol size in meters
        r = 1e-6 # [m]
        # weight fraction H2SO4 in H2SO4-H2O aerosol mixture
        w = 0.75 # [kg/kg]
        # mixing timescale between troposphere and stratosphere in seconds
        t_mix = s_in_yr # [s]
        # conversion timescale of SO2 to H2SO4 in seconds
        t_convert = 30*s_in_day # [s]
        # ratio of mixing ratio of SO2 of tropopause to surface
        alpha = 0.1 # []
    elif is_limiting_params:
        # vertical optical depth for aerosol observation
        tau_for_obs = 0.1 # []
        # average H2SO4-H2O aerosol size in meters
        r = 1e-7 # [m]
        # weight fraction H2SO4 in H2SO4-H2O aerosol mixture
        w = 0.75 # [kg/kg]
        # mixing timescale between troposphere and stratosphere in seconds
        t_mix = s_in_yr # [s]
        # conversion timescale of SO2 to H2SO4 in seconds
        t_convert = 1.7*s_in_day # [s]
        # adjust timescales if M star
        if is_M:
            t_convert = 1.25*s_in_day # [s]
        # ratio of mixing ratio of SO2 of tropopause to surface
        alpha = 1. # []

    # make Sulfur_Cycle instance
    S_cyc = sulfur.Sulfur_Cycle(atm,type_obs,tau_for_obs,r,w,t_mix,t_convert,
                                alpha,is_G,is_M,m_aero,lambda_stell,
                                u_so2_for_obs)

    # see shape of ocean parameters inputted
    is_single_pH = False
    is_single_oc_mass = False
    try:
        len(pH)
    except TypeError:
        is_single_pH = True

    try:
        len(oc_mass)
    except TypeError:
        is_single_oc_mass = True

    # if vary both ocean pH and size
    # make a grid to have all possible combinations
    if not is_single_pH and not is_single_oc_mass:
        oc_mass,pH = np.meshgrid(oc_mass,pH)

    # calculate S in ocean for atm S observation
    S_cyc.calc_oc_S(oc_mass,pH)
    # calculate t_SIV_crit
    t_SIV_crit = S_cyc.calc_t_SIV(S_outgass)

    # update user that run worked
    print('successful run for planet %s.\n'%name)

    # SAVE RESULTS

    # make directory for saving results
    usr_results_dir = './my_results/'
    os.makedirs(usr_results_dir, exist_ok=True)

    # flatten arrays if have 2D arrays
    if not is_single_pH and not is_single_oc_mass:
        pH = pH.flatten()
        oc_mass = oc_mass.flatten()
        t_SIV_crit = t_SIV_crit.flatten()


    # output planetary & model parameters
    fname_pl = usr_results_dir + name + '_params.txt'

    f = open(fname_pl,'w')
    f.write('PLANET PARAMETERS\n\n')
    f.write('R\t\t%1.3E m\n'%atm.planet.R)
    f.write('M\t\t%1.3E kg\n'%atm.planet.M)
    f.write('T_surf\t\t%1.3F K\n'%T_surf)
    f.write('T_strat\t\t%1.3F K\n'%T_strat)
    f.write('p_surf_dry\t%1.3E Pa\n'%p_surf)
    f.write('f_h2_dry\t%1.3F\n'%f_h2)
    f.write('f_he_dry\t%1.3F\n'%f_he)
    f.write('f_n2_dry\t%1.3F\n'%f_n2)
    f.write('f_o2_dry\t%1.3F\n'%f_o2)
    f.write('f_co2_dry\t%1.3F\n'%f_co2)
    f.write('RH_surf\t\t%1.3F\n'%RH_surf)
    f.write('p_surf\t\t%1.3E Pa\n\n\n'%atm.planet.p_surf)

    f.write('MODEL PARAMETERS\n\n')
    f.write('type_obs\t\t%s\n'%type_obs)
    if type_obs=='aero':
        f.write('tau_for_obs\t\t%1.2E\n'%S_cyc.tau)
        f.write('r\t\t\t%1.2E m\n'%S_cyc.r)
        f.write('w\t\t\t%1.2F kg/kg\n'%S_cyc.w)
        f.write('t_mix\t\t\t%1.3E s\n'%S_cyc.t_mix)
        f.write('t_convert\t\t%1.3E s\n'%S_cyc.t_convert)
        f.write('m_aero\t\t\t%1.2F, %1.2F i\n'%(S_cyc.m_aero.real,S_cyc.m_aero.imag))
        f.write('alpha\t\t\t%1.2F\n'%S_cyc.alpha)
        f.write('lambda_stell\t\t%1.3E m\n'%S_cyc.lambda_stell)
        f.write('S_outgass\t\t%1.3E kg S/yr'%S_cyc.m_outgass_SIV)
    elif type_obs=='gas':
        f.write('u_so2_for_obs\t\t%1.3E kg/m2'%S_cyc.u_so2)
    f.close()

    # output results
    # use pandas to make writing out to csv easy
    if is_single_pH and is_single_oc_mass:
        results = np.array([[pH,oc_mass,t_SIV_crit[0]]])
    elif is_single_pH:
        results = np.zeros((oc_mass.shape[0],3))
        results[:,0].fill(pH)
        results[:,1] = oc_mass
        results[:,2] = t_SIV_crit
    elif is_single_oc_mass:
        results = np.zeros((pH.shape[0],3))
        results[:,0] = pH
        results[:,1].fill(oc_mass)
        results[:,2] = t_SIV_crit
    else:
        results = np.zeros((pH.shape[0],3))
        results[:,0] = pH
        results[:,1] = oc_mass
        results[:,2] = t_SIV_crit
    # print(results.shape)
    results_df = pd.DataFrame(results, columns=['pH','ocean_mass_earth','t_SIV*_yr'])
    fname_t_SIV = usr_results_dir + name + '_results.csv'
    results_df.to_csv(fname_t_SIV,index=False)

    # tell user where results are saved
    print('planet parameters for run saved under:')
    print('\t %s'%fname_pl)
    print('results of t_SIV* vs ocean parameters for run saved under:')
    print('\t %s\n\n'%fname_t_SIV)


    return S_cyc
Exemplo n.º 13
0
import pytest

from src.planet import Planet
from src.planet_mapper import map_system

planetArray = Planet("COM", [
    Planet("B", [
        Planet("C", [
            Planet("D", [
                Planet("E", [
                    Planet("F", []),
                    Planet("J", [Planet("K", [Planet("L", [])])])
                ]),
                Planet("I", []),
            ])
        ]),
        Planet("G", [Planet("H", [])]),
    ])
])

input = [
    "COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K",
    "K)L"
]


@pytest.mark.parametrize("test_input, expected", [(input, planetArray)])
def test_count_orbits_calculates_correct_number_of_orbits(
        test_input, expected):
    planets = map_system(test_input)
    assert planets.toJSON() == planetArray.toJSON()
Exemplo n.º 14
0
 def planet(self):
     p = Planet(self)
     return p