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)
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)
示例#4
0
def validate_sim_par(sim_par_json):
    """Validate all properties of a SimulationParameter JSON against the Honeybee schema.

    \b
    Args:
        sim_par_json: Full path to a SimulationParameter JSON file.
    """
    try:
        # first check the JSON against the OpenAPI specification
        click.echo('Validating SimulationParameter JSON ...')
        schema_simulation_parameter.SimulationParameter.parse_file(
            sim_par_json)
        click.echo('Pydantic validation passed.')
        # re-serialize to make sure no errors are found in re-serialization
        with open(sim_par_json) as json_file:
            data = json.load(json_file)
        SimulationParameter.from_dict(data)
        click.echo('Python re-serialization passed.')
        # if we made it to this point, report that the object is valid
        click.echo('Congratulations! Your SimulationParameter JSON is valid!')
    except Exception as e:
        _logger.exception(
            'SimulationParameter validation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
示例#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
示例#6
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)
示例#7
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
示例#8
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)
示例#9
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'
示例#10
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)
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)
示例#12
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']
示例#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
示例#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
示例#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
示例#16
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
示例#17
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)
示例#18
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)
示例#19
0
def dict_to_simulation(sim_dict, raise_exception=True):
    """Get a Python object of any Simulation object from a dictionary.

    Args:
        sim_dict: A dictionary of any Honeybee energy simulation object. Note
            that this should be a non-abridged dictionary to be valid.
        raise_exception: Boolean to note whether an excpetion should be raised
            if the object is not identified as a simulation object. Default: True.

    Returns:
        A Python object derived from the input sim_dict.
    """
    try:  # get the type key from the dictionary
        sim_type = sim_dict['type']
    except KeyError:
        raise ValueError('Simulation dictionary lacks required "type" key.')

    if sim_type == 'SimulationControl':
        return SimulationControl.from_dict(sim_dict)
    elif sim_type == 'RunPeriod':
        return RunPeriod.from_dict(sim_dict)
    elif sim_type == 'DaylightSavingTime':
        return DaylightSavingTime.from_dict(sim_dict)
    elif sim_type == 'ShadowCalculation':
        return ShadowCalculation.from_dict(sim_dict)
    elif sim_type == 'SizingParameter':
        return SizingParameter.from_dict(sim_dict)
    elif sim_type == 'SimulationOutput':
        return SimulationOutput.from_dict(sim_dict)
    elif sim_type == 'SimulationParameter':
        return SimulationParameter.from_dict(sim_dict)
    elif raise_exception:
        raise ValueError(
            '{} is not a recognized energy Simulation type'.format(sim_type))
示例#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)
示例#21
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
示例#22
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
示例#23
0
def test_default_sim_par():
    """Test the default_sim_par command."""
    runner = CliRunner()
    ddy_path = './tests/ddy/chicago.ddy'

    result = runner.invoke(default_sim_par, [ddy_path])
    assert result.exit_code == 0
    simpar_dict = json.loads(result.output)
    sim_par = SimulationParameter.from_dict(simpar_dict)

    assert 'Zone Ideal Loads Supply Air Total Cooling Energy' in sim_par.output.outputs
    assert 'Chiller Electricity Energy' in sim_par.output.outputs
示例#24
0
def test_comfort_sim_par():
    """Test the comfort_sim_par command."""
    runner = CliRunner()
    ddy_path = './tests/ddy/chicago.ddy'

    result = runner.invoke(comfort_sim_par, [ddy_path])
    assert result.exit_code == 0
    simpar_dict = json.loads(result.output)
    sim_par = SimulationParameter.from_dict(simpar_dict)

    assert 'Zone Mean Air Temperature' in sim_par.output.outputs
    assert 'Surface Inside Face Temperature' in sim_par.output.outputs
def test_custom_sim_par():
    """Test the custom_sim_par command."""
    runner = CliRunner()
    ddy_path = './tests/ddy/chicago.ddy'

    result = runner.invoke(
        custom_sim_par,
        [ddy_path, 'Surface Window Transmitted Beam Solar Radiation Energy'])
    assert result.exit_code == 0
    simpar_dict = json.loads(result.output)
    sim_par = SimulationParameter.from_dict(simpar_dict)

    assert 'Surface Window Transmitted Beam Solar Radiation Energy' in sim_par.output.outputs
示例#26
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)
示例#27
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)
示例#28
0
def test_load_balance_sim_par():
    """Test the load_balance_sim_par command."""
    runner = CliRunner()
    ddy_path = './tests/ddy/chicago.ddy'

    result = runner.invoke(load_balance_sim_par, [ddy_path, '--load-type', 'Sensible'])
    assert result.exit_code == 0
    simpar_dict = json.loads(result.output)
    sim_par = SimulationParameter.from_dict(simpar_dict)

    assert 'Zone Ideal Loads Supply Air Sensible Cooling Energy' \
        in sim_par.output.outputs
    assert 'Zone People Sensible Heating Energy' in sim_par.output.outputs
示例#29
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)
示例#30
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'