def convert(self):
        """
        return values from raw_values that are converted to units consistent with output units - energy and annual
        """
        if self.definition == 'absolute':
            if self.time_unit is None:
                self.time_unit = 'year'
            self.values = UnitConverter.unit_convert(
                self.raw_values,
                unit_from_num=self.energy_unit,
                unit_from_den=self.time_unit,
                unit_to_num=cfg.calculation_energy_unit,
                unit_to_den='year')
            self.values = util.remove_df_levels(self.values,
                                                cfg.removed_demand_levels,
                                                agg_function='mean')
            if self.demand_tech_unit_type == 'service demand':
                self.values = UnitConverter.unit_convert(
                    self.values,
                    unit_from_num=self.unit,
                    unit_to_num=self.service_demand_unit)
            self.absolute = True

        else:
            self.values = self.raw_values.copy()
            self.absolute = False
 def convert(self):
     """
     convert raw_values to model currency and capacity (energy_unit/time_step)
     """
     model_energy_unit = cfg.calculation_energy_unit
     self.values = UnitConverter.unit_convert(self.raw_values, unit_from_den=self.energy_unit,unit_to_den=model_energy_unit)
     if self.definition == 'absolute':
         self.values = UnitConverter.currency_convert(self.values, self.currency, self.currency_year)
         self.absolute = True
     else:
         self.absolute = False
예제 #3
0
    def convert_cost(self):
        """
        convert raw_values to model currency and energy
        """

        self.values = UnitConverter.unit_convert(
            self.raw_values,
            unit_from_den=self.cost_denominator_unit,
            unit_to_den=self.unit_to)
        self.values = UnitConverter.currency_convert(self.values,
                                                     self.currency,
                                                     self.currency_year)
 def convert(self):
     """
     return values from raw_values that are converted to units consistent with output units
     """
     if self.definition == 'absolute':
         if self.is_numerator_service:
             # if the numerator is service, definition has to be flipped in order to make the numerator an energy unit
             self.values = 1 / self.raw_values
             numerator_unit = self.denominator_unit
             denominator_unit = self.numerator_unit
             self.flipped = True
         else:
             self.values = self.raw_values
             numerator_unit = self.numerator_unit
             denominator_unit = self.denominator_unit
             self.flipped = False
         self.values = UnitConverter.unit_convert(
             self.values,
             unit_from_num=numerator_unit,
             unit_from_den=denominator_unit,
             unit_to_num=cfg.calculation_energy_unit,
             unit_to_den=self.service_demand_unit)
         self.absolute = True
     else:
         self.values = self.raw_values.copy()
         self.absolute = False
예제 #5
0
 def convert(self):
     model_energy_unit = cfg.calculation_energy_unit
     model_time_step = cfg.getParam('time_step')
     if self.time_unit is not None:
         # if sales has a time_unit, then the unit is energy and must be converted to capacity
         self.values = UnitConverter.unit_convert(self.values, unit_from_num=self.capacity_or_energy_unit,
                                         unit_from_den=self.time_unit, unit_to_num=model_energy_unit,
                                         unit_to_den=model_time_step)
     else:
         # if sales is a capacity unit, the model must convert the unit type to an energy unit for conversion ()
         unit_from_num = self.capacity_or_energy_unit + "_" + model_time_step
         self.values = UnitConverter.unit_convert(self.values,
                                         unit_from_num=unit_from_num,
                                         unit_from_den=model_time_step,
                                         unit_to_num=model_energy_unit,
                                         unit_to_den=model_time_step)
 def convert_units(self):
     if self.name is not None:
         unit_factor = UnitConverter.unit_convert(
             1,
             unit_from_den=self.energy_unit,
             unit_to_den=cfg.calculation_energy_unit)
         self.values *= unit_factor
예제 #7
0
파일: master.py 프로젝트: pouyana/satgen
 def master_inp_cont_gen(self,db_tuple):
     """
     Creates the master inp content dict
     """
     un_cnv=UnitConverter()
     result = {}
     for t in self.get_name_vars():
         if t not in ["init_date", "final_date" , "init_semiMajorAxis", "name", "id", "final_id", "final_semiMajorAxis", "final_eccentricity" , "init_eccentricity"]:
             result[t]=un_cnv.rad_to_deg(db_tuple[self.get_i(t)])
         if t in ["init_semiMajorAxis", "final_semiMajorAxis"]:
             result[t]=un_cnv.m_to_km(db_tuple[self.get_i(t)])
         if t in ["init_date", "final_date"]:
             result[t]=self.format_date(db_tuple[self.get_i(t)])
         if t in ["name", "final_eccentricity", "init_eccentricity"]:
             result[t]=db_tuple[self.get_i(t)]
     return result
예제 #8
0
 def convert(self):
     if self.input_type == 'total':
         self.values = UnitConverter.unit_convert(self.raw_values,
                                                  unit_from_num=self.unit,
                                                  unit_to_num=self.unit_to)
     else:
         self.values = self.raw_values
 def convert(self):
     """converts energy units to model energy units and service units to subsector service demand units"""
     self.values = UnitConverter.unit_convert(
         self.raw_values,
         unit_from_num=self.energy_unit,
         unit_from_den=self.denominator_unit,
         unit_to_num=cfg.calculation_energy_unit,
         unit_to_den=self.service_demand_unit)
예제 #10
0
파일: config.py 프로젝트: PlanetHunt/satgen
 def __init__(self, db, log_level="ERROR"):
     logger = Logger(log_level)
     self.log = logger.get_logger()
     self.conf = {}
     self.db = db
     self.db_id = 0
     self.unit_lib = UnitConverter()
     self.config_dict = ConfigDict()
 def convert(self):
     """
     convert raw_values to model currency and capacity (energy_unit/time_step)
     """
     model_energy_unit = cfg.calculation_energy_unit
     model_time_step = cfg.getParam('time_step')
     if hasattr(self, 'time_unit') and self.time_unit is not None:
         # if a cost has a time_unit, then the unit is energy and must be converted to capacity
         self.values = UnitConverter.unit_convert(self.raw_values, unit_from_den=self.capacity_or_energy_unit, unit_from_num=self.time_unit, unit_to_den=model_energy_unit, unit_to_num=model_time_step)
     else:
         # if a cost is a capacity unit, the model must convert the unit type to an energy unit for conversion ()
         unit_from_den = self.capacity_or_energy_unit + "_" + model_time_step
         self.values = UnitConverter.unit_convert(self.raw_values, unit_from_den=unit_from_den, unit_from_num=model_time_step, unit_to_den=model_energy_unit, unit_to_num=model_time_step)
     if self.definition == 'absolute':
         self.values = UnitConverter.currency_convert(self.values, self.currency, self.currency_year)
         self.absolute = True
     else:
         self.absolute = False
예제 #12
0
 def convert(self):
     """
     convert values to model currency and capacity (energy_unit/time_step)
     """
     if self.values is not None:
         model_energy_unit = cfg.calculation_energy_unit
         model_time_step = cfg.getParam('time_step')
         if self.time_unit is not None:
             self.values = UnitConverter.unit_convert(self.values/self.input_timestep, unit_from_num=self.capacity_or_energy_unit,
                                             unit_from_den=self.time_unit, unit_to_num=model_energy_unit,
                                             unit_to_den=model_time_step)
         else:
             unit_from_num = self.capacity_or_energy_unit + "_" + model_time_step
             self.values = UnitConverter.unit_convert(self.values/self.input_timestep,
                                                      unit_from_num=unit_from_num,
                                                      unit_from_den=model_time_step,
                                                      unit_to_num=model_energy_unit,
                                                      unit_to_den=model_time_step)
 def convert(self):
     """
     return values from raw_values that are converted to units consistent with output units
     """
     if self.definition == 'absolute':
         self.values = UnitConverter.unit_convert(self.raw_values,
                                         unit_from_num=self.input_unit, unit_to_num=self.output_unit)
         self.absolute = True
     else:
         self.values = self.raw_values.copy()
         self.absolute = False
 def convert_cost(self):
     """
     convert raw_values to model currency and capacity (energy_unit/time_step)
     """
     if self.demand_tech_unit_type == 'service demand':
         if self.tech_time_unit is None:
             self.time_unit = 'year'
         self.values = UnitConverter.unit_convert(
             self.raw_values,
             unit_from_num=self.tech_time_unit,
             unit_from_den=self.unit,
             unit_to_num=self.stock_time_unit,
             unit_to_den=self.service_demand_unit)
     else:
         self.values = copy.deepcopy(self.raw_values)
     if self.definition == 'absolute':
         self.values = UnitConverter.currency_convert(
             self.values, self.currency, self.currency_year)
         self.absolute = True
     else:
         self.absolute = False
예제 #15
0
    def __init__(self, dispatch_feeders, dispatch_geography, dispatch_geographies, scenario):
        # Todo, this doesn't seem necessary because we can put these things in the config
        # #TODO replace 1 with a config parameter
        # for col, att in util.object_att_from_table('DispatchConfig', 1):
        #     setattr(self, col, att)
        self.node_config_dict = dict()

        for supply_node in util.csv_read_table('DispatchNodeConfig', 'supply_node', return_iterable=True):
            self.node_config_dict[supply_node] = DispatchNodeConfig(supply_node)

        self.set_dispatch_orders()
        # self.dispatch_window_dict = dict(util.csv_read_table('DispatchWindows')) # todo doesn't seem used
        self.curtailment_cost = UnitConverter.unit_convert(0, unit_from_den='megawatt_hour',unit_to_den=cfg.calculation_energy_unit)
        self.unserved_capacity_cost = UnitConverter.unit_convert(10000.0, unit_from_den='megawatt_hour',unit_to_den=cfg.calculation_energy_unit)
        self.dist_net_load_penalty = UnitConverter.unit_convert(15000.0, unit_from_den='megawatt_hour',unit_to_den=cfg.calculation_energy_unit)

        # this bulk penalty is mostly for transmission
        self.bulk_net_load_penalty = UnitConverter.unit_convert(5000.0, unit_from_den='megawatt_hour',unit_to_den=cfg.calculation_energy_unit)
        self.ld_upward_imbalance_penalty = UnitConverter.unit_convert(150.0, unit_from_den='megawatt_hour',unit_to_den=cfg.calculation_energy_unit)
        self.ld_downward_imbalance_penalty = UnitConverter.unit_convert(50.0, unit_from_den='megawatt_hour',unit_to_den=cfg.calculation_energy_unit)
        self.dispatch_feeders = dispatch_feeders
        self.feeders = ['bulk'] + dispatch_feeders
        self.dispatch_geography = dispatch_geography
        self.dispatch_geographies = dispatch_geographies
        self.stdout_detail = getParamAsBoolean('stdout_detail', 'opt')
        self.transmission = dispatch_transmission.DispatchTransmission(cfg.transmission_constraint, scenario)

        self.solve_kwargs = {"keepfiles": False, "tee": False}
예제 #16
0
파일: config.py 프로젝트: pouyana/satgen
 def __init__(self, db, log_level="ERROR"):
     #logger
     logger = Logger(log_level)
     self.log = logger.get_logger()
     #empty conf
     self.conf = {}
     #database
     self.db = db
     self.db_id = 0
     #unit library
     self.unit_lib = UnitConverter()
     #configuration dictionary
     self.config_dict = ConfigDict()
 def convert(self):
     """
     convert raw_values to model currency and capacity (energy_unit/time_step)
     """
     self.values = UnitConverter.currency_convert(self.values,
                                                  self.currency,
                                                  self.currency_year)
     model_energy_unit = cfg.calculation_energy_unit
     model_time_step = cfg.getParam('time_step')
     if self.time_unit is not None:
         # if a cost has a time_unit, then the unit is energy and must be converted to capacity
         self.values = UnitConverter.unit_convert(
             self.values,
             unit_from_den=self.self.capacity_or_energy_unit,
             unit_from_num=self.time_unit,
             unit_to_den=model_energy_unit,
             unit_to_num=model_time_step)
     else:
         self.values = UnitConverter.unit_convert(
             self.values,
             unit_from_den=self.capacity_or_energy_unit + "_" +
             model_time_step,
             unit_to_den=model_energy_unit)
 def convert_and_remap(self, unit_type, stock_unit):
     """convert service demand to stock unit for stocks defined as service demand"""
     if unit_type == 'service demand':
         self.remap(map_to='int_values',
                    converted_geography=GeoMapper.demand_primary_geography,
                    fill_timeseries=False)
         self.int_values = UnitConverter.unit_convert(
             self.int_values,
             unit_from_num=self.unit,
             unit_to_num=stock_unit)
         self.unit = stock_unit
         self.current_data_type = self.input_type
         self.projected = False
     else:
         raise ValueError(
             "should not have called this function for this demand stock unit type"
         )
예제 #19
0
def test_convert_scalar_to_all():
    from testing import value_eq
    from unit_converter import UnitConverter

    eV_to = {
        'J': 1.60217646e-19,
        'Ha': 0.03674932439858279,
        'Ry': 0.07349864879716558,
        'eV': 1.0,
        'kcal_mol': 23.0605419446755,
        'kJ_mol': 96.48533350089092,
        'K': 11604.505934630948,
        'degC': 11331.355934630948,
        'degF': 20428.440682335706,
    }

    v = UnitConverter.convert_scalar_to_all('eV', 1.0)

    for unit in eV_to.keys():
        assert (value_eq(v[unit], eV_to[unit]))
예제 #20
0
 def __init__(self,
              db,
              log_level="ERROR",
              stela_file="stela.json",
              step_file="stela_step.json",
              start_file="stela_start.json",
              config_file="config.json"
              ):
     logger = Logger(log_level)
     self.log = logger.get_logger()
     self.convert = UnitConverter(log_level)
     try:
         stjsha = open(stela_file)
         ststha = open(start_file)
         stspha = open(step_file)
         confha = open(config_file)
     except IOError as e:
         print "One (more) of the config files is not avaialbe."
         print e
         raise
     try:
         self.stjs_sections = json.load(stjsha)["sections"]
         self.stst_sections = json.load(ststha)["sections"]
         self.stsp_sections = json.load(stspha)["sections"]
         self.config = json.load(confha)["config"]
     except ValueError as e:
         print "One (more) of the config files is not valid json."
         print e
         raise
     stjsha.close()
     ststha.close()
     stspha.close()
     confha.close()
     self.db = DB(str(self.config["project"]["base"] + db))
     self.combination_option = []
     self.db_list = {}
     self.multiparentage = []
     self.needed_elements = []
예제 #21
0
 def set_max_min_flex_loads(self, flex_pmin, flex_pmax):
     self.flex_load_penalty_short = UnitConverter.unit_convert(cfg.getParamAsFloat('flex_load_penalty_short', 'opt'), unit_from_den='megawatt_hour', unit_to_den=cfg.calculation_energy_unit)
     self.flex_load_penalty_long = UnitConverter.unit_convert(cfg.getParamAsFloat('flex_load_penalty_long', 'opt'), unit_from_den='megawatt_hour', unit_to_den=cfg.calculation_energy_unit)
     if self.has_flexible_load:
         self.max_flex_load = flex_pmax.squeeze().to_dict()
         self.min_flex_load = flex_pmin.squeeze().to_dict()
예제 #22
0
파일: sara.py 프로젝트: PlanetHunt/satgen
 def __init__(self, sara_path, db, default_dir_path):
     self.set_sara_path(sara_path)
     self.set_default_dir(default_dir_path)
     self.set_db(db)
     self.uc = UnitConverter()
예제 #23
0
class Config:

    """
    Read STELA XML configurations, create the config files and add the satelite
    in database. This module is only generate only STELA compatible data.
    To get data out of database user should use or change the database package.
    """

    def __init__(self,
                 db,
                 log_level="ERROR",
                 stela_file="stela.json",
                 step_file="stela_step.json",
                 start_file="stela_start.json",
                 config_file="config.json"
                 ):
        logger = Logger(log_level)
        self.log = logger.get_logger()
        self.convert = UnitConverter(log_level)
        try:
            stjsha = open(stela_file)
            ststha = open(start_file)
            stspha = open(step_file)
            confha = open(config_file)
        except IOError as e:
            print "One (more) of the config files is not avaialbe."
            print e
            raise
        try:
            self.stjs_sections = json.load(stjsha)["sections"]
            self.stst_sections = json.load(ststha)["sections"]
            self.stsp_sections = json.load(stspha)["sections"]
            self.config = json.load(confha)["config"]
        except ValueError as e:
            print "One (more) of the config files is not valid json."
            print e
            raise
        stjsha.close()
        ststha.close()
        stspha.close()
        confha.close()
        self.db = DB(str(self.config["project"]["base"] + db))
        self.combination_option = []
        self.db_list = {}
        self.multiparentage = []
        self.needed_elements = []

    def get_value(self, name):
        """
        Gets the value of given element by name.

        Args:
                name (str)

        Kwargs:
                None

        Returns:
                different
        """
        element = self.find_element_by_name(name, self.needed_elements)[0]
        return element["value"]

    def add_edge_length(self, a, b):
        """
        Adds the edges toghether.

        Args:
                a,b (float)

        Kwargs:
                None

        Returns:
                tuple
        """
        return tuple(sum(x) for x in zip(a, b))

    def calculate_drag_area(self, edge_tuple):
        """
        Calculates the drag area with the given tuple.

        Args:
                  edge_tuple (tuple)

        Kwargs:
                  None

        Returns:
                  float
        """
        area = 0
        for i in itertools.combinations(edge_tuple, 2):
            area = ((i[0] * i[1]) * 2) + area
        return float(area / 4)

    def convert_to_tuple(self, tuple_str):
        """
        Converts the given tuple string to a tuple python object.

        Args:
                tuple_str (str)

        Kwargs:
                None

        Returns:
                tuple
        """
        return literal_eval(tuple_str)

    def do_steps(self):
        """
        Create the steps from the json step files. Please be cautious how you
        fill file. The application will stop working if the values here are
        not set correctly.
        If you want to add something to the combination you should edit the
        stela_step.json file as follows:
        {
        "name": "semiMajorAxis",
        "start": 6600,
        "end": 7200,
        "step": 50,
        "unit": "km"
        }

        Args:
                None

        Kwargs:
                None

        Returns:
                dict
        """
        steps = self.stsp_sections
        all_step_config = dict()
        for k in steps:
            if(k["end"] < k["start"]):
                print "The 'end' smaller than 'start', please change the '" + \
                    str(k["name"]) + "' settings in the stela_step.json file."
                raise ValueError
            tmp_list = list()
            all_step_config[k["name"]] = tmp_list
            start = k["start"]
            end = k["end"]
            if(k["type"] == "tuple"):
                start = self.convert_to_tuple(start)
                end = self.convert_to_tuple(end)
                tmp_list.append(str(start))
                while(start != end):
                    start = self.add_edge_length(
                        start, self.convert_to_tuple(k["step"]))
                    tmp_list.append(str(start))
            else:
                if(not (k["unit"] ==
                        self.find_element_by_name(
                        k["name"],
                        self.needed_elements)[0]["unit"])):
                    start = self.convert.convert(k["unit"],
                                                 self.find_element_by_name(
                        k["name"],
                        self.needed_elements)[0]["unit"],
                        float(start))
                    step = self.convert.convert(k["unit"],
                                                self.find_element_by_name(
                        k["name"],
                        self.needed_elements)[0]["unit"],
                        float(k["step"]))
                    end = self.convert.convert(k["unit"],
                                               self.find_element_by_name(
                        k["name"],
                        self.needed_elements)[0]["unit"],
                        float(k["end"]))
                else:
                    start = float(start)
                    step = float(k["step"])
                tmp_list.append(float(start))
                while float(start) < float(end):
                    start = float(start) + float(step)
                    tmp_list.append(start)
        return all_step_config

    def get_combinations(self):
        """
        Returns all the possible combinations from the given dict
        it uses product function.

        Args:
                None

        Kwargs:
                None

        Returns:
                itertools.product
        """
        all_steps = self.do_steps()
        self.combination_option = [k for k, v in all_steps.items()]
        self.combination_option.append("name")
        self.combination_option.append("date")
        result = itertools.product(*(v for k, v in all_steps.items()))
        return result

    def get_combination_options(self):
        """
        Returns the options from the combinations.

        Args:
               None

        Kwargs:
               None

        Returns:
               list
        """
        if(len(self.combination_option) == 0):
            self.get_combinations()
        return self.combination_option

    def generate_name(self, size_of=8):
        """
        Generates Random UPPERCASE names for the satellite taken from
        http://stackoverflow.com/q/2257441

        Args:
                size (int)

        Kwargs:
                None

        Returns:
                str
        """
        return ''.join(random.choice(string.ascii_uppercase + string.digits)
                       for _ in range(size_of))

    def get_path(self):
        """
        Finds the right pass to save the xml file created.

        Args:
                  None

        Kwargs:
                  None

        Returns:
                  None
        """
        if(not os.path.isdir(self.config["sim"]["path"])):
            os.mkdir(self.config["sim"]["path"])
        return self.config["sim"]["path"] + "/" + \
            [item for item in self.needed_elements
             if item["name"] == "name"][0]["value"] + "_a_sim.xml"

    def agument_database(self):
        """
        Adds the varaible data to the database, which not comming with start
        data. The qus are always the second in the database object.

        Args:
                  None

        Kwargs:
                  None

        Retruns:
                  None
        """
        for i in self.db_list.items():
            qu = i[1]
            qu = qu["qu"][:-1] + ")"
            self.db_list[i[0]]["qu"] = qu

    def get_element_index(self, element, json_list):
        """
        Finds an element index in a given list.

        Args:
                element (dict)
                json_list (list)

        Kwargs:
                None

        Returns:
                int (index within)
        """
        return [i for i, val in enumerate(
            json_list) if element["name"] == val["name"]][0]

    def exchange_element(self, element, json_list):
        """
        Exchanges the element with the same element given in a list
        and also the database.

        Args:
                  element (dict)
                  json_list (list)

        Kwargs:
                  None

        Returns:
                  None
        """
        index = self.get_element_index(element, json_list)
        self.set_new_value_in_db_list(element)
        json_list.pop(index)
        json_list.append(element)

    def set_new_value_in_db_list(self, element):
        """
        Finds the element index in the database element dict.

        Args:
                element (dict)

        Kwargs:
                None

        Returns:
                int
        """
        index = [item for item in self.db_list.items()
                 if element["database_tag"] == item[0]][0]
        index2 = [i for i, val in enumerate(
            list(index)[1]["names"]) if element["name"] == val][0]
        values = list(index[1]["values"])
        values[index2] = element["value"]
        self.db_list[index[0]]["values"] = tuple(values)

    def generate_json_stub(self, json_file, **vars):
        """
        Generate a json stub or appends to it for the given paramater names.

        Args:
                json_file (str) address of the given json file

        Kwargs:
                parameters name (str)

        Returns:
                None
        """

    def agument_config(self, combination):
        """
        Infulence the STELA settings with the created combinations.

        Args:
                  combination (list)

        Kwargs:
                  None

        Returns:
                  None
        """
        counter = 0
        for o in self.combination_option:
            if(o == "Length"):
                new_value = combination[counter]
                self.update_value("dragArea", self.calculate_drag_area(
                    self.convert_to_tuple(new_value)))
                self.update_value("reflectingArea", self.calculate_drag_area(
                    self.convert_to_tuple(new_value)))
                counter = counter + 1
            else:
                new_value = combination[counter]
                self.update_value(o, new_value)
                counter = counter + 1

    def update_value(self, name, value, unit=None):
        """
        Update a value in the needed elements.

        Args:
                name (str)
                value (float)
                unit (str)

        Kwargs:
                None

        Returns:
                None
        """
        element = self.find_element_by_name(name, self.needed_elements)[0]
        if(unit):
            if(not unit == self.find_element_by_name(
                    name, self.needed_elements)[0]["unit"]):
                value = self.convert.convert(
                    unit, self.find_element_by_name(
                        name, self.needed_elements)[0]["unit"], float(value))
        element["value"] = value
        self.exchange_element(element, self.needed_elements)

    def add_element_to_db_tuple(self, element):
        """
        Adds the newly generated satelite to the database.

        Args:
                element (dict)

        Kwargs:
                None

        Returns:
                None
        """
        if("database_tag" in element and "value" in element):
            if(element["database_tag"] != ""):
                if(element["database_tag"] not in list
                   (self.db_list.keys())):
                    self.db_list[element["database_tag"]] = {}
                    self.db_list[element["database_tag"]][
                        "names"] = (str(element["xml_tag"]),)
                    if(type(element["value"]) != str):
                        self.db_list[element["database_tag"]][
                            "values"] = (element["value"],)
                    else:
                        self.db_list[element["database_tag"]][
                            "values"] = (str(element["value"]),)
                    self.db_list[element["database_tag"]]["qu"] = "(?,"
                else:
                    if(element["xml_tag"] not in
                       self.db_list[element["database_tag"]]["names"]):
                        self.db_list[element["database_tag"]]["names"] =\
                            self.db_list[
                            element["database_tag"]]["names"] +\
                            (str(element["xml_tag"]),)
                        if(type(element["value"]) !=
                           str):
                            self.db_list[
                                element["database_tag"]]["values"] =\
                                self.db_list[
                                    element["database_tag"]]["values"] + \
                                (element["value"],)
                        else:
                            self.db_list[
                                element["database_tag"]]["values"] =\
                                self.db_list[
                                element["database_tag"]]["values"] + \
                                (str(element["value"]),)
                        self.db_list[
                            element["database_tag"]]["qu"] =\
                            self.db_list[element["database_tag"]]["qu"] + "?,"

    def recursive_xml_generate(self, root, parent=""):
        """
        Generate the recursive xml element with from root object.

        Args:
                root (Element)
                parent (ElementTree)

        Kwargs:
                None

        return:
                string
        """
        if(root["parent"] == ""):
            ETS = ET.Element(root["xml_tag"])
            self.root = ETS
        else:
            ETS = ET.SubElement(parent, root["xml_tag"])
        if(len(root["default_parms"]) > 0):
            for i in root["default_parms"]:
                if(type(i) == dict):
                    ETS.set(list(i.keys())[0], list(i.values())[0])
        if(root["unit"] != ""):
            ETS.set("unit", root["unit"])
        if("value" in root):
            ETS.text = str(root["value"])
        if("children_obj" in root):
            if(len(root["children_obj"]) > 0):
                for i in root["children_obj"]:
                    self.recursive_xml_generate(i, ETS)
        ET.ElementTree(self.root).write(
            self.get_path(),
            encoding="UTF-8",
            xml_declaration=True)

    def sort_by_parents_children(self):
        """
        Sorts the list descending with parent child relation.

        Args:
                None

        Kwargs:
                None

        Returns:
                element
        """
        root = [
            item for item in self.needed_elements if item["parent"] == ""][0]
        self.find_children_element(root, self.needed_elements)
        root.pop("children", None)
        root["children_obj"] = sorted(
            root["children_obj"], key=itemgetter("sort_number"),
            reverse=False)
        return root

    def find_children_element(self, element, json_list):
        """
        finds and adds element as childeren to their parents.

        Args:
                element (dict)
                json_list (list)

        Kwargs:
                None

        Returns:
                None
        """
        if("children" in element):
            if(len(element["children"]) > 0):
                element['children_obj'] = []
                while(len(element["children"]) > 0):
                    child = element["children"].pop()
                    element_tmp = self.find_element_by_name(child, json_list)
                    if(len(element_tmp) > 0):
                        element_t = element_tmp[0]
                        element["children_obj"].append(element_t)
                        element["children_obj"] = sorted(
                            element["children_obj"], key=itemgetter(
                                "sort_number"),
                            reverse=False)
                        self.find_children_element(element_t, json_list)
            else:
                element.pop("children", None)

    def find_element_by_name(self, name, json_list):
        """
        Find an element by the given name. searches in alias.

        Args:
                name (str)
                json_list (list)

        Kwargs:
                None

        Returns:
                dict
        """
        result = [item for item in json_list if item["name"] == name]
        if (len(result) == 0):
            return [item for item in json_list if name in item["alias"]]
        else:
            return result

    def multi_parentage(self, element):
        """
        Solves the multiparentage problem, when one exists.

        Args:
                element (dict)

        Kwargs:
                None

        Returns:
                Boolean
        """
        if(type(element["parent"]) == list and len(element["parent"]) > 1):
            self.multiparentage.append(element)
            return True
        else:
            return False

    def solve_multi_parentage(self):
        """
        Solves the multiparentage problem. by adding multiparent element
        with only the right parent.


        Args:
                needed_elements list

        Kwargs:
                None

        Returns:
                None
        """
        for element in self.multiparentage:
            a = [item for item in self.needed_elements if item[
                "parent"] in element["parent"]]
            if(len(a) > 0):
                element["parent"] = a[0]["parent"]
                self.needed_elements.append(element)
                self.add_element_to_db_tuple(element)

    def parents_exists(self, element, full_list):
        """
        Searches in the full element list for the parents of the given
        element and add it to the given list.

        Args:
                element (dict)
                needed_elements (list)
                full_list (list)

        Kwargs:
                None

        Returns:
                None
        """
        if(element["parent"] != ""):
            if(not self.element_exists(element, self.needed_elements)):
                self.needed_elements.append(element)
            parent_element = self.find_element_by_name(
                element["parent"], full_list)
            if(len(parent_element) > 0):
                if(not self.element_exists(parent_element[0],
                                           self.needed_elements)):
                    self.needed_elements.append(parent_element[0])
                self.parents_exists(
                    parent_element[0], full_list)

    def find_parents(self, element):
        """
        Finds the element's parent if any exists.

        Args:
                element (dict)

        Kwargs:
                None

        Returns:
                list (Empty if False)
        """
        if(len(element["parent"]) > 0):
            if(type(element["parent"] != list)):
                return element["parent"]
            else:
                return [element["parent"]]
        else:
            return []

    def add_name_to_combination(self, combination):
        """
        Adds the name to the combination

        Args:
                combination (tuple)

        Kwargs:
                None

        Returns:
                 tuple (new combination)
        """
        combination_list = list(combination)
        combination_list.append(self.generate_name())
        return tuple(combination_list)

    def get_date_now(self):
        """
        Returns the date (now) in STELA acceptable format.

        Args:
                None

        Kwargs:
                None

        Returns:
                str (date)
        """
        return strftime("%Y-%m-%dT%H:%M:%S.000", gmtime())

    def add_date_to_combination(self, combination):
        """
        Update the date for the given STELA sim object.

        Args:
                combination (tuple)

        Kwargs:
                None

        Returns:
                tuple (new combination)
        """
        combination_list = list(combination)
        date = self.get_date_now()
        combination_list.append(date)
        return tuple(combination_list)

    def element_exists(self, element, json_list):
        """
        Checks if an element exists in the given json_list.

        Args:
                element (dict)
                json_list (list)

        Kwargs:
                None

        Returns:
                Boolean
        """
        return (len([item for item in json_list if item["name"] ==
                     element["name"]]) > 0)

    def generate_xml(self):
        """
        Generate the xml file for stela from given data.

        Args:
                None

        Kwargs:
                None

        Returns:
                Boolean
        """
        if(len(self.needed_elements) == 0):
            self.generate_foundation_xml()
            xml_feed = self.sort_by_parents_children()
            self.recursive_xml_generate(xml_feed)
        else:
            xml_feed = self.sort_by_parents_children()
            self.recursive_xml_generate(xml_feed)

    def generate_foundation_xml(self):
        """
        Generate the xml file for stela from given data.

        Args:
                None

        Kwargs:
                None

        Returns:
                Boolean
        """
        for i in self.stst_sections:
            element = self.find_element_by_name(
                i["name"], self.stjs_sections)[0]
            if("value" in i):
                element["value"] = i["value"]
            self.parents_exists(element, self.stjs_sections)
            if(not self.multi_parentage(element)):
                parent_element = self.find_element_by_name(
                    element["parent"], self.stjs_sections)[0]
                self.add_element_to_db_tuple(element)
            if(not self.element_exists(parent_element, self.needed_elements)):
                self.needed_elements.append(element)
                self.add_element_to_db_tuple(element)
        self.solve_multi_parentage()
        self.generate_xml()
예제 #24
0
파일: config.py 프로젝트: pouyana/satgen
 def convert_to_xml(self):
     """
     Creates an xml configuration from the cfg file
     """
     unit_converter = UnitConverter()
     dictio = self.config_dict.get_dict()
     sort_space_object = self.config_dict.get_sort_space_object()
     unit_dict = self.config_dict.get_unit_dict()
     self.set_abstract_item(
         "General",
         "Solar Activity Type",
         self.get_solar_activity_type())
     self.set_abstract_item(
         "General",
         "Iteration Data",
         "")
     self.set_abstract_item(
         "General",
         "Atmospheric Model",
         "")
     self.set_stela_version("2.5.0")
     leosimulation = ET.Element('LEOSimulation')
     leosimulation.set("version", str(self.get_stela_version()))
     stelaversion = ET.SubElement(leosimulation, 'STELAVersion')
     stelaversion.text = "2.5.1"
     spaceobject = ET.SubElement(leosimulation, dictio["Space Object"])
     self.parse_elements(
         spaceobject,
         self.get_conf()["Space Object"],
         unit_dict,
         sort_space_object,
         dictio,
         ["Edge Length", "Constant Drag Coef"])
     ephemerisman = ET.SubElement(leosimulation, 'EphemerisManager')
     ephemerisman.set('version', str(self.get_stela_version()))
     initstate = ET.SubElement(ephemerisman, 'initState')
     bulletin = ET.SubElement(initstate, 'bulletin')
     bulletin.set('version', str(self.get_stela_version()))
     date = strftime("%Y-%m-%dT%H:%M:%S.000", gmtime())
     self.set_initial_date(date)
     date_element = ET.SubElement(bulletin, 'date')
     date_element.text = date
     bulletin_type = str(dictio["Type " + self.get_type_of_sim()])
     sim_type_element = ET.SubElement( bulletin, bulletin_type)
     for param in self.config_dict.get_conf_sim(sim_type_element.tag):
         tmp_el = ET.SubElement(sim_type_element, str(dictio[param]))
         if param in unit_dict:
             tmp_el.set('unit', str(unit_dict[param]))
             if(unit_dict[param]=="rad"):
                 tmp_el.text = str(
                         unit_converter.deg_to_rad(
                             float(self.get_abstract_item(
                                 "Initial Bulletin", param.title()))))
             elif(unit_dict[param]=="m"):
                 tmp_el.text = str(
                         unit_converter.km_to_m(
                             float(self.get_abstract_item(
                                 "Initial Bulletin", param.title()))))
             else:
                 tmp_el.text = str(
                     self.get_abstract_item(
                         "Initial Bulletin", param.title()))
         else:
             tmp_el.text = str(
                 self.get_abstract_item("Initial Bulletin", param.title()))
     finishstate = ET.SubElement(ephemerisman, 'finalState')
     self.parse_elements(
          leosimulation,
          self.get_conf()["General"],
          unit_dict,
          self.config_dict.get_sort_general(),
          dictio,
         [
         "Stela Version",
         "Edge Length",
         "Solar Activity Type",
         "Atmospheric Model" ,
         "Earth Tesseral Switch",
         "Iteration Data"])
     result = ""
     if(sys.version_info) > (2,7):
         result = prettify(leosimulation)
     else:
         result = ET.tostring(leosimulation)
     return result
예제 #25
0
파일: config.py 프로젝트: pouyana/satgen
class Config:
    def __init__(self, db, log_level="ERROR"):
        #logger
        logger = Logger(log_level)
        self.log = logger.get_logger()
        #empty conf
        self.conf = {}
        #database
        self.db = db
        self.db_id = 0
        #unit library
        self.unit_lib = UnitConverter()
        #configuration dictionary
        self.config_dict = ConfigDict()


    def set_value(self, value, keyword):
        """
        Set the value of different config options with the help
        of the defined functions.
        """
        if(keyword in ["Edge Length", "Edge length"]):
            self.set_edge_length(value)
        if(keyword in ["Model", "model"]):
            self.set_model(value)
        if(keyword in ["Mass", "mass"]):
            self.set_mass(value)
        if(keyword in ["Simulation duration", "Simulation Duration"]):
            self.set_sim_dur(value)
        if(keyword in ["Ephemeris step", "Ephemeris step"]):
            self.set_ephemeris_step(value)
        if(keyword in ["Difference between terrestrial and universal time", "Difference between terrestrial and universal time"]):
            self.set_diff_terrestrial_universal_time(value)
        if(keyword in ["a (Semi major axis)", "A (Semi Major Axis)"]):
            self.set_semi_major_axis(value)
        if(keyword in ["lambdaEq"]):
            self.set_lambdaEq(value)
        if(keyword in ["Stela Version"]):
            self.set_stela_version(value)
        if(keyword in ["Author"]):
            self.set_author(self)
        if(keyword in ["Comment"]):
            self.set_comment(value)
        if(keyword in ["Integration Step", "Integration step"]):
            self.set_int_step(value)
        if(keyword in ["Atmospheric drag switch", "Atmospheric Drag Switch"]):
            self.set_atmos_drag_switch(value)
        if(keyword in ["Drag quadrature Points", "Drag Quadrature Points"]):
            self.set_quad_points(value)
        if(keyword in ["Atmospheric Drag Recompute step", "Atmospheric Drag Recompute Step"]):
            self.set_atmos_drag_recom_step(value)
        if(keyword in ["Solar radiation pressure switch", "Solar Radiation Pressure Switch"]):
            self.set_solar_rad_pres_switch(value)
        if(keyword in ["Solar radiation pressure quadrature Points", "Solar Radiation Pressure Quadrature Points"]):
            self.set_solar_rad_pres_quad_points(value)
        if(keyword in ["Iterative Mode"]):
            self.set_iter_method(value)
        if(keyword in ["Sun switch", "Sun Switch"]):
            self.set_sun_switch(value)
        if(keyword in ["Moon switch", "Moon Switch"]):
            self.set_moon_switch(value)
        if(keyword in ["Zonal order", "Zonal Order"]):
            self.set_zonal_order(value)
        if(keyword in ["Earth Tesseral switch", "Earth Tesseral Switch"]):
            self.set_earth_tesseral_switch(value)
        if(keyword in ["Tesseral min period", "Tesseral Min Period"]):
            self.set_tesseral_min_period(value)
        if(keyword in ["Reentry Altitude", "Reentry altitude"]):
            self.set_reentry_alt(value)
        if(keyword in ["Drag Area","Drag area"]):
            self.set_drag_area(value)
        if(keyword in ["Reflecting Area", "Reflecting area"]):
            self.set_reflect_area(value)
        if(keyword in ["Reflectivity Coefficient", "Reflectivity coefficient"]):
            self.set_reflect_coef(value)
        if(keyword in ["Orbit Type", "Orbit type"]):
            self.set_orbit_type(value)
        if(keyword in ["Name"]):
            self.set_space_object_name(value)
        if(keyword in ["Date", "Initial Date"]):
            self.set_initial_date(value)
        if(keyword in ["Zp (Perigee altitude)", "Zp (Perigee Altitude)", "Zp (Perigee)"]):
            self.set_perigee_alt(value)
        if(keyword in ["Za (Apogee altitude)", "Za (Apogee Altitude)", "Za (Apogee)"]):
            self.set_perigee_alt(value)
        if(keyword in ["I (Inclination)"]):
            self.set_incl(value)
        if(keyword in ["RAAN (Right Ascension of Ascending Node)", "RAAN (Right ascension of ascending Node)"]):
            self.set_raan(value)
        if(keyword in ["W (Argument Of Perigee)", "w (Argument Of Perigee)"]):
            self.set_arg_perigee(value)
        if(keyword in ["M (Mean Anomaly)", "M (Mean anomaly)"]):
            self.set_mean_anomaly(value)
        if(keyword in ["E (Eccentricity)", "e (Eccentricity)"]):
            self.set_eccentricity(value)
        if(keyword in ["Atmospheric model", "Atmospheric Model"]):
            self.set_atoms_model(value)
        if(keyword in ["longitudeTFE"]):
            self.set_longitudeTFE(value)
        if(keyword in ["epochTFE"]):
            self.set_epochTFE(value)
        if(keyword in ["eX"]):
            self.set_eX(value)
        if(keyword in ["eY"]):
            self.set_eY(value)
        if(keyword in ["iX"]):
            self.set_iX(value)
        if(keyword in ["iY"]):
            self.set_iY(value)
        if(keyword in ["x"]):
            self.set_x(value)
        if(keyword in ["y"]):
            self.set_y(value)
        if(keyword in ["z"]):
            self.set_z(value)
        if(keyword in ["vX"]):
            self.set_vX(value)
        if(keyword in ["vY"]):
            self.set_vY(value)
        if(keyword in ["vZ"]):
            self.set_vZ(value)
        if(keyword in ["Solar Activity Type"]):
            self.set_solar_activity_type(value)
        if(keyword in ["AP Constant Equivalent Solar Activity"]):
            self.set_ap_constant_solar_act(value)
        if(keyword in ["F10.7 Constant Equivalent Solar Activity"]):
            self.set_f107(value)
        if(keyword in ["Function Value Accuracy"]):
            self.set_func_value_accu(value)
        if(keyword in ["Simulation Minus Expiring Duration"]):
            self.set_sim_minus_exp(value)
        if(keyword in ["Iteration Method"]):
            self.set_iter_method(value)
        if(keyword in ["Expiring Duration"]):
            self.set_exp_dur(value)
        if(keyword in ["Iterative Mode"]):
            self.set_iter_mode(value)
            

    def set_abstract_item(self, section, option, value):
        """
        Adds items to the config array
        """
        if section in self.conf.keys():
            self.conf[section][option] = value
        else:
            self.conf[section] = {}
            self.conf[section][option] = value

    def get_abstract_item(self, section, option):
        """
        Gives the item value back.
        """
        try:
            return self.conf[section][option]
        except KeyError as e:
            self.log.warning("Key or value not found please try again ")
            return None

    def get_conf(self):
        """
        Gives the conf dict back
        """
        return self.conf

    def set_conf(self, conf):
        """
        Sets the conf file from the conf dict
        """
        self.conf = conf

    def get_config_general(self):
        """
        Gives the General configuration back
        """
        try:
            return self.config["General"]
        except KeyError as e:
            self.log.error("Key General not existant.")
            return None

    def set_longitudeTFE(self, longi):
        """
        Sets the longitudeTFE in km
        """
        self.set_abstract_item("Initial Bulletin", "longitudeTFE", longi)

    def get_longitudeTFE(self):
        """
        Gets the longitudeTFE
        """
        self.get_abstract_item("Initial Bulletin", "longitudeTFE")

    def set_epochTFE(self, epoch):
        """
        Sets the Epoch, which is same as date here
        """
        self.set_abstract_item("Initial Bulletin", "epochTFE", epoch)

    def get_epochTFE(self):
        """
        Gets the Epoch
        """
        self.set_abstract_item("Initial Bulletin", "epochTFE")

    def get_tesseral_min_period(self):
        """
        Gets the Tesseral Min Period
        """
        return self.get_abstract_item("General", "Tesseral min period")

    def set_tesseral_min_period(self, period):
        """
        Sets the Tesseral Min Period
        """
        self.set_abstract_item("General", "Tesseral min period")

    def set_model(self, model):
        """
        Set Model in General
        """
        self.set_abstract_item("General", "Model", model)

    def get_model(self):
        """
        Gives Model back
        """
        return self.get_abstract_item("General", "Model")

    def get_author(self):
        """
        Gives the Author back
        """
        return self.get_abstract_item("General", "Author")

    def set_author(self, author):
        """
        Set the autor of config
        """
        self.set_abstract_item("General", "Author", author)

    def get_comment(self):
        """
        Get the comment field
        """
        return self.get_abstract_item("General", "Comment")

    def set_comment(self, comment):
        """
        Set the comment
        """
        self.set_abstract_item("General", "Comment", comment)

    def get_sim_dur(self):
        """
        Get the Simulation duration in years.
        """
        return self.get_abstract_item("General", "Simulation duration")

    def set_sim_dur(self, dur):
        """
        Set the Simulation durition in years.
        """
        self.set_abstract_item("General", "Simulation duration", dur)

    def get_ephemeris_step(self):
        """
        Get ephemeris Step in seconds.
        """
        return self.get_abstract_item("General", "Ephemeris step")

    def set_ephemeris_step(self, step=86400):
        """
        Sets ephemeris Step in seconds.
        Default value is 86400, which is a day.
        """
        self.set_abstract_item("General", "Ephemeris step", step)

    def get_diff_terrestrial_universal_time(self):
        """
        Get the difference Difference between
        terrestrial and universal time in seconds
        """
        return self.get_abstract_item(
            "General",
            "Difference between terrestrial and universal time")

    def set_diff_terrestrial_universal_time(self, time):
        """
        Set the difference Difference between
        terrestrial and universal time in seconds
        """
        self.set_abstract_item(
            "General",
            "Difference between terrestrial and universal time",
            time)

    def get_int_step(self):
        """
        Get the integration step of the simulation config in seconds
        """
        return self.get_abstract_item("General", "Integration Step")

    def set_int_step(self, step=86400):
        """
        Set the integration step of the simulation, per default 86400s, a day
        """
        self.set_abstract_item("General", "Integration Setp")

    def get_atmos_drag_switch(self):
        """
        Get the atmospheric drag switch, Boolean.
        """
        return self.get_abstract_item("General", "Atmospheric drag switch")

    def set_atmos_drag_switch(self, switch=True):
        """
        Set the atmospheric drag, default True
        """
        self.set_abstract_item("General", "Atmospheric drag switch", switch)

    def get_quad_points(self):
        """
        Returns the Drag quadrature Points
        """
        return self.get_abstract_item("General", "Drag quadrature Points")

    def set_quad_points(self, points=33):
        """
        Sets Drag quadrature Points, default value is 33
        """
        self.set_abstract_item("General", "Drag quadrature Points", points)

    def get_atmos_drag_recom_step(self):
        """
        Retruns the Atmospheric Drag Recompute step
        """
        return self.get_abstract_item(
            "General",
            "Atmospheric Drag Recompute step")

    def set_atmos_drag_recom_step(self, step=1):
        """
        Sets the Atmospheric Drag Recompute step, default is 1.
        """
        self.set_atmos_drag_recom_step(
            "General",
            "Atmospheric Drag Recompute step",
            step)

    def get_solar_rad_pres_switch(self):
        """
        Returns the Solar radiation pressure switch, Boolean
        """
        return self.get_abstract_item(
            "General",
            "Solar radiation pressure switch")

    def set_solar_rad_pres_switch(self, switch=True):
        """
        Sets the Solar radiation pressure switch, Per default True
        """
        self.set_abstract_item(
            "General",
            "Solar radiation pressure switch",
            switch)

    def get_solar_rad_pres_quad_points(self):
        """
        Gets the Solar radiation pressure quadrature Points
        """
        return self.get_abstract_item(
            "General",
            "Solar radiation pressure quadrature Points")

    def set_solar_rad_pres_quad_points(self, points=11):
        """
        Sets Solar radiation pressure quadrature Points, per default 11
        """
        self.set_abstract_item(
            "General",
            "Solar radiation pressure quadrature Points",
            points)

    def get_sun_switch(self):
        """
        Gets the Sun switch, Boolean.
        """
        return self.get_abstract_item("General", "Sun Switch")

    def set_sun_switch(self, switch=True):
        """
        Sets the Sun switch value, per default True.
        """
        self.set_abstract_item("General", "Sun switch", switch)

    def get_moon_switch(self):
        """
        Gets the Sun switch value, Boolean
        """
        return self.get_abstract_item("General", "Moon switch")

    def set_moon_switch(self, switch=True):
        """
        Sets the Moon Switch, per default Boolean True
        """
        self.set_abstract_item("General", "Moon switch", switch)

    def get_zonal_order(self):
        """
        Gets the Zonal order
        """
        return self.get_abstract_item("General", "Zonal order")

    def set_zonal_order(self, order=7):
        """
        Sets the Zonal order, Per default 7
        """
        self.set_abstract_item("General", "Zonal order", order)

    def get_earth_tesseral_switch(self):
        """
        Get the Earth Tesseral Switch, Boolean
        """
        return self.get_abstract_item("General", "Earth Tesseral switch")

    def set_earth_tesseral_switch(self, switch=False):
        """
        Sets the Earth Tesseral switch, per default False
        """
        self.set_abstract_item("General", "Earth Tesseral switch", switch)

    def get_reentry_alt(self):
        """
        Gets the Reentry Altitude
        """
        return self.get_abstract_item("General", "Reentry Altitude")

    def set_reentry_alt(self, alt=120):
        """
        Sets the Reentry Altitude, default 120Km, can't be less than 80.
        """
        while(alt < 80):
            alt = raw_input("The Altitude must be between 140 - 80 KM")
        self.set_abstract_item("General", "Reentry Altitude", alt)

    def set_mass(self, mass):
        """
        Set the mass of the space object in kilo grams
        """
        self.set_abstract_item("Space Object", "Mass", mass)

    def get_mass(self):
        """
        Gives the Mass of the Object back.
        """
        return self.get_abstract_item("Space Object", "Mass")

    def get_edge_length(self):
        """
        Gets the length of a Cube edge, in m
        """
        return self.get_abstract_item("Space Object", "Edge Length")

    def set_edge_length(self, length):
        """
        Set the length of a the Cube Edge in m
        """
        self.set_abstract_item("Space Object", "Edge Length", length)
        self.db.update_value("spaceObject", "edgeLength", self.get_db_id(), length)
        self.set_drag_area()
        self.set_reflect_area()

    def get_drag_area(self):
        """
        Get the Drag area of a space object, in m^2
        """
        result = self.get_abstract_item("Space Object", "Drag Area")
        if(result):
            return result
        else:
            self.set_drag_area()
            return self.get_drag_area()

    def get_reflect_area(self):
        """
        Get the Reflecting area of the Cube
        """
        result = self.get_abstract_item("Space Object", "Reflecting Area")
        if(result):
            return result
        else:
            self.set_reflect_area()
            return self.get_reflect_area()

    def set_reflect_area(self, number=6):
        """"
        Sets the refelcting area of the Cubesat.
        The value would be calculated from the numbers
        of the reflecting sides of the cubes.Default value of 6.
        """
        if(number < 7):
            self.set_abstract_item(
                "Space Object",
                "Reflecting Area",
                float(self.calculate_drag_area(self.get_edge_length())))
        else:
            self.log.error("A cube had at most 6 Reflectable sides")

    def get_reflect_coef(self):
        """
        Gets the Reflectivity Coefficient
        """
        result = self.get_abstract_item(
            "Space Object",
            "Reflectivity Coefficient")
        if(result):
            return result
        else:
            self.set_reflect_coef()
            return self.get_reflect_coef()

    def set_reflect_coef(self, coef=1.5):
        """
        Sets the Reflectivity Coefficient, Default value 1.5.
        Is Material connceted and a mean value should be set.
        """
        self.set_abstract_item(
            "Space Object",
            "Reflectivity Coefficient",
            coef)

    def get_orbit_type(self):
        """
        Gets the orbit type.
        """
        result = self.get_abstract_item("Space Object", "Orbit Type")
        if(result):
            return result
        else:
            self.set_orbit_type()
            return self.get_orbit_type()

    def set_orbit_type(self, orbit="LEO"):
        """
        Sets the orbit type. Default is LEO (Low Earth Orbit)
        """
        self.set_abstract_item("Space Object", "Orbit Type", orbit)

    def get_drag_coef_type(self):
        """
        Gets the Drag Coefficent Type
        """
        return self.get_abstract_item(
            "Space Object",
            "Drag Coefficent Type")

    def set_drag_coef_type(self, coef="VARIABLE"):
        """
        ets the Drag Coefficent Type
        Per default VARIABLE the other value would be the CONSTANT
        """
        self.set_abstract_item(
            "Space Object",
            "Drag Coefficent Type",
            "Drag Coefficent Type "+coef)

    def get_space_object_name(self):
        """
        Returns the space objcet name.
        """
        return self.get_abstract_item("Space Object", "Name")

    def set_space_object_name(self, name):
        """
        Sets the space object name it should be called in
        satgen so the object get inserted to the table.
        """
        self.set_abstract_item("Space Object", "Name", name)


    def get_db_id(self):
        """
        Returns the database id if not exisit 0
        """
        return self.db_id

    def set_db_id(self,db_id):
        """
        Sets the database id of the configuration
        """
        self.db_id = db_id

    def calculate_drag_area(self,edge_tuple):
        """
        Calculates the drag area with the given tuple
        """
        step_conf = ConfigStep()
        area = 0
        for i in itertools.combinations(step_conf.convert_to_tuple(edge_tuple),2):
            area = ((i[0]*i[1])*2)+area
        return area

    def set_drag_area(self, mode="random"):
        """
        Set the Drag area of space object, in m^2
        The mode can be fixed, random
        The default mode is the random, mode
        before that the edge length must be set.
        """
        area = self.calculate_drag_area(self.get_edge_length())
        try:
            if(self.get_edge_length()):
                if (mode == "fixed"):
                    self.set_abstract_item(
                        "Space Object",
                        "Drag Area",
                        float(area))
                elif (mode == "random"):
                    self.set_abstract_item(
                        "Space Object",
                        "Drag Area",
                        (float(area)/4))
        except:
            self.log.error(
                "The Cube Length is not set"
                "Please set it with set_edge_length(l)")

    def get_atmos_model(self):
        """
        Get the Atmospheric model
        """
        return self.get_abstract_item(
            "Atmospheric Model",
            "Atmospheric Model")

    def set_atoms_model(self, model="NRLMSISE-00"):
        """
        Sets the Atmospheric model, per default NRLMSISE-00
        """
        self.get_abstract_item("Atmospheric Model", "Atmospheric model", model)

    def get_solar_activity_type(self):
        """
        Gets the Solar activiy type
        """
        return self.get_abstract_item("Solar Activity", "Solar Activity Type")

    def set_solar_activity_type(self, act_type="MEAN_CONSTANT"):
        """
        Sets the Solar Activity Type, per default is the MEAN_CONSTANT
        """
        self.set_abstract_item(
            "Solar Activity",
            "Solar Activity Type",
            act_type)

    def get_ap_constant_solar_act(self):
        """
        Gets AP Constant Equivalent Solar Activity
        """
        return self.get_abstract_item(
            "Solar Activity",
            "AP Constant Equivalent Solar Activity")

    def set_ap_constant_solar_act(self, ap=15):
        """
        Sets AP Constant Equivalent Solar Activity, default value is 15
        """
        self.set_abstract_item(
            "Solar Activity",
            "AP Constant Equivalent Solar Activity",
            ap)

    def get_f107(self):
        """
        Gets the F10.7 Constant Equivalent Solar Activity
        """
        return self.get_abstract_item(
            "Solar Activity",
            "F10.7 Constant Equivalent Solar Activity")

    def set_f107(self, f107=140):
        """
        Sets F10.7 Constant Equivalent Solar Activity,
        with default value of 140
        """
        self.set_abstract_item(
            "Solar Activity",
            "F10.7 Constant Equivalent Solar Activity",
            f107)

    def get_initial_date(self):
        """
        Gets the initail date of the simulation
        """
        return self.get_abstract_item("Initial Bulletin", "Date")

    def set_initial_date(self, date):
        """
        Sets the date, the date can be dot or - splitted yyyy-mm-dd
        internally it will be changed to yyyy-mm-ddT12:00:00:00.000
        """
        return self.set_abstract_item("Initial Bulletin", "Date", date)


    def get_type_of_sim(self):
        """
        Gets the type of Simulation, paramater
        """
        return self.get_abstract_item("Initial Bulletin", "Type")

    def set_type_of_sim(self, sim_type="Perigee/Apogee"):
        """
        Sets the type of simulation, per default Perigee/Apogee
        """
        self.set_abstract_item("Initial Bulletin", "Type", sim_type)

    def get_frame(self):
        """
        Gets the Simulation Frame
        """
        return self.get_abstract_item("Initial Bulletin", "Frame")

    def set_frame(self, frame="CELESTIAL_MEAN_OF_DATE"):
        """
        Sets the Simulation Frame, per default CELESTIAL_MEAN_OF_DATE
        """
        self.set_abstract_item("Initial Bulletin", "Frame", frame)

    def get_nature(self):
        """
        Gets the Nature of Simulation
        """
        return self.get_abstract_item("Initial Bulletin", "Nature")

    def set_nature(self, nature="MEAN"):
        """
        Sets the Nature of Simulation, per default MEAN
        """
        self.set_abstract_item("Initial Bulletin", "Nature", nature)

    def get_preigee_alt(self):
        """
        Gets the Perigee Altitude in Km
        """
        return self.get_abstract_item(
            "Initial Bulletin",
            "Zp (Perigee altitude)")

    def set_perigee_alt(self, alt):
        """
        Sets the perigee Altitude in Km
        """
        self.set_abstract_item(
            "Initial Bulletin",
            "Zp (Perigee altitude)",
            alt)

    def get_apogee_alt(self):
        """
        Gets the Apogee altitude in Km
        """
        return self.get_abstract_item(
            "Initial Bulletin",
            "Za (Apogee altitude)")

    def set_apogee_alt(self, alt):
        """
        Sets the Apogee altitude in Km
        """
        self.set_abstract_item(
            "Initial Bulletin",
            "Za (Apogee altitude)",
            alt)

    def get_incl(self):
        """
        Gets the Inclination in Deg
        """
        return self.get_abstract_item("Initial Bulletin", "I (Inclination)")

    def set_incl(self, inclination):
        """
        Sets the Inclination in Deg
        """
        self.set_abstract_item(
            "Initial Bulletin",
            "I (Inclination)",
            inclination)

    def get_raan(self):
        """
        Gets the RAAN (Right Ascension of Ascending Node) in Deg
        """
        return self.get_abstract_item(
            "Initial Bulletin",
            "RAAN (Right Ascension of Ascending Node)")

    def set_raan(self, rann):
        """
        Sets RAAN (Right Ascension of Ascending Node) in Deg
        """
        self.set_abstract_item(
            "Initial Bulletin",
            "RAAN (Right Ascension of Ascending Node)",
            raan)

    def get_arg_perigee(self):
        """
        Gets the Argument of prigee in Deg
        """
        return self.get_abstract_item(
            "Initial Bulletin",
            "w (Argument of perigee)")

    def set_arg_perigee(self, arg):
        """
        Sets the Argument of perigee in Deg
        """
        self.set_abstract_item(
            "Initial Bulletin",
            "w (Argument of perigee)",
            arg)

    def get_mean_anomaly(self):
        """
        Gets the Mean Anomaly in Deg
        """
        return self.get_abstract_item("Initial Bulletin", "M (Mean anomaly)")

    def set_mean_anomaly(self, anomaly):
        """
        Sets the Mean Anomaly in Deg
        """
        self.set_abstract_item(
            "Initial Bulletin",
            "M (Mean anomaly)",
            anomaly)

    def set_semi_major_axis(self, axis):
        """
        Sets the SemiMajor Axis in km
        """
        self.set_abstract_item("Initial Bulletin", "a (Semi major axis)".title(), axis)

    def get_semi_major_axis(self):
        """
        Gets the SemiMajor Axis in km
        """
        return self.get_abstract_item("Initial Bulletin", "a (Semi major axis)".title())

    def get_eccentricity(self):
        """
        Gets the Eccentricity
        """
        return self.get_abstract_item("Initial Bulletin", "e (Eccentricity)")

    def set_eccentricity(self, ecc):
        """
        Sets the Eccentricity
        """
        self.set_abstract_item("Initial Bulletin", "e (Eccentricity)", ecc)

    def set_eX(self, eX):
        """
        Sets the eX Orbital Parameter
        """
        self.set_abstract_item("Initial Bulletin", "eX", eX)

    def get_eX(self):
        """
        Gets the eX Orbital Parameter
        """
        return self.get_abstract_item("Initial Bulletin", "eX")

    def set_eY(self, eY):
        """
        Sets the eY Orbital Parameter
        """
        self.set_abstract_item("Initial Bulletin", "eY", eY)

    def get_eY(self):
        """
        Gets the eY Orbital Parameter
        """
        return self.get_abstract_item("Initial Bulletin", "eY")

    def set_iX(self, iX):
        """
        Sets the Orbital Parameter iX
        """
        self.set_abstract_item("Initial Bulletin", "iX", iX)

    def get_iX(self):
        """
        Gets the Orbital Parameter iX
        """
        return self.get_abstract_item("Initial Bulletin", "iX")

    def set_iY(self, iY):
        """
        Sets the Orbital Parameter iY
        """
        self.set_abstract_item("Initial Bulletin", "iY", iY)

    def get_iY(self):
        """
        Gets the Orbital Parameter iY
        """
        return self.get_abstract_item("Initial Bulletin", "iY")

    def set_x(self, x):
        """
        Sets the x value
        """
        self.set_abstract_item("Initial Bulletin", "x", x)

    def get_x(self):
        """
        Gets the x value
        """
        self.get_abstract_item("Initial Bulletin", "x")

    def set_lambdaEq(self, lambdaEq):
        """
        Sets the Orbital Parameter lambdaEq in Deg
        """
        self.set_abstract_item("Initial Bulletin", "lambdaEq", lambdaEq)

    def get_lambdaEq(self):
        """
        Gets the Orbital Parameter lambdaEq in Deg
        """
        return self.get_abstract_item("Initial Bulletin", "lambdaEq")

    def set_epoch_tfe(self, date):
        """
        Sets the epochTFE with the date
        """
        self.set_abstract_item("Initial Bulletin", "epochTFE", date)

    def get_eppch_tfe(self):
        """
        Returns the epochTFE
        """
        return self.get_abstract_item("Initial Bulletin", "epochTFE")

    def set_func_value_accu(self, accu):
        """
        Sets functional Value Accuracy of Iteration in days
        """
        self.set_abstract_item(
            "Iteration Data",
            "Function Value Accuracy",
            accu)

    def get_func_value_accu(self):
        """
        Gets the functional Value Accuracy of Iteration in days
        """
        return self.get_abstract_item(
            "Iteration Data",
            "Function Value Accuracy")

    def get_exp_dur(self):
        """
        Gets the Expiring Duration in years
        """
        return self.get_abstract_item(
            "Iteration Data",
            "Expiring Duration")

    def set_exp_dur(self, dur):
        """
        Sets the expiring duration in years
        """
        self.set_abstract_item(
            "Iteration Data",
            "Expiring Duration")

    def get_sim_minus_exp(self):
        """
        Gets the Simulation Minus Expireing Duration in years
        """
        return self.get_abstract_item(
            "Iteration Data",
            "Simulation Minus Expireing Duration")

    def set_sim_minus_exp(self, exp):
        """
        Sets the Simulation Minus Expireing Duration in years
        """
        self.set_abstract_item(
            "Iteration Data",
            "Simulation Minus Expireing Duration")

    def set_iter_method(self, method="FrozenOrbit"):
        """
        Sets the Iteration Method
        """
        self.set_abstract_item(
            "Iteration Data",
            "Iteration Method",
            method)

    def get_iter_method(self):
        """
        Gets the Iteration Method
        """
        self.get_abstract_item("Iteration Data", "Iteration Method")

    def get_stela_version(self):
        """
        Gets the Stela Version
        """
        return self.get_abstract_item("General", "Stela Version")

    def set_stela_version(self, version):
        """
        Sets the Stela Version
        """
        self.set_abstract_item("General", "Stela Version", version)

    def set_drag_coef_const(self, value):
        """
        Sets the value for the Constant drag coeficient
        """
        if(self.get_conf()["Space Object"]["Drag Coefficent Type"] ==
           "Drag Coefficent Type CONSTANT"):
                self.set_abstract_item(
                    "Space Object",
                    "Constant Drag Coef",
                    value)

    def get_drag_coef_const(self):
        """
        Returns the constant Drag Coefficent
        """
        return self.get_abstract_item("Space Object", "Constant Drag Coef")

    def values_to_keys(self, want_value, dictio):
        """
        Returns key from the given values, for dicts
        """
        for key, is_value in dictio.items():
            if (is_value == want_value):
                return key

    def parse_elements(
            self,
            parent,
            key_value_dict,
            unit_dict=dict(),
            sort_dict=dict(),
            trans_dict=dict(),
            exceptions=list()):
        """
        Parses the keys and values dict with help of 
        unit_dict, sort_dict, transition_dict and the excpetion list.
        """
        db_id = self.get_db_id()
        conf_dict = self.config_dict
        unit_converter = self.unit_lib
        sorted_list = sorted(
            key_value_dict.items(),
            key=lambda x: sort_dict.get(x[0]))
        for sort_item in sorted_list:
            if(sort_item[0] not in exceptions and sort_item[0] != "Drag Coefficent Type"):
                tmp_el = ET.SubElement(parent, str(trans_dict[sort_item[0]]))
                if sort_item[0] in unit_dict:
                    tmp_el.set('unit', str(unit_dict[sort_item[0]]))
                    #unit conversion
                    if(unit_dict[sort_item[0]]=="rad"):
                        tmp_el.text = str(
                            unit_converter.deg_to_rad(float(sort_item[1])))
                    elif(unit_dict[sort_item[0]]=="m"):
                        tmp_el.text = str(
                            unit_converter.km_to_m(float(sort_item[1])))
                    else:
                        tmp_el.text = str(sort_item[1])
                else:
                    tmp_el.text = str(sort_item[1])
            #exception Atmospheric Model
            if(sort_item[0] == "Atmospheric Model"):
                atmos = ET.SubElement(parent, str(trans_dict["Atmospheric model"]))
                atmos.text = self.get_atmos_model()

            #exception Drag Coefficient
            if(sort_item[0] == "Drag Coefficent Type"):
                drag_co_type = self.get_conf()["Space Object"]["Drag Coefficent Type"]
                drag_co_el = ET.SubElement(
                    parent,
                    str(trans_dict["Drag Coefficent Type " + drag_co_type]))
                if(drag_co_type == "CONSTANT"):
                    drag_co_const = ET.SubElement(
                        drag_co_el,
                        str(trans_dict["Constant Drag Coef"]))
                    drag_co_const.text = str(self.get_drag_coef_const())
            #exception Solar Activity
            if(sort_item[0] == "Solar Activity Type"):
                solar_act_type = self.get_solar_activity_type()
                tmp_el = ET.SubElement(
                    parent,
                    str(trans_dict["Solar Activity Type " + solar_act_type]))
                if(solar_act_type == "VARIABLE"):
                    solar_act_type_el = ET.SubElement(
                        tmp_el, str(trans_dict["Solar Activity Type"]))
                    solar_act_type_el.text = str(self.get_solar_activity_type())
                else:
                    self.parse_elements(
                        tmp_el,                                                     
                        self.get_conf()["Solar Activity"],                          
                        unit_dict,
                        config_dict.get_sort_solar_act(),
                        trans_dict)
            #exception Iteration Data
            if(sort_item[0] == "Iteration Data"):
                iteration = ET.SubElement(parent, str(trans_dict["Iteration Data"]))
                self.parse_elements(
                    iteration,
                    self.get_conf()["Iteration Data"],
                    unit_dict,
                    conf_dict.get_sort_iteration_data(),
                    trans_dict)

    def get_xml_file_name(self):
        """
        Get the xml_file name generated
        """
        name = self.get_space_object_name()
        edge_length = self.get_edge_length()
        mass = self.get_mass()
        sat_name = name+"_a_sim.xml"
        return sat_name

    def convert_to_xml(self):
        """
        Creates an xml configuration from the cfg file
        """
        unit_converter = UnitConverter()
        dictio = self.config_dict.get_dict()
        sort_space_object = self.config_dict.get_sort_space_object()
        unit_dict = self.config_dict.get_unit_dict()
        self.set_abstract_item(
            "General",
            "Solar Activity Type",
            self.get_solar_activity_type())
        self.set_abstract_item(
            "General",
            "Iteration Data",
            "")
        self.set_abstract_item(
            "General",
            "Atmospheric Model",
            "")
        self.set_stela_version("2.5.0")
        leosimulation = ET.Element('LEOSimulation')
        leosimulation.set("version", str(self.get_stela_version()))
        stelaversion = ET.SubElement(leosimulation, 'STELAVersion')
        stelaversion.text = "2.5.1"
        spaceobject = ET.SubElement(leosimulation, dictio["Space Object"])
        self.parse_elements(
            spaceobject,
            self.get_conf()["Space Object"],
            unit_dict,
            sort_space_object,
            dictio,
            ["Edge Length", "Constant Drag Coef"])
        ephemerisman = ET.SubElement(leosimulation, 'EphemerisManager')
        ephemerisman.set('version', str(self.get_stela_version()))
        initstate = ET.SubElement(ephemerisman, 'initState')
        bulletin = ET.SubElement(initstate, 'bulletin')
        bulletin.set('version', str(self.get_stela_version()))
        date = strftime("%Y-%m-%dT%H:%M:%S.000", gmtime())
        self.set_initial_date(date)
        date_element = ET.SubElement(bulletin, 'date')
        date_element.text = date
        bulletin_type = str(dictio["Type " + self.get_type_of_sim()])
        sim_type_element = ET.SubElement( bulletin, bulletin_type)
        for param in self.config_dict.get_conf_sim(sim_type_element.tag):
            tmp_el = ET.SubElement(sim_type_element, str(dictio[param]))
            if param in unit_dict:
                tmp_el.set('unit', str(unit_dict[param]))
                if(unit_dict[param]=="rad"):
                    tmp_el.text = str(
                            unit_converter.deg_to_rad(
                                float(self.get_abstract_item(
                                    "Initial Bulletin", param.title()))))
                elif(unit_dict[param]=="m"):
                    tmp_el.text = str(
                            unit_converter.km_to_m(
                                float(self.get_abstract_item(
                                    "Initial Bulletin", param.title()))))
                else:
                    tmp_el.text = str(
                        self.get_abstract_item(
                            "Initial Bulletin", param.title()))
            else:
                tmp_el.text = str(
                    self.get_abstract_item("Initial Bulletin", param.title()))
        finishstate = ET.SubElement(ephemerisman, 'finalState')
        self.parse_elements(
             leosimulation,
             self.get_conf()["General"],
             unit_dict,
             self.config_dict.get_sort_general(),
             dictio,
            [
            "Stela Version",
            "Edge Length",
            "Solar Activity Type",
            "Atmospheric Model" ,
            "Earth Tesseral Switch",
            "Iteration Data"])
        result = ""
        if(sys.version_info) > (2,7):
            result = prettify(leosimulation)
        else:
            result = ET.tostring(leosimulation)
        return result
    
    def convert_space_object_to_tuple(self):
        """
        convertes the space object to tuple
        """
        key_tuple = tuple()
        value_tuple = tuple()
        qu_tuple = tuple()
        qu = "?,"
        qu_tuple = "("
        for k,v in self.get_conf()["Space Object"].items():
            if(k=="Drag Coefficent Type"):
                k = k+" "+v
                v = 1
            key_tuple = key_tuple+(self.config_dict.get_dict()[k],)
            value_tuple=value_tuple+(v,)
            qu_tuple = qu_tuple+qu
        qu_tuple = qu_tuple[:-1]+")"
        return {"key":key_tuple, "value":value_tuple, "qu": qu_tuple}

    def convert_init_state_to_tuple(self, space_object_id):
        """
        converts the initState to Tuple
        """
        unit_dict = self.config_dict.get_unit_dict()
        key_tuple = tuple()
        value_tuple = tuple()
        qu_tuple = tuple()
        qu = "?,"
        qu_tuple = "(?,?,?,"
        bulletin_type = str(self.config_dict.get_dict()["Type " + self.get_type_of_sim()])
        for param in self.config_dict.get_conf_sim(bulletin_type):
            key_tuple = key_tuple + (self.config_dict.get_dict()[param],)
            if param in unit_dict:
                if(unit_dict[param]=="rad"):
                    value_tuple = value_tuple + (
                            self.unit_lib.deg_to_rad(
                            float(self.get_abstract_item(
                                "Initial Bulletin", param.title()))), )
                elif(unit_dict[param]=="m"):
                    value_tuple = value_tuple + (self.unit_lib.km_to_m(
                        float(self.get_abstract_item(
                            "Initial Bulletin", param.title()))),)
                else:
                    value_tuple = value_tuple + (self.get_abstract_item(
                        "Initial Bulletin", param.title()),)
            else:
                value_tuple = value_tuple + (
                        self.get_abstract_item("Initial Bulletin", param.title()),)
            qu_tuple = qu_tuple+qu
        key_tuple = key_tuple + ("spaceObjectId", bulletin_type, "date")
        value_tuple = value_tuple + (space_object_id, 1, self.get_initial_date())
        qu_tuple = qu_tuple[:-1]+")"
        return {"key":key_tuple, "value":value_tuple, "qu": qu_tuple}

    def convert_general_sim(self, space_object_id):
        """
        convert to General Sim tuple for the database
        """
        key_tuple = tuple()
        value_tuple = tuple()
        qu_tuple = tuple()
        qu = "?,"
        qu_tuple = "(?, "
        for k,v in self.get_conf()["General"].items():
            if(k not in ["Stela Version",
                "Drag Coefficent Type",
                "Edge Length",
                "Solar Activity Type",
                "Atmospheric Model" ,
                "Earth Tesseral Switch",
                "Iteration Data"]):
                key_tuple = key_tuple+(self.config_dict.get_dict()[k],)
                value_tuple = value_tuple + (v,)
                qu_tuple = qu_tuple+qu
        key_tuple = key_tuple + ("spaceObjectId",)
        value_tuple = value_tuple + (space_object_id,)
        qu_tuple = qu_tuple[:-1]+")"
        return {"key":key_tuple, "value":value_tuple, "qu": qu_tuple}
예제 #26
0
파일: sara.py 프로젝트: PlanetHunt/satgen
class Sara:

    def __init__(self, sara_path, db, default_dir_path):
        self.set_sara_path(sara_path)
        self.set_default_dir(default_dir_path)
        self.set_db(db)
        self.uc = UnitConverter()

    def set_sara_path(self, sara_path):
        """
        Sets the Master Absolute Path
        """
        self.sara_path = sara_path

    def get_db(self):
        """
        Return database instance
        """
        return self.db

    def set_db(self, db):
        """
        Sets the database instance
        """
        self.db = db

    def get_default_dir(self):
        """
        returns the absolute path to the default directory
        """
        return self.default_dir

    def set_default_dir(self, default_path):
        """
        set the defualt abs path
        """
        self.default_dir = default_path

    def get_sara_path(self):
        """
        returns the absolute path to SARA
        """
        return self.sara_path

    def get_space_objects(self):
        """
        creates the folders and set the env
        variable so the master simulation
        can be run
        """
        return self.db.get_space_objects_data()

    def format_date_to_ymd(self, date):
        """
        formats date object to YYYY/MM/DD
        """
        return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f").strftime("%Y/%m/%d")

    def format_date_to_hms(self, date):
        """
        formats date object to HH:MM:SS.SSS
        """
        return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f").strftime("%H:%M:%S.%f")

    def create_files(self, db_tuple):
        """
        creates and copies files to run SARA
        """

        self.path = self.get_default_dir() + "/sara_sim/" + db_tuple[1]
        os.mkdir(self.path)
        os.chdir(self.path)
        os.mkdir("input")
        os.mkdir("output")

        cfg_content = {"name": db_tuple[1], 
                        "kep_e": db_tuple[4], 
                        "kep_i": self.uc.rad_to_deg(db_tuple[5]),
                        "kep_ran": self.uc.rad_to_deg(db_tuple[6]), 
                        "kep_aop": self.uc.rad_to_deg(db_tuple[7]),
                        "kep_tan": self.uc.rad_to_deg(db_tuple[8]), 
                        "kep_a": self.uc.m_to_km(db_tuple[3]),
                        "init_date_ymd": self.format_date_to_ymd(db_tuple[2]),
                        "init_time_hms": self.format_date_to_hms(db_tuple[2]),
                        }

        cfg_template = open(self.get_default_dir() + "/sample_files/sara.inp", "r")
        data = cfg_template.read()

        data = data.format(**cfg_content)

        cfg_file = open(os.getcwd() + "/input/reentry.inp", "w")
        cfg_file.write(data)

        cfg_template.close()
        cfg_file.close()

        shutil.copyfile(self.get_default_dir(
        ) + "/sample_files/usermat.db", os.getcwd() + "/input/usermat.db")

    def run_sara(self):
        """
        runs SARA
        """
        subprocess.call(self.get_sara_path() + "/REENTRY/reentry_linux")