Example #1
0
def test_simulation_parameter_equality():
    """Test the equality of SimulationParameter objects."""
    sim_par = SimulationParameter()
    sim_par_dup = sim_par.duplicate()
    sim_par_alt = SimulationParameter(timestep=4)

    assert sim_par is sim_par
    assert sim_par is not sim_par_dup
    assert sim_par == sim_par_dup
    sim_par_dup.timestep = 12
    assert sim_par != sim_par_dup
    assert sim_par != sim_par_alt
Example #2
0
def test_simulation_parameter_to_dict_detailed():
    """Test the to_dict method with a detailed SimulationParameter."""
    sim_par = SimulationParameter()
    output = SimulationOutput()
    output.add_zone_energy_use()
    output.include_html = True
    output.reporting_frequency = 'Daily'
    output.add_summary_report('Annual Building Utility Performance Summary')
    output.add_summary_report('Climatic Data Summary')
    output.add_summary_report('Envelope Summary')
    sim_par.output = output
    run_period = RunPeriod(Date(1, 1), Date(6, 21))
    run_period.daylight_saving_time = DaylightSavingTime(
        Date(3, 12), Date(11, 5))
    run_period.start_day_of_week = 'Monday'
    run_period.holidays = [Date(1, 1), Date(3, 17), Date(7, 4)]
    sim_par.run_period = run_period
    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
    shadow_calc_alt = ShadowCalculation(calculation_frequency=20)
    sim_par.shadow_calculation = shadow_calc_alt
    sizing_alt = SizingParameter(None, 1, 1)
    relative_path = './tests/ddy/chicago.ddy'
    sizing_alt.add_from_ddy_996_004(relative_path)
    sim_par.sizing_parameter = sizing_alt

    sim_par_dict = sim_par.to_dict()

    assert 'outputs' in sim_par_dict['output']
    assert 'holidays' in sim_par_dict['run_period']
    assert 'daylight_saving_time' in sim_par_dict['run_period']
    assert 'design_days' in sim_par_dict['sizing_parameter']
Example #3
0
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'
Example #4
0
def test_run_idf_5vertex():
    """Test the run_idf methods with 5-vertex apertures."""
    # Get input Model
    input_hb_model = './tests/json/model_colinear_verts.json'
    with open(input_hb_model) as json_file:
        data = json.load(json_file)
    model = Model.from_dict(data)

    # 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(1, 7)

    # 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_5verts',
                       '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
Example #5
0
def test_run_idf():
    """Test the prepare_idf_for_simulation and run_idf methods."""
    # Get input Model
    room = Room.from_box('TinyHouseZone', 5, 10, 3)
    room.properties.energy.program_type = office_program
    room.properties.energy.add_default_ideal_air()
    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(1, 7)

    # 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',
                       '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 simulation_par_detailed(directory):
    sim_par = SimulationParameter()
    output = SimulationOutput()
    output.add_zone_energy_use()
    output.include_html = True
    output.reporting_frequency = 'Daily'
    output.add_summary_report('Annual Building Utility Performance Summary')
    output.add_summary_report('Climatic Data Summary')
    output.add_summary_report('Envelope Summary')
    sim_par.output = output
    run_period = RunPeriod(Date(1, 1), Date(6, 21))
    run_period.daylight_saving_time = DaylightSavingTime(Date(3, 12), Date(11, 5))
    run_period.start_day_of_week = 'Monday'
    run_period.holidays = [Date(1, 1), Date(3, 17), Date(7, 4)]
    sim_par.run_period = run_period
    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
    shadow_calc_alt = ShadowCalculation(
        solar_distribution='FullInteriorAndExteriorWithReflections',
        calculation_method='PixelCounting', calculation_update_method='Timestep')
    sim_par.shadow_calculation = shadow_calc_alt
    sizing_alt = SizingParameter(None, 1, 1)
    relative_path = './scripts/ddy/chicago.ddy'
    sizing_alt.add_from_ddy_996_004(relative_path)
    sim_par.sizing_parameter = sizing_alt

    dest_file = os.path.join(directory, 'simulation_par_detailed.json')
    with open(dest_file, 'w') as fp:
        json.dump(sim_par.to_dict(), fp, indent=4)
def default_sim_par(ddy_file, run_period_json, filter_des_days, output_file):
    """Get a SimulationParameter JSON with default outputs for energy use only.
    \n
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
    """
    try:
        assert os.path.isfile(ddy_file), 'No DDY file found at {}.'.format(
            ddy_file)
        sim_par = SimulationParameter()
        sim_par.output.add_zone_energy_use()
        sim_par.output.add_hvac_energy_use()
        if run_period_json:
            assert os.path.isfile(run_period_json), \
                'No run period JSON file found at {}.'.format(run_period_json)
            with open(run_period_json) as json_file:
                data = json.load(json_file)
            sim_par.run_period = RunPeriod.from_dict(data)
        if filter_des_days:
            sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file)
        else:
            sim_par.sizing_parameter.add_from_ddy(ddy_file)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
def custom_sim_par(ddy_file, output_names, run_period_json, filter_des_days,
                   output_file):
    """Get a SimulationParameter JSON with outputs for thermal load balances.
    \n
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
        output_names: A list of EnergyPlus output names as strings (eg.
            'Surface Window System Solar Transmittance'. These outputs will be
            requested from the simulation.
    """
    try:
        assert os.path.isfile(ddy_file), 'No DDY file found at {}.'.format(
            ddy_file)
        sim_par = SimulationParameter()
        for output_name in output_names:
            sim_par.output.add_output(output_name)
        if run_period_json:
            assert os.path.isfile(run_period_json), \
                'No run period JSON file found at {}.'.format(run_period_json)
            with open(run_period_json) as json_file:
                data = json.load(json_file)
            sim_par.run_period = RunPeriod.from_dict(data)
        if filter_des_days:
            sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file)
        else:
            sim_par.sizing_parameter.add_from_ddy(ddy_file)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
def load_balance_sim_par(ddy_file, load_type, run_period_json, filter_des_days,
                         output_file):
    """Get a SimulationParameter JSON with outputs for thermal load balances.
    \n
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
    """
    try:
        assert os.path.isfile(ddy_file), 'No DDY file found at {}.'.format(
            ddy_file)
        sim_par = SimulationParameter()
        sim_par.output.add_zone_energy_use(load_type)
        gl_load_type = load_type if load_type != 'All' else 'Total'
        sim_par.output.add_gains_and_losses(gl_load_type)
        sim_par.output.add_surface_energy_flow()
        if run_period_json:
            assert os.path.isfile(run_period_json), \
                'No run period JSON file found at {}.'.format(run_period_json)
            with open(run_period_json) as json_file:
                data = json.load(json_file)
            sim_par.run_period = RunPeriod.from_dict(data)
        if filter_des_days:
            sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file)
        else:
            sim_par.sizing_parameter.add_from_ddy(ddy_file)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #10
0
def custom_sim_par(ddy_file, output_names, run_period, north, filter_des_days,
                   output_file):
    """Get a SimulationParameter JSON with an option for custom outputs.

    \b
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
        output_names: Any number of EnergyPlus output names as strings (eg.
            'Surface Window System Solar Transmittance'. These outputs will be
            requested from the simulation.
    """
    try:
        sim_par = SimulationParameter()
        for output_name in output_names:
            sim_par.output.add_output(output_name)
        _apply_run_period(run_period, sim_par)
        sim_par.north_angle = north
        _apply_design_days(ddy_file, filter_des_days, sim_par)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #11
0
def sizing_sim_par(ddy_file, load_type, north, filter_des_days, output_file):
    """Get a SimulationParameter JSON with outputs and run period for HVAC sizing.

    \b
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
    """
    try:
        sim_par = SimulationParameter()
        sim_par.output.add_zone_energy_use(load_type)
        gl_load_type = load_type if load_type != 'All' else 'Total'
        sim_par.output.add_gains_and_losses(gl_load_type)
        sim_par.output.add_surface_energy_flow()
        sim_par.simulation_control = SimulationControl(True, True, True, True,
                                                       False)
        sim_par.north_angle = north
        _apply_design_days(ddy_file, filter_des_days, sim_par)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #12
0
def orientation_sim_pars(ddy_file, north_angles, output_name, run_period,
                         start_north, filter_des_days, folder, log_file):
    """Get SimulationParameter JSONs with different north angles for orientation studies.

    \b
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
        north_angles: Any number of values between -360 and 360 for the counterclockwise
            difference between the North and the positive Y-axis in degrees. 90 is
            West and 270 is East.
    """
    try:
        # get a default folder if none was specified
        if folder is None:
            folder = os.path.join(folders.default_simulation_folder,
                                  'orientation_study')
        preparedir(folder, remove_content=False)

        # create a base set of simulation parameters to be edited parametrically
        sim_par = SimulationParameter()
        for out_name in output_name:
            sim_par.output.add_output(out_name)
        _apply_run_period(run_period, sim_par)
        _apply_design_days(ddy_file, filter_des_days, sim_par)

        # shift all of the north angles by the start_north if specified
        if start_north != 0:
            north_angles = [angle + start_north for angle in north_angles]
            for i, angle in enumerate(north_angles):
                angle = angle - 360 if angle > 360 else angle
                angle = angle + 360 if angle < -360 else angle
                north_angles[i] = angle

        # loop through the north angles and write a simulation parameter for each
        json_files = []
        for angle in north_angles:
            sim_par.north_angle = angle
            base_name = 'sim_par_north_{}'.format(int(angle))
            file_name = '{}.json'.format(base_name)
            file_path = os.path.join(folder, file_name)
            with open(file_path, 'w') as fp:
                json.dump(sim_par.to_dict(), fp)
            sp_info = {
                'id': base_name,
                'path': file_name,
                'full_path': os.path.abspath(file_path)
            }
            json_files.append(sp_info)
        log_file.write(json.dumps(json_files))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameters.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #13
0
def test_simulation_parameter_to_dict_simple():
    """Test the to_dict method with a simple SimulationParameter."""
    sim_par = SimulationParameter()
    sim_par_dict = sim_par.to_dict()

    assert 'output' in sim_par_dict
    assert 'run_period' in sim_par_dict
    assert 'timestep' in sim_par_dict
    assert 'simulation_control' in sim_par_dict
    assert 'shadow_calculation' in sim_par_dict
    assert 'sizing_parameter' in sim_par_dict
Example #14
0
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
Example #15
0
def test_run_idf_window_shade():
    """Test the Model.to.idf and run_idf method with a model that has a window shade."""
    # Get input Model
    room = Room.from_box('TinyHouseZone', 5, 10, 3)
    room.properties.energy.program_type = office_program
    room.properties.energy.add_default_ideal_air()

    double_clear = WindowConstruction('Double Pane Clear',
                                      [clear_glass, air_gap, clear_glass])
    shade_mat = EnergyWindowMaterialShade('Low-e Diffusing Shade', 0.005, 0.15,
                                          0.5, 0.25, 0.5, 0, 0.4, 0.2, 0.1,
                                          0.75, 0.25)
    sched = ScheduleRuleset.from_daily_values('NighSched', [
        1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1
    ])
    double_ec = WindowConstructionShade('Double Low-E Inside EC', double_clear,
                                        shade_mat, 'Interior',
                                        'OnIfHighSolarOnWindow', 200, sched)

    south_face = room[3]
    south_face.apertures_by_ratio(0.4, 0.01)
    south_face.apertures[0].properties.energy.construction = double_ec
    north_face = room[1]
    north_face.apertures_by_ratio(0.4, 0.01)

    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(1, 7)

    # 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_shd',
                       '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
Example #16
0
def model_to_osm(model_json, sim_par_json, folder, check_model, log_file):
    """Translate a Model JSON file into an OpenStudio Model and corresponding IDF.
    \n
    Args:
        model_json: Full path to a Model JSON file.
    """
    try:
        # check that the model JSON is there
        assert os.path.isfile(model_json), \
            'No Model JSON file found at {}.'.format(model_json)

        # set the default folder if it's not specified
        if folder is None:
            folder = os.path.dirname(os.path.abspath(model_json))

        # check that the simulation parameters are there
        if sim_par_json is not None:
            assert os.path.isfile(sim_par_json), \
                'No simulation parameter file found at {}.'.format(sim_par_json)
        else:
            sim_par = SimulationParameter()
            sim_par.output.add_zone_energy_use()
            sim_par.output.add_hvac_energy_use()
            sim_par_dict = sim_par.to_dict()
            sp_json = os.path.abspath(
                os.path.join(folder, 'simulation_parameter.json'))
            with open(sp_json, 'w') as fp:
                json.dump(sim_par_dict, fp)

        # run the Model re-serialization and check if specified
        if check_model:
            model_json = measure_compatible_model_json(model_json, folder)

        # Write the osw file to translate the model to osm
        osw = to_openstudio_osw(folder, model_json, sim_par_json)

        # run the measure to translate the model JSON to an openstudio measure
        if osw is not None and os.path.isfile(osw):
            osm, idf = run_osw(osw)
            # run the resulting idf through EnergyPlus
            if idf is not None and os.path.isfile(idf):
                log_file.write(json.dumps([osm, idf]))
            else:
                raise Exception('Running OpenStudio CLI failed.')
        else:
            raise Exception('Writing OSW file failed.')
    except Exception as e:
        _logger.exception('Model translation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #17
0
def model_to_idf(model_json, sim_par_json, additional_str, output_file):
    """Translate a Model JSON file to an IDF using direct-to-idf translators.
    \n
    The resulting IDF should be simulate-able but not all Model properties might
    make it into the IDF given that the direct-to-idf translators are used.
    \n
    Args:
        model_json: Full path to a Model JSON file.
    """
    try:
        # check that the model JSON is there
        assert os.path.isfile(model_json), \
            'No Model JSON file found at {}.'.format(model_json)

        # check that the simulation parameters are there and load them
        if sim_par_json is not None:
            assert os.path.isfile(sim_par_json), \
                'No simulation parameter file found at {}.'.format(sim_par_json)
            with open(sim_par_json) as json_file:
                data = json.load(json_file)
            sim_par = SimulationParameter.from_dict(data)
        else:
            sim_par = SimulationParameter()
            sim_par.output.add_zone_energy_use()
            sim_par.output.add_hvac_energy_use()

        # re-serialize the Model to Python
        with open(model_json) as json_file:
            data = json.load(json_file)
        model = Model.from_dict(data)

        # set the schedule directory in case it is needed
        sch_path = os.path.abspath(model_json) if 'stdout' in str(output_file) \
            else os.path.abspath(str(output_file))
        sch_directory = os.path.join(os.path.split(sch_path)[0], 'schedules')

        # create the strings for simulation paramters and model
        ver_str = energyplus_idf_version() if folders.energyplus_version \
            is not None else energyplus_idf_version((9, 2, 0))
        sim_par_str = sim_par.to_idf()
        model_str = model.to.idf(model, schedule_directory=sch_directory)
        idf_str = '\n\n'.join(
            [ver_str, sim_par_str, model_str, additional_str])

        # write out the IDF file
        output_file.write(idf_str)
    except Exception as e:
        _logger.exception('Model translation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #18
0
def test_simulation_parameter_init():
    """Test the initialization of SimulationParameter and basic properties."""
    sim_par = SimulationParameter()
    str(sim_par)  # test the string representation

    assert sim_par.output == SimulationOutput()
    assert sim_par.run_period == RunPeriod()
    assert sim_par.timestep == 6
    assert sim_par.simulation_control == SimulationControl()
    assert sim_par.shadow_calculation == ShadowCalculation()
    assert sim_par.sizing_parameter == SizingParameter()
    assert sim_par.north_angle == 0
    assert sim_par.north_vector == Vector2D(0, 1)
    assert sim_par.terrain_type == 'City'
Example #19
0
def test_run_idf_daylight_control():
    """Test Model.to.idf and run_idf with a model possessing daylight controls."""
    room = Room.from_box('TinyHouseZone', 5, 10, 3)
    room.properties.energy.program_type = office_program
    room.properties.energy.add_default_ideal_air()
    south_face = room[3]
    south_face.apertures_by_ratio(0.4, 0.01)

    room.properties.energy.add_daylight_control_to_center(0.8, 500, 0.5)
    sens_pt = room.properties.energy.daylighting_control.sensor_position
    assert sens_pt.x == pytest.approx(2.5, rel=1e-3)
    assert sens_pt.y == pytest.approx(5, rel=1e-3)
    assert sens_pt.z == pytest.approx(0.8, rel=1e-3)
    room.move(Vector3D(5, 5, 0))
    assert room.properties.energy.daylighting_control.sensor_position == \
        sens_pt.move(Vector3D(5, 5, 0))

    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_daylight',
                       '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
Example #20
0
def model_to_idf(model_json, sim_par_json, additional_str, output_file):
    """Translate a Model JSON file to an IDF using direct-to-idf translators.

    If the model contains a feature that is not translate-able through direct-to-idf
    translators, an exception will be raised.

    \b
    Args:
        model_json: Full path to a Model JSON file.
    """
    try:
        # load simulation parameters or generate default ones
        if sim_par_json is not None:
            with open(sim_par_json) as json_file:
                data = json.load(json_file)
            sim_par = SimulationParameter.from_dict(data)
        else:
            sim_par = SimulationParameter()
            sim_par.output.add_zone_energy_use()
            sim_par.output.add_hvac_energy_use()

        # re-serialize the Model to Python
        with open(model_json) as json_file:
            data = json.load(json_file)
        model = Model.from_dict(data)

        # set the schedule directory in case it is needed
        sch_path = os.path.abspath(model_json) if 'stdout' in str(output_file) \
            else os.path.abspath(str(output_file))
        sch_directory = os.path.join(os.path.split(sch_path)[0], 'schedules')

        # create the strings for simulation paramters and model
        ver_str = energyplus_idf_version() if folders.energyplus_version \
            is not None else ''
        sim_par_str = sim_par.to_idf()
        model_str = model.to.idf(model, schedule_directory=sch_directory)
        idf_str = '\n\n'.join(
            [ver_str, sim_par_str, model_str, additional_str])

        # write out the IDF file
        output_file.write(idf_str)
    except Exception as e:
        _logger.exception('Model translation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #21
0
def test_run_idf_hot_water():
    """Test the Model.to.idf and run_idf method with a model possessing hot water."""
    # Get input Model
    room = Room.from_box('TinyHouseZone', 5, 10, 3)
    room.properties.energy.program_type = office_program
    simple_office = ScheduleDay(
        'Simple Weekday', [0, 1, 0],
        [Time(0, 0), Time(9, 0), Time(17, 0)])
    schedule = ScheduleRuleset('Office Water Use', simple_office, None,
                               schedule_types.fractional)
    shw = ServiceHotWater('Office Hot Water', 0.1, schedule)
    room.properties.energy.service_hot_water = shw
    room.properties.energy.add_default_ideal_air()
    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(1, 7)

    # 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_shw',
                       '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
Example #22
0
def test_to_openstudio_osw():
    """Test to_openstudio_osw."""
    # create the model
    room = Room.from_box('TinyHouseZone', 5, 10, 3)
    model = Model('TinyHouse', [room])
    model_json_path = './tests/simulation/model_osw_test.json'
    with open(model_json_path, 'w') as fp:
        json.dump(model.to_dict(included_prop=['energy']), fp)

    # create the simulation parameter
    sim_par = SimulationParameter()
    sim_par.output.add_zone_energy_use()
    simpar_json_path = './tests/simulation/simpar_osw_test.json'
    with open(simpar_json_path, 'w') as fp:
        json.dump(sim_par.to_dict(), fp)

    # create additional measures
    measure_path = './tests/measure/edit_fraction_radiant_of_lighting_and_equipment'
    measure = Measure(measure_path)
    measure.arguments[0].value = 0.25
    measure.arguments[1].value = 0.25

    # test it without measures
    folder = './tests/simulation/'
    osw_path = os.path.join(folder, 'workflow.osw')

    osw = to_openstudio_osw(folder, model_json_path, simpar_json_path)
    assert os.path.isfile(osw_path)
    os.remove(osw_path)

    # test it with measures
    osw = to_openstudio_osw(folder,
                            model_json_path,
                            additional_measures=[measure])
    assert os.path.isfile(osw_path)
    os.remove(osw_path)

    os.remove(model_json_path)
    os.remove(simpar_json_path)
Example #23
0
def default_sim_par(ddy_file, run_period, north, filter_des_days, output_file):
    """Get a SimulationParameter JSON with default outputs for energy use only.

    \b
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
    """
    try:
        sim_par = SimulationParameter()
        sim_par.output.add_zone_energy_use()
        sim_par.output.add_hvac_energy_use()
        _apply_run_period(run_period, sim_par)
        sim_par.north_angle = north
        _apply_design_days(ddy_file, filter_des_days, sim_par)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #24
0
def comfort_sim_par(ddy_file, run_period, north, filter_des_days, output_file):
    """Get a SimulationParameter JSON with outputs for thermal comfort mapping.

    \b
    Args:
        ddy_file: Full path to a DDY file that will be used to specify design days
            within the simulation parameter.
    """
    try:
        sim_par = SimulationParameter()
        sim_par.output.add_comfort_metrics()
        sim_par.output.add_surface_temperature()
        _apply_run_period(run_period, sim_par)
        sim_par.north_angle = north
        _apply_design_days(ddy_file, filter_des_days, sim_par)
        output_file.write(json.dumps(sim_par.to_dict()))
    except Exception as e:
        _logger.exception(
            'Failed to generate simulation parameter.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Example #25
0
def test_simulation_parameter_init_from_idf():
    """Test the initialization of SimulationParameter from_idf."""
    sim_par = SimulationParameter()
    output = SimulationOutput()
    output.add_zone_energy_use()
    sim_par.output = output
    run_period = RunPeriod(Date(1, 1), Date(6, 21))
    sim_par.run_period = run_period
    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
    shadow_calc_alt = ShadowCalculation(calculation_frequency=20)
    sim_par.shadow_calculation = shadow_calc_alt
    sizing_alt = SizingParameter(None, 1, 1)
    relative_path = './tests/ddy/chicago.ddy'
    sizing_alt.add_from_ddy_996_004(relative_path)
    sim_par.sizing_parameter = sizing_alt

    idf_str = sim_par.to_idf()
    rebuilt_sim_par = SimulationParameter.from_idf(idf_str)
    rebuilt_sim_par.sizing_parameter.apply_location(sizing_alt[0].location)
    assert sim_par == rebuilt_sim_par
    assert rebuilt_sim_par.to_idf() == idf_str
Example #26
0
def test_simulation_parameter_dict_methods():
    """Test the to/from dict methods."""
    sim_par = SimulationParameter()
    output = SimulationOutput()
    output.add_zone_energy_use()
    sim_par.output = output
    run_period = RunPeriod(Date(1, 1), Date(6, 21))
    sim_par.run_period = run_period
    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
    shadow_calc_alt = ShadowCalculation(calculation_frequency=20)
    sim_par.shadow_calculation = shadow_calc_alt
    sizing_alt = SizingParameter(None, 1, 1)
    relative_path = './tests/ddy/chicago.ddy'
    sizing_alt.add_from_ddy_996_004(relative_path)
    sim_par.sizing_parameter = sizing_alt

    sim_par_dict = sim_par.to_dict()
    new_sim_par = SimulationParameter.from_dict(sim_par_dict)
    new_sim_par.sizing_parameter.apply_location(sizing_alt[0].location)
    assert new_sim_par == sim_par
    assert sim_par_dict == new_sim_par.to_dict()
                   tolerance=tolerance,
                   angle_tolerance=angle_tolerance)
    floor_area = _model.floor_area
    assert floor_area != 0, 'Connected _rooms have no floors with which to compute EUI.'
    floor_area = floor_area * conversion_to_meters()**2
    mults = {rm.identifier.upper(): rm.multiplier for rm in _model.rooms}
    mults = None if all(mul == 1 for mul in mults.values()) else mults

    # process the simulation folder name and the directory
    directory = os.path.join(folders.default_simulation_folder,
                             _model.identifier)
    sch_directory = os.path.join(directory, 'schedules')
    nukedir(directory)  # delete any existing files in the directory

    # create simulation parameters for the coarsest/fastest E+ sim possible
    _sim_par_ = SimulationParameter()
    _sim_par_.timestep = _timestep_ if _timestep_ is not None else 1
    _sim_par_.shadow_calculation.solar_distribution = 'FullExterior'
    _sim_par_.output.add_zone_energy_use()
    _sim_par_.output.reporting_frequency = 'Monthly'
    if run_bal_:
        _sim_par_.output.add_output(gl_el_equip_out)
        _sim_par_.output.add_output(gl_gas_equip_out)
        _sim_par_.output.add_output(gl1_shw_out)
        _sim_par_.output.add_output(gl2_shw_out)
        _sim_par_.output.add_gains_and_losses('Total')
        _sim_par_.output.add_surface_energy_flow()
    # set the north if it is not defaulted
    if _north_ is not None:
        try:
            _sim_par_.north_vector = to_vector2d(_north_)
def simulation_par_simple(directory):
    sim_par = SimulationParameter()

    dest_file = os.path.join(directory, 'simulation_par_simple.json')
    with open(dest_file, 'w') as fp:
        json.dump(sim_par.to_dict(), fp, indent=4)
Example #29
0
def simulate_model(model_json, epw_file, sim_par_json, base_osw, folder,
                   check_model, log_file):
    """Simulate a Model JSON file in EnergyPlus.

    \b
    Args:
        model_json: Full path to a Model JSON file.
        epw_file: Full path to an .epw file.
    """
    try:
        # get a ddy variable that might get used later
        epw_folder, epw_file_name = os.path.split(epw_file)
        ddy_file = os.path.join(epw_folder,
                                epw_file_name.replace('.epw', '.ddy'))

        # set the default folder to the default if it's not specified
        if folder is None:
            proj_name = \
                os.path.basename(model_json).replace('.json', '').replace('.hbjson', '')
            folder = os.path.join(folders.default_simulation_folder, proj_name,
                                  'OpenStudio')
        preparedir(folder, remove_content=False)

        # process the simulation parameters and write new ones if necessary
        def ddy_from_epw(epw_file, sim_par):
            """Produce a DDY from an EPW file."""
            epw_obj = EPW(epw_file)
            des_days = [
                epw_obj.approximate_design_day('WinterDesignDay'),
                epw_obj.approximate_design_day('SummerDesignDay')
            ]
            sim_par.sizing_parameter.design_days = des_days

        def write_sim_par(sim_par):
            """Write simulation parameter object to a JSON."""
            sim_par_dict = sim_par.to_dict()
            sp_json = os.path.abspath(
                os.path.join(folder, 'simulation_parameter.json'))
            with open(sp_json, 'w') as fp:
                json.dump(sim_par_dict, fp)
            return sp_json

        if sim_par_json is None:  # generate some default simulation parameters
            sim_par = SimulationParameter()
            sim_par.output.add_zone_energy_use()
            sim_par.output.add_hvac_energy_use()
        else:
            with open(sim_par_json) as json_file:
                data = json.load(json_file)
            sim_par = SimulationParameter.from_dict(data)
        if len(sim_par.sizing_parameter.design_days) == 0 and os.path.isfile(
                ddy_file):
            try:
                sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file)
            except AssertionError:  # no design days within the DDY file
                ddy_from_epw(epw_file, sim_par)
        elif len(sim_par.sizing_parameter.design_days) == 0:
            ddy_from_epw(epw_file, sim_par)
        sim_par_json = write_sim_par(sim_par)

        # run the Model re-serialization and check if specified
        if check_model:
            model_json = measure_compatible_model_json(model_json, folder)

        # Write the osw file to translate the model to osm
        osw = to_openstudio_osw(folder,
                                model_json,
                                sim_par_json,
                                base_osw=base_osw,
                                epw_file=epw_file)

        # run the measure to translate the model JSON to an openstudio measure
        if osw is not None and os.path.isfile(osw):
            gen_files = [osw]
            if base_osw is None:  # separate the OS CLI run from the E+ run
                osm, idf = run_osw(osw)
                # run the resulting idf through EnergyPlus
                if idf is not None and os.path.isfile(idf):
                    gen_files.extend([osm, idf])
                    sql, eio, rdd, html, err = run_idf(idf, epw_file)
                    if err is not None and os.path.isfile(err):
                        gen_files.extend([sql, eio, rdd, html, err])
                    else:
                        raise Exception('Running EnergyPlus failed.')
                else:
                    raise Exception('Running OpenStudio CLI failed.')
            else:  # run the whole simulation with the OpenStudio CLI
                osm, idf = run_osw(osw, measures_only=False)
                if idf is not None and os.path.isfile(idf):
                    gen_files.extend([osm, idf])
                else:
                    raise Exception('Running OpenStudio CLI failed.')
                sql, eio, rdd, html, err = output_energyplus_files(
                    os.path.dirname(idf))
                if os.path.isfile(err):
                    gen_files.extend([sql, eio, rdd, html, err])
                else:
                    raise Exception('Running EnergyPlus failed.')
            log_file.write(json.dumps(gen_files))
        else:
            raise Exception('Writing OSW file failed.')
    except Exception as e:
        _logger.exception('Model simulation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
_run_period_ = RunPeriod.from_analysis_period(_run_period_) \
    if _run_period_ is not None else RunPeriod()

# set the daylight savings if it is input
if daylight_saving_ is not None:
    daylight_saving = DaylightSavingTime.from_analysis_period(daylight_saving_)
    _run_period_.daylight_saving_time = daylight_saving

# set the holidays if requested.
if len(holidays_) != 0:
    try:
        dates = tuple(Date.from_date_string(date) for date in holidays_)
    except ValueError:
        dates = tuple(DateTime.from_date_time_string(date).date for date in holidays_)
    _run_period_.holidays = dates

# set the start day of the week if it is input
if _start_dow_ is not None:
    _run_period_.start_day_of_week = _start_dow_.title()

# set the default timestep
_timestep_ = _timestep_ if _timestep_ is not None else 6

# return final simulation parameters
sim_par = SimulationParameter(output=_output_,
                              run_period=_run_period_,
                              timestep=_timestep_,
                              simulation_control=_sim_control_,
                              shadow_calculation=_shadow_calc_,
                              sizing_parameter=_sizing_)