def from_dict(cls, data): """Create a RunPeriod object from a dictionary. Args: data: A RunPeriod dictionary in following the format below. .. code-block:: python { "type": "RunPeriod", "start_date": {month: 1, day: 1}, "end_date": {month: 12, day: 31}, "start_day_of_week": 'Monday', "holidays": [{month: 1, day: 1}, {month: 7, day: 4}], "daylight_saving_time": {} // DaylightSavingTime dictionary representation } """ assert data['type'] == 'RunPeriod', \ 'Expected RunPeriod dictionary. Got {}.'.format(data['type']) start_date = Date.from_dict(data['start_date']) if \ 'start_date' in data else Date(1, 1) end_date = Date.from_dict(data['end_date']) if \ 'end_date' in data else Date(12, 31) start_day_of_week = data['start_day_of_week'] if \ 'start_day_of_week' in data else 'Sunday' holidays = None if 'holidays' in data and data['holidays'] is not None: holidays = tuple(Date.from_dict(hol) for hol in data['holidays']) daylight_saving = None if 'daylight_saving_time' in data and data['daylight_saving_time'] is not None: daylight_saving = DaylightSavingTime.from_dict(data['daylight_saving_time']) return cls(start_date, end_date, start_day_of_week, holidays, daylight_saving)
def schedule_primary_school_occupancy(directory): weekday_school = ScheduleDay('Weekday School Year', [0, 1, 0.5, 0], [Time(0, 0), Time(8, 0), Time(15, 0), Time(18, 0)]) weekend_school = ScheduleDay('Weekend School Year', [0]) weekday_summer = ScheduleDay('Weekday Summer', [0, 0.5, 0], [Time(0, 0), Time(9, 0), Time(17, 0)]) weekend_summer = ScheduleDay('Weekend Summer', [0]) summer_weekday_rule = ScheduleRule( weekday_summer, start_date=Date(7, 1), end_date=Date(9, 1)) summer_weekday_rule.apply_weekday = True summer_weekend_rule = ScheduleRule( weekend_summer, start_date=Date(7, 1), end_date=Date(9, 1)) summer_weekend_rule.apply_weekend = True school_weekend_rule = ScheduleRule(weekend_school) school_weekend_rule.apply_weekend = True summer_design = ScheduleDay('School Summer Design', [0, 1, 0.25], [Time(0, 0), Time(6, 0), Time(18, 0)]) winter_design = ScheduleDay('School Winter Design', [0]) schedule = ScheduleRuleset('School Occupancy', weekday_school, [summer_weekday_rule, summer_weekend_rule, school_weekend_rule], schedule_types.fractional, weekend_summer, summer_design, winter_design) dest_file = os.path.join(directory, 'schedule_primary_school_occupancy.json') with open(dest_file, 'w') as fp: json.dump(schedule.to_dict(True), fp, indent=4)
def test_schedule_ruleset_values(): """Test the ScheduleRuleset values method.""" weekday_office = ScheduleDay( 'Weekday Office Occupancy', [0, 1, 0], [Time(0, 0), Time(9, 0), Time(17, 0)]) saturday_office = ScheduleDay( 'Saturday Office Occupancy', [0, 0.25, 0], [Time(0, 0), Time(9, 0), Time(17, 0)]) sunday_office = ScheduleDay('Sunday Office Occupancy', [0]) sat_rule = ScheduleRule(saturday_office, apply_saturday=True) sun_rule = ScheduleRule(sunday_office, apply_sunday=True) schedule = ScheduleRuleset('Office Occupancy', weekday_office, [sat_rule, sun_rule], schedule_types.fractional) assert len(schedule.values()) == 8760 assert len(schedule.values(leap_year=True)) == 8784 sch_week_vals = schedule.values(end_date=Date(1, 7)) assert len(sch_week_vals) == 24 * 7 assert sch_week_vals[:24] == sunday_office.values_at_timestep() assert sch_week_vals[24:48] == weekday_office.values_at_timestep() assert sch_week_vals[144:] == saturday_office.values_at_timestep() sch_week_vals_10_min = schedule.values(6, end_date=Date(1, 7)) assert len(sch_week_vals_10_min) == 24 * 7 * 6
def data_collection_at_timestep(self, timestep=1, start_date=Date(1, 1), end_date=Date(12, 31)): """Get a ladybug DataCollection representing this schedule at a given timestep. Note that ladybug DataCollections always follow the "Ladybug Tools Interpretation" of date time values as noted in the ScheduleDay.values_at_timestep documentation. Args: timestep: An integer for the number of steps per hour at which to make the resulting DataCollection. start_date: An optional ladybug Date object for when to start the DataCollection. Default: 1 Jan on a non-leap year. end_date: An optional ladybug Date object for when to end the DataCollection. Default: 31 Dec on a non-leap year. """ a_period = AnalysisPeriod(start_date.month, start_date.day, 0, end_date.month, end_date.day, 23, timestep, self.is_leap_year) data_type, unit = self._get_lb_data_type_and_unit() header = Header(data_type, unit, a_period, metadata={'schedule': self.identifier}) values = self.values_at_timestep(timestep, start_date, end_date) return HourlyContinuousCollection(header, values)
def from_analysis_period(cls, analysis_period=None, start_day_of_week='Sunday', holidays=None, daylight_saving_time=None): """Initialize a RunPeriod object from a ladybug AnalysisPeriod. Note that the st_hour and end_hour properties of the AnalysisPeriod are completely ignored when using this classmethod since EnergyPlus cannot start or end a simulation at an interval less than a day. Args: analysis_period: A ladybug AnalysisPeriod object that has the start and end dates for the simulation. Default: an AnalysisPeriod for the whole year. start_day_of_week: Text for the day of the week on which the simulation starts. Default: 'Sunday'. Choose from the following: * Sunday * Monday * Tuesday * Wednesday * Thursday * Friday * Saturday holidays: A list of Ladybug Date objects for the holidays within the simulation. If None, no folidays are applied. Default: None. daylight_saving_time: A DaylightSavingTime object to dictate the start and end dates of daylight saving time. If None, no daylight saving time is applied to the simulation. Default: None. """ assert isinstance(analysis_period, AnalysisPeriod), 'Expected AnalysisPeriod ' \ 'for RunPeriod.from_analysis_period. Got {}.'.format(type(analysis_period)) st_date = Date(analysis_period.st_month, analysis_period.st_date, analysis_period.is_leap_year) end_date = Date(analysis_period.end_month, analysis_period.end_date, analysis_period.is_leap_year) return cls(st_date, end_date, start_day_of_week, holidays, daylight_saving_time)
def test_simulation_parameter_setability(): """Test the setting of properties of SimulationParameter.""" sim_par = SimulationParameter() output = SimulationOutput() output.add_zone_energy_use() sim_par.output = output assert sim_par.output == output run_period = RunPeriod(Date(1, 1), Date(6, 21)) sim_par.run_period = run_period assert sim_par.run_period == run_period sim_par.timestep = 4 assert sim_par.timestep == 4 sim_control_alt = SimulationControl(run_for_sizing_periods=True, run_for_run_periods=False) sim_par.simulation_control = sim_control_alt assert sim_par.simulation_control == sim_control_alt shadow_calc_alt = ShadowCalculation('FullExteriorWithReflections') sim_par.shadow_calculation = shadow_calc_alt assert sim_par.shadow_calculation == shadow_calc_alt sizing_alt = SizingParameter(None, 1, 1) relative_path = './tests/ddy/chicago_monthly.ddy' sizing_alt.add_from_ddy(relative_path) sim_par.sizing_parameter = sizing_alt assert sim_par.sizing_parameter == sizing_alt sim_par.north_angle = 20 assert sim_par.north_angle == 20 sim_par.terrain_type = 'Ocean' assert sim_par.terrain_type == 'Ocean'
def from_idf(cls, idf_string, type_idf_string=None): """Create a ScheduleFixedInterval from an EnergyPlus IDF text strings. Args: idf_string: A text string fully describing an EnergyPlus Schedule:File. type_idf_string: An optional text string for the ScheduleTypeLimits. If None, the resulting schedule will have no ScheduleTypeLimit. """ # process the schedule inputs sch_fields = parse_idf_string(idf_string, 'Schedule:File') schedule_type = ScheduleTypeLimit.from_idf(type_idf_string) if type_idf_string \ is not None else None timestep = 60 / int(sch_fields[8]) if sch_fields[8] != '' else 1 start_date = Date(1, 1, False) if sch_fields[5] == '8760' else Date( 1, 1, True) interpolate = False if sch_fields[7] == 'No' or sch_fields[ 7] == '' else True # load the data from the CSV file referenced in the string assert os.path.isfile(sch_fields[2]), \ 'CSV Schedule:File "{}" was not found on this system.'.format(sch_fields[2]) all_data = csv_to_matrix(sch_fields[2]) transposed_data = tuple(zip(*all_data)) csv_data = (float(x) for x in transposed_data[int(sch_fields[3]) - 1][int(sch_fields[4]):]) return cls(sch_fields[0], csv_data, schedule_type, timestep, start_date, 0, interpolate)
def __init__(self, identifier, values, schedule_type_limit=None, timestep=1, start_date=Date(1, 1), placeholder_value=0, interpolate=False): """Initialize Schedule FixedInterval.""" self._locked = False # unlocked by default # set all of the properties that impact how many values can be assigned self._timestep = int_in_range(timestep, 1, 60, 'schedule timestep') assert self._timestep in self.VALIDTIMESTEPS, 'ScheduleFixedInterval timestep ' \ '"{}" is invalid. Must be one of the following:\n{}'.format( timestep, self.VALIDTIMESTEPS) start_date = Date(1, 1) if start_date is None else start_date assert isinstance(start_date, Date), 'Expected ladybug Date for ' \ 'ScheduleFixedInterval start_date. Got {}.'.format(type(start_date)) self._start_date = start_date # set the values and all properties that can be re-set self.identifier = identifier self._display_name = None self.values = values self.schedule_type_limit = schedule_type_limit self.placeholder_value = placeholder_value self.interpolate = interpolate
def test_daylight_saving_time_init(): """Test the initialization of DaylightSavingTime and basic properties.""" daylight_save = DaylightSavingTime() str(daylight_save) # test the string representation assert daylight_save.start_date == Date(3, 12) assert daylight_save.end_date == Date(11, 5)
def test_date_to_from_array(): """Test the from_array method for Date.""" dt1 = Date(6, 21) dt_arr = dt1.to_array() rebuilt_dt = Date.from_array(dt_arr) assert rebuilt_dt == dt1 assert rebuilt_dt.to_array() == dt_arr
def test_to_from_date_string(): """Test the from_date_string method for Date.""" dt1 = Date(6, 21) dt_str = str(dt1) rebuilt_dt = Date.from_date_string(dt_str) assert rebuilt_dt == dt1 assert str(rebuilt_dt) == dt_str
def test_date_to_from_dict(): """Test the dict methods for Date.""" dt1 = Date(6, 21) dt_dict = dt1.to_dict() rebuilt_dt = Date.from_dict(dt_dict) assert dt1 == rebuilt_dt assert rebuilt_dt.to_dict() == dt_dict
def test_simulation_control_init_from_idf(): """Test the initialization of SimulationControl from_idf.""" daylight_save = DaylightSavingTime(Date(3, 10), Date(11, 3)) idf_str = daylight_save.to_idf() rebuilt_daylight_save = DaylightSavingTime.from_idf(idf_str) assert daylight_save == rebuilt_daylight_save assert rebuilt_daylight_save.to_idf() == idf_str
def test_simulation_control_dict_methods(): """Test the to/from dict methods.""" daylight_save = DaylightSavingTime(Date(3, 10), Date(11, 3)) ds_dict = daylight_save.to_dict() new_daylight_save = DaylightSavingTime.from_dict(ds_dict) assert new_daylight_save == daylight_save assert ds_dict == new_daylight_save.to_dict()
def __init__(self, file_path, cooling_date=Date(1, 1), heating_date=Date(1, 1)): """Initialize ZSZ""" # check that the file exists assert os.path.isfile(file_path), 'No file was found at {}'.format( file_path) assert file_path.endswith('.csv'), \ '{} is not an CSV file ending in .csv.'.format(file_path) self._file_path = file_path # parse the data in the file data_mtx = csv_to_matrix(file_path) # extract the header and the peak values headers = data_mtx[0][:] # copy the list del headers[0] peak = data_mtx[-3][:] # copy the list del peak[0] del data_mtx[0] for i in range(3): del data_mtx[-1] self._headers = headers self._peak = peak # process the timestep of the data data_mtx = list(zip(*data_mtx)) time1 = datetime.strptime(data_mtx[0][0], '%H:%M:%S') time2 = datetime.strptime(data_mtx[0][1], '%H:%M:%S') t_delta = time2 - time1 self._timestep = int(3600 / t_delta.seconds) self._cooling_date = cooling_date self._heating_date = heating_date self._cool_a_period = AnalysisPeriod(cooling_date.month, cooling_date.day, 0, cooling_date.month, cooling_date.day, 23, timestep=self._timestep) self._heat_a_period = AnalysisPeriod(heating_date.month, heating_date.day, 0, heating_date.month, heating_date.day, 23, timestep=self._timestep) # process the body of the data del data_mtx[0] self._data = data_mtx # properties to be computed upon request self._cooling_load_data = None self._heating_load_data = None self._cooling_flow_data = None self._heating_flow_data = None
def is_leap_year(self, value): value = bool(value) self._start_date = Date(self._start_date.month, self._start_date.day, value) self._end_date = Date(self._end_date.month, self._end_date.day, value) if self._daylight_saving_time is not None: st_dt = self._daylight_saving_time._start_date ed_dt = self._daylight_saving_time._end_date self._daylight_saving_time._start_date = Date(st_dt.month, st_dt.day, value) self._daylight_saving_time._end_date = Date(ed_dt.month, ed_dt.day, value)
def __init__(self, start_date=Date(1, 1), end_date=Date(12, 31)): """Initialize UWGRunPeriod.""" # process the dates if start_date is not None: self._check_date(start_date, 'start_date') self._start_date = start_date else: self._start_date = Date(1, 1) self.end_date = end_date
def __init__(self, start_date=Date(3, 12), end_date=Date(11, 5)): """Initialize DaylightSavingTime.""" # process the dates if start_date is not None: self._check_date(start_date, 'start_date') self._start_date = start_date else: self._start_date = Date(3, 12) self.end_date = end_date
def model_occ_schedules(model_json, threshold, period, output_file): """Translate a Model's occupancy schedules into a JSON of 0/1 values. \b Args: model_json: Full path to a Model JSON file. """ try: # re-serialize the Model with open(model_json) as json_file: data = json.load(json_file) model = Model.from_dict(data) # loop through the rooms and collect all unique occupancy schedules scheds, room_occupancy = [], {} for room in model.rooms: people = room.properties.energy.people if people is not None: model.properties.energy._check_and_add_schedule( people.occupancy_schedule, scheds) room_occupancy[room.identifier] = people.occupancy_schedule.identifier else: room_occupancy[room.identifier] = None # process the run period if it is supplied if period is not None and period != '' and period != 'None': a_per = AnalysisPeriod.from_string(period) start = Date(a_per.st_month, a_per.st_day) end = Date(a_per.end_month, a_per.end_day) a_period = AnalysisPeriod(start.month, start.day, 0, end.month, end.day, 23) timestep = a_per.timestep else: a_per = a_period = AnalysisPeriod() start, end, timestep = Date(1, 1), Date(12, 31), 1 # convert occupancy schedules to lists of 0/1 values schedules = {} for sch in scheds: values = [] for val in sch.values(timestep, start, end): is_occ = 0 if val < threshold else 1 values.append(is_occ) header = Header(Fraction(), 'fraction', a_period) schedules[sch.identifier] = HourlyContinuousCollection(header, values) if a_per.st_hour != 0 or a_per.end_hour != 23: schedules = {key: data.filter_by_analysis_period(a_per) for key, data in schedules.items()} schedules = {key: data.values for key, data in schedules.items()} # write out the JSON file occ_dict = {'schedules': schedules, 'room_occupancy': room_occupancy} output_file.write(json.dumps(occ_dict)) except Exception as e: _logger.exception('Model translation failed.\n{}'.format(e)) sys.exit(1) else: sys.exit(0)
def test_run_period(): """Test the run_period command.""" runner = CliRunner() result = runner.invoke(run_period, ['1', '6', '1', '12']) assert result.exit_code == 0 run_per = RunPeriod.from_string(result.output) assert run_per.start_date == Date(1, 6) assert run_per.end_date == Date(1, 12)
def daylight_saving_time(self, value): if value is not None: assert isinstance(value, DaylightSavingTime), 'Expected DaylightSavingTime' \ ' for RunPeriod run_period. Got {}.'.format(type(value)) if value.start_date.leap_year is not self.start_date.leap_year: leap = self.start_date.leap_year value._start_date = Date(value._start_date.month, value._start_date.day, leap) value._end_date = Date(value._end_date.month, value._end_date.day, leap) self._daylight_saving_time = value
def test_run_period_init(): """Test the initialization of RunPeriod and basic properties.""" run_period = RunPeriod() str(run_period) # test the string representation assert run_period.start_date == Date(1, 1) assert run_period.end_date == Date(12, 31) assert run_period.start_day_of_week == 'Sunday' assert run_period.holidays is None assert run_period.daylight_saving_time is None assert run_period.is_leap_year is False
def test_run_period_string_methods(): """Test the to/from string methods.""" run_period = RunPeriod() run_period.start_date = Date(1, 1) run_period.end_date = Date(6, 21) run_period.start_day_of_week = 'Monday' run_period.holidays = (Date(1, 1), Date(3, 17)) run_period.daylight_saving_time = DaylightSavingTime() new_run_period = RunPeriod.from_string(str(run_period)) assert new_run_period == run_period
def test_run_idf_window_ventilation(): """Test the Model.to.idf and run_idf method with a model possessing operable windows.""" room = Room.from_box('TinyHouseZone', 5, 10, 3) room.properties.energy.add_default_ideal_air() south_face = room[3] north_face = room[1] south_face.apertures_by_ratio(0.4, 0.01) north_face.apertures_by_ratio(0.4, 0.01) south_face.apertures[0].is_operable = True north_face.apertures[0].is_operable = True heat_setpt = ScheduleRuleset.from_constant_value( 'House Heating', 20, schedule_types.temperature) cool_setpt = ScheduleRuleset.from_constant_value( 'House Cooling', 28, schedule_types.temperature) setpoint = Setpoint('House Setpoint', heat_setpt, cool_setpt) room.properties.energy.setpoint = setpoint vent_control = VentilationControl(22, 27, 12, 30) room.properties.energy.window_vent_control = vent_control ventilation = VentilationOpening(wind_cross_vent=True) op_aps = room.properties.energy.assign_ventilation_opening(ventilation) assert len(op_aps) == 2 model = Model('TinyHouse', [room]) # Get the input SimulationParameter sim_par = SimulationParameter() sim_par.output.add_zone_energy_use() ddy_file = './tests/ddy/chicago.ddy' sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file) sim_par.run_period.end_date = Date(6, 7) sim_par.run_period.start_date = Date(6, 1) # create the IDF string for simulation paramters and model idf_str = '\n\n'.join((sim_par.to_idf(), model.to.idf(model))) # write the final string into an IDF idf = os.path.join(folders.default_simulation_folder, 'test_file_window_vent', 'in.idf') write_to_file(idf, idf_str, True) # prepare the IDF for simulation epw_file = './tests/simulation/chicago.epw' prepare_idf_for_simulation(idf, epw_file) # run the IDF through EnergyPlus sql, zsz, rdd, html, err = run_idf(idf, epw_file) assert os.path.isfile(sql) assert os.path.isfile(err) err_obj = Err(err) assert 'EnergyPlus Completed Successfully' in err_obj.file_contents
def test_daylight_saving_time_equality(): """Test the equality of DaylightSavingTime objects.""" daylight_save = DaylightSavingTime() daylight_save_dup = daylight_save.duplicate() daylight_save_alt = DaylightSavingTime(Date(3, 10), Date(11, 3)) assert daylight_save is daylight_save assert daylight_save is not daylight_save_dup assert daylight_save == daylight_save_dup daylight_save_dup.start_date = Date(3, 10) assert daylight_save != daylight_save_dup assert daylight_save != daylight_save_alt
def test_run_period_init_from_idf(): """Test the initialization of RunPeriod from_idf.""" run_period = RunPeriod() run_period.start_date = Date(1, 1) run_period.end_date = Date(6, 21) run_period.start_day_of_week = 'Monday' run_period.holidays = (Date(1, 1), Date(3, 17)) run_period.daylight_saving_time = DaylightSavingTime() rp_str, holidays, dst = run_period.to_idf() rebuilt_run_period = RunPeriod.from_idf(rp_str, holidays, dst) assert run_period == rebuilt_run_period assert rebuilt_run_period.to_idf() == (rp_str, holidays, dst)
def test_run_period_dict_methods(): """Test the to/from dict methods.""" run_period = RunPeriod() run_period.start_date = Date(1, 1) run_period.end_date = Date(6, 21) run_period.start_day_of_week = 'Monday' run_period.holidays = (Date(1, 1), Date(3, 17)) run_period.daylight_saving_time = DaylightSavingTime() rp_dict = run_period.to_dict() new_run_period = RunPeriod.from_dict(rp_dict) assert new_run_period == run_period assert rp_dict == new_run_period.to_dict()
def from_idf(cls, idf_string): """Create a DaylightSavingTime object from an EnergyPlus IDF text string. Args: idf_string: A text string fully describing an EnergyPlus RunPeriodControl:DaylightSavingTime definition. """ # check the inputs ep_strs = parse_idf_string(idf_string, 'RunPeriodControl:DaylightSavingTime,') start_vals = ep_strs[0].split('/') end_vals = ep_strs[1].split('/') start_date = Date(int(start_vals[0]), int(start_vals[1])) end_date = Date(int(end_vals[0]), int(end_vals[1])) return cls(start_date, end_date)
def from_dict(cls, data): """Create a ScheduleFixedInterval from a dictionary. Note that the dictionary must be a non-abridged version for this classmethod to work. Args: data: ScheduleFixedInterval dictionary following the format below. .. code-block:: python { "type": 'ScheduleFixedInterval', "identifier": 'Awning_Transmittance_X45NF23U', "display_name": 'Automated Awning Transmittance', "values": [], # list of numbers for the values of the schedule "schedule_type_limit": {}, # ScheduleTypeLimit dictionary representation "timestep": 1, # Integer for the timestep of the schedule "start_date": (1, 1), # Date dictionary representation "placeholder_value": 0, # Number for the values out of range "interpolate": False # Boolean noting whether to interpolate between values } """ assert data['type'] == 'ScheduleFixedInterval', \ 'Expected ScheduleFixedInterval. Got {}.'.format(data['type']) sched_type = None if 'schedule_type_limit' in data and data[ 'schedule_type_limit'] is not None: sched_type = ScheduleTypeLimit.from_dict( data['schedule_type_limit']) timestep = 1 if 'timestep' in data and data['timestep'] is not None: timestep = data['timestep'] start_date = Date(1, 1) if 'start_date' in data and data['start_date'] is not None: start_date = Date.from_array(data['start_date']) placeholder_value = 0 if 'placeholder_value' in data and data[ 'placeholder_value'] is not None: placeholder_value = data['placeholder_value'] interpolate = False if 'interpolate' in data and data['interpolate'] is not None: interpolate = data['interpolate'] new_obj = cls(data['identifier'], data['values'], sched_type, timestep, start_date, placeholder_value, interpolate) if 'display_name' in data and data['display_name'] is not None: new_obj.display_name = data['display_name'] return new_obj
def __init__(self, start_date=Date(1, 1), end_date=Date(12, 31), start_day_of_week='Sunday', holidays=None, daylight_saving_time=None): """Initialize RunPeriod.""" # process the dates if start_date is not None: self._check_date(start_date, 'start_date') self._start_date = start_date else: self._start_date = Date(1, 1) self.end_date = end_date self.start_day_of_week = start_day_of_week self.holidays = holidays self.daylight_saving_time = daylight_saving_time