Beispiel #1
0
 def test_from_string_leap_year(self):
     """Test creating analysis priod from a string."""
     ap_string = '2/21 to 3/22 between 5 to 17 @1*'
     ap = AnalysisPeriod.from_string(ap_string)
     assert ap.st_hour == 5
     assert ap.end_hour == 17
     assert ap.st_month == 2
     assert ap.end_month == 3
     assert ap.st_day == 21
     assert ap.end_day == 22
     assert ap.timestep == 1
Beispiel #2
0
 def test_design_day_from_properties(self):
     """Test hourly data properties of a standard ddy."""
     location = Location('Test City', 'USA', 34.20, -118.35, -8, 226)
     a_period = AnalysisPeriod(12, 21, 0, 12, 21, 23)
     des_day = DesignDay.from_design_day_properties(
         'Test Day', 'WinterDesignDay', location, a_period, 3.9, 0,
         'Wetbulb', 3.9, 98639, 0.8, 330, 'ASHRAEClearSky', [0])
     assert des_day.location == location
     new_period = des_day.analysis_period
     assert new_period.st_month == a_period.st_month
     assert new_period.st_day == a_period.st_day
     assert new_period.st_hour == a_period.st_hour
     assert new_period.end_month == a_period.end_month
     assert new_period.end_day == a_period.end_day
     assert new_period.end_hour == a_period.end_hour
Beispiel #3
0
def test_schedule_fixedinterval_data_collection():
    """Test the ScheduleFixedInterval data_collection_at_timestep method."""
    trans_sched = ScheduleFixedInterval('Custom Transmittance',
                                        [x / 8760 for x in range(8760)],
                                        schedule_types.fractional)

    sch_data = trans_sched.data_collection_at_timestep()
    assert len(sch_data) == 8760
    assert sch_data.values == trans_sched.values
    assert isinstance(sch_data.header.data_type, fraction.Fraction)
    assert sch_data.header.unit == 'fraction'
    assert sch_data.header.analysis_period == AnalysisPeriod()

    sch_data = trans_sched.data_collection_at_timestep(timestep=2)
    assert len(sch_data) == 8760 * 2
Beispiel #4
0
 def hourly_prevailing_temperature_timestep(self, timestep):
     """HourlyContinuousCollection of prevailing temperature at timestep."""
     if timestep != 1:
         hourly_coll = self.hourly_prevailing_temperature
         _new_values = []
         for val in hourly_coll.values:
             _new_values.extend([val] * timestep)
         a_per = hourly_coll.header.analysis_period
         _new_a_per = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour,
                                     a_per.end_month, a_per.end_day, a_per.end_hour,
                                     timestep, a_per.is_leap_year)
         _new_header = hourly_coll.header.duplicate()
         _new_header._analysis_period = _new_a_per
         return HourlyContinuousCollection(_new_header, _new_values)
     return self.hourly_prevailing_temperature
Beispiel #5
0
def test_init_monthly_per_hour():
    """Test the init methods for monthly per hour collections."""
    a_per = AnalysisPeriod(6, 1, 0, 7, 31, 23)
    vals = [20] * 24 + [25] * 24
    avg = sum(vals) / 48
    # Setup data collection
    dc1 = MonthlyPerHourCollection(Header(Temperature(), 'C', a_per), vals,
                                   a_per.months_per_hour)

    assert dc1.datetimes == tuple(a_per.months_per_hour)
    assert dc1.values == tuple(vals)
    assert dc1.average == avg
    assert not dc1.is_continuous
    str(dc1)  # Test the string representation of the collection
    str(dc1.header)  # Test the string representation of the header
Beispiel #6
0
    def to_idf(self, schedule_directory, include_datetimes=False):
        """IDF string representation of the schedule.

        Note that this method does both the production of the IDF string
        representation of the Schedule:File as well as the actual writing of
        the schedule to a CSV format that can be read in by EnergyPlus.

        Args:
            schedule_directory: [Required] Text string of a path to a folder on this
                machine to which the CSV version of the file will be written.
            include_datetimes: Boolean to note whether a column of datetime objects
                should be written into the CSV alongside the data. Default is False,
                which will keep the resulting CSV lighter in file size but you may
                want to include such datetimes in order to verify that values align with
                the expected timestep. Note that the included datetimes will follow the
                EnergyPlus interpretation of aligning values to timesteps in which case
                the timestep to which the value is matched means that the value was
                utilized over all of the previous timestep.

        Returns:
            schedule_file --
            Text string representation of the Schedule:File describing this schedule.
        """
        # gather all of the data to be written into the CSV
        sched_data = [str(val) for val in self.values_at_timestep(self.timestep)]
        if include_datetimes:
            sched_a_per = AnalysisPeriod(timestep=self.timestep,
                                         is_leap_year=self.is_leap_year)
            sched_data = ('{},{}'.format(dt, val) for dt, val in
                          zip(sched_a_per.datetimes, sched_data))
        file_path = os.path.join(schedule_directory,
                                 '{}.csv'.format(self.identifier.replace(' ', '_')))

        # write the data into the file
        write_to_file(file_path, ',\n'.join(sched_data), True)

        # generate the IDF strings
        shc_typ = self._schedule_type_limit.identifier if \
            self._schedule_type_limit is not None else ''
        col_num = 1 if not include_datetimes else 2
        num_hrs = 8760 if not self.is_leap_year else 8784
        interp = 'No' if not self.interpolate else 'Yes'
        min_per_step = int(60 / self.timestep)
        fields = (self.identifier, shc_typ, file_path, col_num, 0, num_hrs, 'Comma',
                  interp, min_per_step)
        schedule_file = generate_idf_string('Schedule:File', fields,
                                            self._schedule_file_comments)
        return schedule_file
Beispiel #7
0
def test_run_uwg(correct):
    # set up the run manager
    epw_path = './tests/fixtures/epw/boston.epw'
    district = District(
        correct['typologies'], correct['site_area'], correct['climate_zone'],
        correct['tree_coverage_ratio'], correct['grass_coverage_ratio'],
        correct['traffic_parameters'], correct['vegetation_parameters'],
        correct['pavement_parameters'], correct['characteristic_length'])
    a_period = AnalysisPeriod(1, 1, 0, 1, 7, 23)
    run_manager = RunManager(epw_path, district, analysis_period=a_period)

    # set the run manager to run through the uwg
    morphed_epw = run_manager.run()
    assert os.path.isfile(morphed_epw)
    assert os.stat(morphed_epw).st_size > 1
    os.remove(morphed_epw)
Beispiel #8
0
def test_get_aligned_collection_continuous():
    """Test the method for getting an aligned continuous collection."""
    header = Header(Temperature(), 'C', AnalysisPeriod(end_month=1, end_day=1))
    values = list(xrange(24))
    dc1 = HourlyContinuousCollection(header, values)
    dc2 = dc1.get_aligned_collection(50)
    assert dc1.header.data_type.name == dc2.header.data_type.name
    assert dc1.header.unit == dc2.header.unit
    assert dc1.header.analysis_period == dc2.header.analysis_period
    assert dc1.header.metadata == dc2.header.metadata
    assert len(dc1.values) == len(dc2.values)
    assert dc2.values == tuple([50] * 24)

    dc3 = dc1.get_aligned_collection(50, RelativeHumidity(), '%')
    assert dc3.header.data_type.name == 'Relative Humidity'
    assert dc3.header.unit == '%'
Beispiel #9
0
def test_get_percentile():
    """Test the get_percentile method."""
    header1 = Header(Temperature(), 'C', AnalysisPeriod())
    values = list(xrange(8760))
    dc = HourlyContinuousCollection(header1, values)

    assert dc.get_percentile(0) == 0
    assert dc.get_percentile(25) == 2189.75
    assert dc.get_percentile(50) == 4379.5
    assert dc.get_percentile(75) == 6569.25
    assert dc.get_percentile(100) == 8759

    with pytest.raises(Exception):
        dc.get_percentile(-10)
    with pytest.raises(Exception):
        dc.get_percentile(110)
Beispiel #10
0
def test_init_hourly():
    """Test the init methods for dicontinuous collections."""
    a_per = AnalysisPeriod(6, 21, 12, 6, 21, 13)
    dt1, dt2 = DateTime(6, 21, 12), DateTime(6, 21, 13)
    v1, v2 = 20, 25
    avg = (v1 + v2) / 2
    # Setup data collection
    dc1 = HourlyDiscontinuousCollection(Header(Temperature(), 'C', a_per),
                                        [v1, v2], [dt1, dt2])

    assert dc1.datetimes == (dt1, dt2)
    assert dc1.values == (v1, v2)
    assert dc1.average == avg
    assert dc1.is_continuous is False
    str(dc1)  # Test the string representation of the collection
    str(dc1.header)  # Test the string representation of the header
Beispiel #11
0
    def from_analysis_period(cls, analysis_period=AnalysisPeriod(3, 12, 0, 11, 5, 23)):
        """Initialize a DaylightSavingTime object from a ladybug AnalysisPeriod.

        Args:
            analysis_period: A ladybug AnalysisPeriod object that has the start
                and end dates for daylight savings time.
                Default: 12 Mar - 5 Nov (daylight savings in the US in 2017)
        """
        assert isinstance(analysis_period, AnalysisPeriod), 'Expected AnalysisPeriod ' \
            'for DaylightSavingTime.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)
Beispiel #12
0
    def __init__(self, file_path):
        """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._a_period = AnalysisPeriod(1,
                                        1,
                                        0,
                                        1,
                                        1,
                                        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
Beispiel #13
0
def test_bin_vectors():
    """Bin vectors"""

    # Testing vals
    dir_vals = [0, 0, 0, 10, 85, 90, 95, 170, 285, 288]
    spd_vals = dir_vals

    # Make into fake data collections
    a_per = AnalysisPeriod(6, 21, 12, 6, 21, 13)
    dates = [DateTime(6, 21, i) for i in range(len(dir_vals))]
    spd_header = Header(Speed(), 'm/s', a_per)
    dir_header = Header(GenericType('Direction', 'deg'), 'deg', a_per)
    spd_data = HourlyDiscontinuousCollection(spd_header, spd_vals, dates)
    dir_data = HourlyDiscontinuousCollection(dir_header, dir_vals, dates)

    # Init simple dir set divided by 4
    w = WindRose(dir_data, spd_data, 4)
Beispiel #14
0
def test_xticks_radial():
    """Test polar coordinate array"""

    # Testing vals ensure all histogram heights are equal.
    dir_vals = [3, 3, 10,  # 315 - 45
                85, 90, 95,  # 45 - 135
                170, 170, 170,  # 135 - 225
                230, 285, 288]  # 225 - 315

    spd_vals = dir_vals

    # Make into fake data collections
    a_per = AnalysisPeriod(6, 21, 12, 6, 21, 13)
    dates = [DateTime(6, 21, i) for i in range(len(dir_vals))]
    spd_header = Header(Speed(), 'm/s', a_per)
    dir_header = Header(GenericType('Direction', 'deg'), 'deg', a_per)
    spd_data = HourlyDiscontinuousCollection(spd_header, spd_vals, dates)
    dir_data = HourlyDiscontinuousCollection(dir_header, dir_vals, dates)

    # Init simple dir set divided by 4
    w = WindRose(dir_data, spd_data, 4)
    f = _deg2rad
    cos, sin = math.cos, math.sin

    # Testing
    xticks = w.orientation_lines
    xticks = [xtick.scale(1 / w.compass_radius) for xtick in xticks]
    # w.angles - 90: [225, -45, 45, 135, 225]

    # Since frequencies are for xticks, no need to scale vectors.
    chk_xticks = [
        [(0, 0), (cos(f(225)), -sin(f(225)))],  # v0
        [(0, 0), (cos(f(-45)), -sin(f(-45)))],  # v1 bin 0
        [(0, 0), (cos(f(-45)), -sin(f(-45)))],  # v2
        [(0, 0), (cos(f(45)),  -sin(f(45)))],   # v3 bin 1
        [(0, 0), (cos(f(45)),  -sin(f(45)))],   # v4
        [(0, 0), (cos(f(135)), -sin(f(135)))],  # v5 bin 2
        [(0, 0), (cos(f(135)), -sin(f(135)))],  # v6
        [(0, 0), (cos(f(225)), -sin(f(225)))]]  # v7 bin 3

    for i, (chk_xtick, xtick) in enumerate(zip(chk_xticks, xticks)):
        # Check x, y
        # print(chk_xtick[1][0], xtick.to_array()[1][0])
        # print(chk_xtick[1][1], xtick.to_array()[1][1])
        assert abs(chk_xtick[1][0] - xtick.to_array()[1][0]) < 1e-10
        assert abs(chk_xtick[1][1] - xtick.to_array()[1][1]) < 1e-10
Beispiel #15
0
def test_filter_by_analysis_period():
    """Test the filter_by_analysis_period method"""
    epw_path = './tests/assets/epw/chicago.epw'
    wea_from_epw = Wea.from_epw_file(epw_path)

    a_period = AnalysisPeriod(12, 21, 0, 3, 21, 23)
    filtered_wea = wea_from_epw.filter_by_analysis_period(a_period)
    assert len(filtered_wea) == len(filtered_wea.diffuse_horizontal_irradiance.values) \
        == len(a_period)
    assert not filtered_wea.is_annual
    assert filtered_wea.is_continuous

    wea_path = './tests/assets/wea/chicago_winter.wea'
    filtered_wea.write(wea_path)
    assert os.path.isfile(wea_path)
    assert os.stat(wea_path).st_size > 1
    os.remove(wea_path)
def test_design_day_hourly_data():
    """Test hourly data properties of a standard ddy."""
    location = Location('Test City', '-', 'USA', 34.20, -118.35, -8, 226)
    a_period = AnalysisPeriod(8, 21, 0, 8, 21, 23)
    des_day = DesignDay.from_design_day_properties(
        'Test Day', 'SummerDesignDay', location, a_period, 36.8, 13.2,
        'Wetbulb', 20.5, 98639, 3.9, 170, 'ASHRAETau', [0.436, 2.106])
    # dry bulb values
    db_data_collect = des_day.hourly_dry_bulb
    assert db_data_collect[5] == approx(23.6, rel=1e-1)
    assert db_data_collect[14] == approx(36.8, rel=1e-1)

    # dew point values
    dpt_data_collect = des_day.hourly_dew_point
    assert dpt_data_collect[0] == approx(11.296, rel=1e-1)
    assert dpt_data_collect[-1] == approx(11.296, rel=1e-1)

    # relative humidity values
    rh_data_collect = des_day.hourly_relative_humidity
    assert rh_data_collect[5] == approx(45.896, rel=1e-1)
    assert rh_data_collect[14] == approx(21.508, rel=1e-1)

    # barometric pressure values
    bp_data_collect = des_day.hourly_barometric_pressure
    assert bp_data_collect[0] == approx(98639, rel=1e-1)
    assert bp_data_collect[-1] == approx(98639, rel=1e-1)

    # wind speed values
    ws_data_collect = des_day.hourly_wind_speed
    assert -0.1 < ws_data_collect[0] - 3.9 < 0.1
    assert -0.1 < ws_data_collect[-1] - 3.9 < 0.1

    # wind direction values
    wd_data_collect = des_day.hourly_wind_direction
    assert wd_data_collect[0] == approx(170, rel=1e-1)
    assert wd_data_collect[-1] == approx(170, rel=1e-1)

    # radiation values
    direct_normal_rad, diffuse_horizontal_rad, global_horizontal_rad = \
        des_day.hourly_solar_radiation
    assert direct_normal_rad[0] == 0
    assert direct_normal_rad[11] == approx(891.46, rel=1e-1)
    assert diffuse_horizontal_rad[0] == 0
    assert diffuse_horizontal_rad[11] == approx(165.32, rel=1e-1)
    assert global_horizontal_rad[0] == 0
    assert global_horizontal_rad[11] == approx(985.05, rel=1e-1)
Beispiel #17
0
    def from_analysis_period(cls,
                             analysis_period=AnalysisPeriod(
                                 1, 1, 0, 12, 31, 23)):
        """Initialize a UWGRunPeriod object from a ladybug AnalysisPeriod.

        Args:
            analysis_period: A ladybug AnalysisPeriod object that has the start
                and end dates for daylight savings time.
        """
        assert isinstance(analysis_period, AnalysisPeriod), 'Expected AnalysisPeriod ' \
            'for UWGRunPeriod.from_analysis_period. Got {}.'.format(
                type(analysis_period))
        st_date = Date(analysis_period.st_month, analysis_period.st_day,
                       analysis_period.is_leap_year)
        end_date = Date(analysis_period.end_month, analysis_period.end_day,
                        analysis_period.is_leap_year)
        return cls(st_date, end_date)
Beispiel #18
0
def test_pmv_collection_heat_loss_outputs():
    """Test the heat loss outputs of the PMV collection."""
    calc_length = 24
    air_temp_header = Header(Temperature(), 'C',
                             AnalysisPeriod(end_month=1, end_day=1))
    air_temp = HourlyContinuousCollection(air_temp_header, [24] * calc_length)
    pmv_obj = PMV(air_temp, 50, air_speed=0.5)

    assert isinstance(pmv_obj.adjusted_air_temperature,
                      HourlyContinuousCollection)
    assert len(pmv_obj.adjusted_air_temperature.values) == calc_length
    assert pmv_obj.adjusted_air_temperature[0] == pytest.approx(21.79,
                                                                rel=1e-2)

    assert isinstance(pmv_obj.cooling_effect, HourlyContinuousCollection)
    assert len(pmv_obj.cooling_effect.values) == calc_length
    assert pmv_obj.cooling_effect[0] == pytest.approx(2.215, rel=1e-2)

    assert isinstance(pmv_obj.heat_loss_conduction, HourlyContinuousCollection)
    assert len(pmv_obj.heat_loss_conduction.values) == calc_length
    assert pmv_obj.heat_loss_conduction[0] == pytest.approx(12.14, rel=1e-2)

    assert isinstance(pmv_obj.heat_loss_sweating, HourlyContinuousCollection)
    assert len(pmv_obj.heat_loss_sweating.values) == calc_length
    assert pmv_obj.heat_loss_sweating[0] == pytest.approx(2.44, rel=1e-2)

    assert isinstance(pmv_obj.heat_loss_latent_respiration,
                      HourlyContinuousCollection)
    assert len(pmv_obj.heat_loss_latent_respiration.values) == calc_length
    assert pmv_obj.heat_loss_latent_respiration[0] == pytest.approx(4.95,
                                                                    rel=1e-2)

    assert isinstance(pmv_obj.heat_loss_dry_respiration,
                      HourlyContinuousCollection)
    assert len(pmv_obj.heat_loss_dry_respiration.values) == calc_length
    assert pmv_obj.heat_loss_dry_respiration[0] == pytest.approx(1.093,
                                                                 rel=1e-2)

    assert isinstance(pmv_obj.heat_loss_radiation, HourlyContinuousCollection)
    assert len(pmv_obj.heat_loss_radiation.values) == calc_length
    assert pmv_obj.heat_loss_radiation[0] == pytest.approx(28.78, rel=1e-2)

    assert isinstance(pmv_obj.heat_loss_convection, HourlyContinuousCollection)
    assert len(pmv_obj.heat_loss_convection.values) == calc_length
    assert pmv_obj.heat_loss_convection[0] == pytest.approx(26.296, rel=1e-2)
Beispiel #19
0
def test_write_to_file_timestep():
    ap = AnalysisPeriod(12, 21, 0, 12, 21, 23, timestep=4)
    sp = Sunpath(location)
    folder = './tests/assets/temp'
    filename = 'sunpath_dec_21_timestep'
    sp.to_file(folder, filename, hoys=ap.hoys)
    sp_file = os.path.join(folder, '%s.rad' % filename)
    sp_mod_file = os.path.join(folder, '%s.mod' % filename)
    assert os.path.isfile(sp_file)
    assert os.path.isfile(sp_mod_file)
    with open(sp_mod_file) as inf:
        for count, _ in enumerate(inf):
            pass
    assert count == 36  # number of suns - 1
    with open(sp_file) as inf:
        for count, _ in enumerate(inf):
            pass
    assert count == 36  # number of suns - 1
Beispiel #20
0
def test_hourlyplot_custom():
    """Test the initialization of HourlyPlot with custom properties."""
    header = Header(Temperature(), 'C', AnalysisPeriod())
    values = list(range(8760))
    data_coll = HourlyContinuousCollection(header, values)
    hour_plot = HourlyPlot(data_coll, LegendParameters(), Point3D(10, 10, 10),
                           2, 2, 100)

    assert hour_plot.base_point == Point3D(10, 10, 10)
    assert hour_plot.x_dim == 2
    assert hour_plot.y_dim == 2
    assert hour_plot.z_dim == 100

    mesh = hour_plot.colored_mesh3d
    assert isinstance(mesh, Mesh3D)
    assert len(mesh.faces) == 8760
    assert mesh.min == Point3D(10, 10, 10)
    assert mesh.max == Point3D(2 * 365 + 10, 2 * 24 + 10, 110)
Beispiel #21
0
def test_cull_to_timestep():
    """Test the test_cull_to_timestep method on the discontinuous collection."""
    a_per = AnalysisPeriod(6, 21, 0, 6, 21, 23)
    dt1, dt2, dt3 = DateTime(6, 21, 12), DateTime(6, 21,
                                                  13), DateTime(6, 21, 12, 30)
    v1, v2 = 20, 25
    dc1 = HourlyDiscontinuousCollection(Header(Temperature(), 'C', a_per),
                                        [v1, v2, v2], [dt1, dt3, dt2])
    dc1_new = dc1.validate_analysis_period()
    dc2_new = dc1.cull_to_timestep()
    assert dc1_new.header.analysis_period.timestep == 2
    assert dc2_new.header.analysis_period.timestep == 1
    assert len(dc1_new.values) == 3
    assert len(dc2_new.values) == 2

    dc1_new.convert_to_culled_timestep()
    assert dc1_new.header.analysis_period.timestep == 1
    assert len(dc1_new.values) == 2
Beispiel #22
0
def test_horizontal_solarcal_collection_full_input():
    """Test the initialization of the HorizontalSolarCal collection will all inputs."""
    calc_length = 24
    irr_header = Header(Irradiance(), 'W/m2',
                        AnalysisPeriod(end_month=1, end_day=1))
    dir_norm = HourlyContinuousCollection(irr_header, [500] * calc_length)
    diff_horiz = HourlyContinuousCollection(irr_header, [200] * calc_length)
    custom_par = SolarCalParameter('seated', None, 45, 0.65, 0.97)
    solarcal_obj = HorizontalSolarCal(Location(), dir_norm, diff_horiz, 24,
                                      0.6, 0.35, custom_par)

    assert solarcal_obj.fraction_body_exposed[12] == 0.6
    assert solarcal_obj.floor_reflectance[0] == 0.35
    assert solarcal_obj.solarcal_body_parameter.posture == 'seated'
    assert solarcal_obj.solarcal_body_parameter.sharp is None
    assert solarcal_obj.solarcal_body_parameter.body_azimuth == 45
    assert solarcal_obj.solarcal_body_parameter.body_absorptivity == 0.65
    assert solarcal_obj.solarcal_body_parameter.body_emissivity == 0.97
Beispiel #23
0
def test_model_occ_schedules():
    runner = CliRunner()
    input_model = './tests/json/ShoeBox.json'

    result = runner.invoke(model_occ_schedules, [input_model])
    assert result.exit_code == 0
    occ_dict = json.loads(result.output)
    assert len(occ_dict['schedules']) == 1
    assert len(list(occ_dict['schedules'].values())[0]) == 8760

    a_per = AnalysisPeriod(6, 21, 8, 9, 21, 16)
    result = runner.invoke(
        model_occ_schedules,
        [input_model, '--period', str(a_per)])
    assert result.exit_code == 0
    occ_dict = json.loads(result.output)
    assert len(occ_dict['schedules']) == 1
    assert len(list(occ_dict['schedules'].values())[0]) == len(a_per)
Beispiel #24
0
def test_init_pmv_collection_full_input():
    """Test the initialization of the PMV collection will all inputs."""
    calc_length = 24
    air_temp_header = Header(Temperature(), 'C', AnalysisPeriod(end_month=1, end_day=1))
    air_temp = HourlyContinuousCollection(air_temp_header, [24] * calc_length)
    custom_par = PMVParameter(15, 0.012, 0.004, 0.2)
    pmv_obj = PMV(air_temp, 50, 22, 0.5, 1.2, 0.85, 0.1, custom_par)

    assert pmv_obj.air_temperature[0] == 24
    assert pmv_obj.rel_humidity[0] == 50
    assert pmv_obj.rad_temperature[0] == 22
    assert pmv_obj.air_speed[0] == 0.5
    assert pmv_obj.met_rate[0] == 1.2
    assert pmv_obj.clo_value[0] == 0.85
    assert pmv_obj.external_work[0] == 0.1
    assert pmv_obj.comfort_parameter.ppd_comfort_thresh == 15
    assert pmv_obj.comfort_parameter.humid_ratio_upper == 0.012
    assert pmv_obj.comfort_parameter.humid_ratio_lower == 0.004
    assert pmv_obj.comfort_parameter.still_air_threshold == 0.2
Beispiel #25
0
def test_filter_collections_by_statement():
    """Test the method to filter collections by conditional statement."""
    header = Header(Temperature(), 'C', AnalysisPeriod(end_month=1, end_day=1))
    values1 = list(xrange(24))
    values2 = [12] * 24
    values3 = list(xrange(12, 36))
    dc1 = HourlyContinuousCollection(header, values1)
    dc2 = HourlyContinuousCollection(header, values2)
    dc3 = HourlyContinuousCollection(header, values3)

    filt_coll = HourlyContinuousCollection.filter_collections_by_statement(
        [dc1, dc2, dc3], 'a >= 12 and c <= 30')

    assert len(filt_coll) == 3
    assert len(filt_coll[0]) == len(filt_coll[1]) == len(filt_coll[2]) == 7
    assert filt_coll[0].values == (12, 13, 14, 15, 16, 17, 18)
    assert filt_coll[1].values == (12, 12, 12, 12, 12, 12, 12)
    assert filt_coll[2].values == (24, 25, 26, 27, 28, 29, 30)
    assert isinstance(filt_coll[0], HourlyDiscontinuousCollection)
Beispiel #26
0
def _ill_values_to_data(ill_values, sun_indices, timestep=1, leap_yr=False):
    """Convert a list of sun-up irradiance from an .ill file into annual irradiance data.

    Args:
        ill_values: A list of raw irradiance values from an .ill file.
        sun_indices: A list of integers for where in the total_count sun-up hours occur.
        timestep: The timestep to make the data collection.
        leap_yr: Boolean to note if data is for a leap year.
    
    Return:
        An annual HourlyContinuousCollection of irradiance data.
    """
    values = [0] * (8760 * timestep) if not leap_yr else [0] * (8784 *
                                                                timestep)
    for i, irr in zip(sun_indices, ill_values):
        values[i] = irr
    a_period = AnalysisPeriod(timestep=timestep, is_leap_year=leap_yr)
    header = Header(Irradiance(), 'W/m2', a_period)
    return HourlyContinuousCollection(header, values)
Beispiel #27
0
def test_daylight_saving():
    """Test the applicaiton of daylight saving time."""
    nyc = Location('New_York',
                   country='USA',
                   latitude=40.72,
                   longitude=-74.02,
                   time_zone=-5)
    daylight_saving = AnalysisPeriod(st_month=3,
                                     st_day=8,
                                     st_hour=2,
                                     end_month=11,
                                     end_day=1,
                                     end_hour=2)
    sp = Sunpath.from_location(nyc, daylight_saving_period=daylight_saving)
    dt1 = DateTime(6, 21, 12, 0)
    dt2 = DateTime(12, 21, 12, 0)
    dt3 = DateTime(6, 21, 0)
    dt4 = DateTime(12, 21, 0)

    assert sp.is_daylight_saving_hour(dt1)
    assert not sp.is_daylight_saving_hour(dt2)
    assert sp.is_daylight_saving_hour(dt3)
    assert not sp.is_daylight_saving_hour(dt4)

    sun1ds = sp.calculate_sun_from_date_time(dt1)
    sun2ds = sp.calculate_sun_from_date_time(dt2)
    sun3ds = sp.calculate_sun_from_date_time(dt3)
    sun4ds = sp.calculate_sun_from_date_time(dt4)

    sp.daylight_saving_period = None

    assert sun1ds != sp.calculate_sun_from_date_time(dt1)
    assert sun3ds != sp.calculate_sun_from_date_time(dt3)
    assert sun1ds.altitude == \
        approx(sp.calculate_sun_from_date_time(dt1.sub_hour(1)).altitude, rel=1e-2)
    assert sun3ds.altitude == \
        approx(sp.calculate_sun_from_date_time(dt3.sub_hour(1)).altitude, rel=1e-2)

    sun2 = sp.calculate_sun_from_date_time(dt2)
    sun4 = sp.calculate_sun_from_date_time(dt4)
    assert sun2 == sun2ds
    assert sun4 == sun4ds
Beispiel #28
0
def test_schedule_ruleset_data_collection():
    """Test the ScheduleRuleset data_collection 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)

    sch_data = schedule.data_collection()
    assert len(sch_data) == 8760
    assert isinstance(sch_data.header.data_type, fraction.Fraction)
    assert sch_data.header.unit == 'fraction'
    assert sch_data.header.analysis_period == AnalysisPeriod()
Beispiel #29
0
def test_pmv_collection_humidity_ratio_outputs():
    """Test the humudity ratio outputs of the PMV collection."""
    calc_length = 24
    air_temp_header = Header(Temperature(), 'C', AnalysisPeriod(end_month=1, end_day=1))
    air_temp = HourlyContinuousCollection(air_temp_header, [24] * calc_length)
    pmv_obj = PMV(air_temp, 90)

    assert isinstance(pmv_obj.humidity_ratio, HourlyContinuousCollection)
    assert len(pmv_obj.humidity_ratio.values) == calc_length
    assert pmv_obj.humidity_ratio[0] == pytest.approx(0.016939, rel=1e-3)

    hr_par = PMVParameter(humid_ratio_upper=0.012)
    pmv_obj = PMV(air_temp, 90, comfort_parameter=hr_par)
    assert pmv_obj._hr_calculated is True
    assert pmv_obj._hr_comfort_required is True

    assert pmv_obj.humidity_ratio[0] == pytest.approx(0.016939, rel=1e-3)
    assert pmv_obj.is_comfortable[0] == 0
    assert pmv_obj.thermal_condition[0] == 0
    assert pmv_obj.discomfort_reason[0] == 2
Beispiel #30
0
def test_init_horizontal_ref_solarcal_collection():
    """Test the initialization of the HorizontalRefSolarCal collection."""
    calc_length = 24
    irr_header = Header(Irradiance(), 'W/m2',
                        AnalysisPeriod(end_month=1, end_day=1))
    dir_norm = HourlyContinuousCollection(irr_header, [300] * calc_length)
    diff_horiz = HourlyContinuousCollection(irr_header, [100] * calc_length)
    ref_horiz = HourlyContinuousCollection(irr_header, [100] * calc_length)
    solarcal_obj = HorizontalRefSolarCal(Location(), dir_norm, diff_horiz,
                                         ref_horiz, 24)

    assert solarcal_obj.comfort_model == 'Horizontal Reflected SolarCal'
    assert solarcal_obj.calc_length == calc_length
    str(solarcal_obj)  # test that the string representation is ok

    assert isinstance(solarcal_obj.direct_horizontal_solar,
                      HourlyContinuousCollection)
    assert len(solarcal_obj.direct_horizontal_solar.values) == calc_length
    assert solarcal_obj.direct_horizontal_solar[12] == 300
    assert isinstance(solarcal_obj.diffuse_horizontal_solar,
                      HourlyContinuousCollection)
    assert len(solarcal_obj.diffuse_horizontal_solar.values) == calc_length
    assert solarcal_obj.diffuse_horizontal_solar[12] == 100
    assert isinstance(solarcal_obj.reflected_horizontal_solar,
                      HourlyContinuousCollection)
    assert len(solarcal_obj.reflected_horizontal_solar.values) == calc_length
    assert solarcal_obj.reflected_horizontal_solar[12] == 100

    assert isinstance(solarcal_obj.effective_radiant_field,
                      HourlyContinuousCollection)
    assert len(solarcal_obj.effective_radiant_field.values) == calc_length
    assert solarcal_obj.effective_radiant_field[12] == pytest.approx(79.35027,
                                                                     rel=1e-3)
    assert isinstance(solarcal_obj.mrt_delta, HourlyContinuousCollection)
    assert len(solarcal_obj.mrt_delta.values) == calc_length
    assert solarcal_obj.mrt_delta[12] == pytest.approx(18.20503, rel=1e-3)
    assert isinstance(solarcal_obj.mean_radiant_temperature,
                      HourlyContinuousCollection)
    assert len(solarcal_obj.mean_radiant_temperature.values) == calc_length
    assert solarcal_obj.mean_radiant_temperature[12] == pytest.approx(42.20503,
                                                                      rel=1e-3)
Beispiel #31
0
def build_collection(values, dates, data_type, unit, time_offset, year):
    """Build a data collection from raw noaa data and process it to the timestep.

    Args:
        values: A list of values to be included in the data collection.
        dates: A list of datetime strings that align with the values.
        data_type: Ladybug data type for the data collection.
        unit: Text for the unit of the collection.
        time_offset: Python timedelta object to correct for the time zone.
        year: Integer for the year of the data.
    """
    if values == []:
        return None

    # convert date codes into datetimes and ensure no duplicates
    leap_yr = True if year % 4 == 0 else False
    datetimes = []
    clean_values = []
    for i, (dat, val) in enumerate(zip(dates, values)):
        if dat != dates[i - 1]:
            yr, month, day, hr, minute = int(dat[:4]), int(dat[5:7]), \
                int(dat[8:10]), int(dat[11:13]), int(dat[14:16])
            py_dat = datetime.datetime(yr, month, day, hr, minute) + time_offset
            if py_dat.year == year:
                lb_dat = DateTime(py_dat.month, py_dat.day, py_dat.hour,
                                  py_dat.minute, leap_year=leap_yr)
                datetimes.append(lb_dat)
                clean_values.append(val)

    # make a discontinuous cata collection
    data_header = Header(data_type, unit, AnalysisPeriod(is_leap_year=leap_yr))
    data_init = HourlyDiscontinuousCollection(data_header, clean_values, datetimes)
    data_final = data_init.validate_analysis_period()

    # cull out unwanted timesteps.
    if _timestep_:
        data_final.convert_to_culled_timestep(_timestep_)
    else:
        data_final.convert_to_culled_timestep(1)

    return data_final