def run_osw_and_report_errors(i):
    """Run an OSW through OpenStudio CLI."""
    osw = _osw[i]
    osm_i, idf_i = run_osw(osw, silent=silent)
    # process the additional strings
    if add_str_ != [] and add_str_[0] is not None and idf is not None:
        add_str = '/n'.join(add_str_)
        with open(idf, "a") as idf_file:
            idf_file.write(add_str)
    osm.append(osm_i)
    idf.append(idf_i)

    # run the IDF through EnergyPlus
    if run_:
        sql_i, zsz_i, rdd_i, html_i, err_i = run_idf(idf_i, _epw_file, silent=silent)

        # report any errors on this component
        if err_i is not None:
            err_obj = Err(err_i)
            err_objs.append(err_obj)
            for warn in err_obj.severe_errors:
                give_warning(ghenv.Component, warn)
            for error in err_obj.fatal_errors:
                print err_obj.file_contents  # print before raising the error
                raise Exception(error)

        # append everything to the global lists
        sql.append(sql_i)
        zsz.append(zsz_i)
        rdd.append(rdd_i)
        html.append(html_i)
        err.append(err_i)
def run_osm_and_report_errors(i):
    """Run an OSW through OpenStudio CLI."""
    # create a blank osw for the translation
    osw_dict = {'seed_file': _osm[i], 'weather_file': _epw_file}
    osw_directory = os.path.dirname(_osm[i])
    sch_directory1 = os.path.join(os.path.dirname(osw_directory), 'schedules')
    sch_directory2 = os.path.join(osw_directory, 'schedules')
    if os.path.isdir(sch_directory1):
        osw_dict['file_paths'] = [sch_directory1]
    elif os.path.isdir(sch_directory2):
        osw_dict['file_paths'] = [sch_directory2]
    osw = os.path.join(osw_directory, 'workflow.osw')
    with open(osw, 'w') as fp:
        json.dump(osw_dict, fp, indent=4)

    # get an IDF from the OSM using the OpenStudio CLI
    osm_i, idf_i = run_osw(osw, silent=silent)
    if idf_i is None:
        log_osw = OSW(os.path.join(osw_directory, 'out.osw'))
        errors = []
        print(log_osw.stdout)
        for error, tb in zip(log_osw.errors, log_osw.error_tracebacks):
            print(tb)
            errors.append(error)
        raise Exception('Failed to run OpenStudio CLI:\n{}'.format(
            '\n'.join(errors)))

    # process the additional strings
    if add_str_ != [] and add_str_[0] is not None and idf is not None:
        a_str = '/n'.join(add_str_)
        with open(idf_i, "a") as idf_file:
            idf_file.write(a_str)
    osm[i] = osm_i
    idf[i] = idf_i

    # run the IDF through EnergyPlus
    if run_:
        sql_i, zsz_i, rdd_i, html_i, err_i = run_idf(idf_i,
                                                     _epw_file,
                                                     silent=silent)

        # report any errors on this component
        if err_i is not None:
            err_obj = Err(err_i)
            err_objs[i] = err_obj
            for warn in err_obj.severe_errors:
                give_warning(ghenv.Component, warn)
            for error in err_obj.fatal_errors:
                print err_obj.file_contents  # print before raising the error
                raise Exception(error)

        # append everything to the global lists
        sql[i] = sql_i
        zsz[i] = zsz_i
        rdd[i] = rdd_i
        html[i] = html_i
        err[i] = err_i
Ejemplo n.º 3
0
def _run_translation_osw(osw, out_path):
    """Generic function used by all import methods that run OpenStudio CLI."""
    # run the measure to translate the model JSON to an openstudio measure
    _, idf = run_osw(osw, silent=True)
    if idf is not None and os.path.isfile(idf):
        if out_path is not None:  # load the JSON string to stdout
            with open(out_path) as json_file:
                print(json_file.read())
    else:
        raise Exception('Running OpenStudio CLI failed.')
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
def simulate_osm(osm_file, epw_file, folder, log_file):
    """Simulate an OSM file in EnergyPlus.

    \b
    Args:
        osm_file: Full path to a simulate-able .osm file.
        epw_file: Full path to an .epw file.
    """
    try:
        # set the default folder to the default if it's not specified and copy the IDF
        if folder is None:
            proj_name = os.path.basename(osm_file).replace('.osm', '')
            folder = os.path.join(folders.default_simulation_folder, proj_name)
        preparedir(folder, remove_content=False)
        base_osm = os.path.join(folder, 'in.osm')
        shutil.copy(osm_file, base_osm)

        # create a blank osw for the translation
        osw_dict = {'seed_file': osm_file, 'weather_file': epw_file}
        osw = os.path.join(folder, 'workflow.osw')
        with open(osw, 'w') as fp:
            json.dump(osw_dict, fp, indent=4)

        # run the OSW through OpenStudio CLI
        osm, idf = run_osw(osw)

        # run the file through EnergyPlus
        if idf is not None and os.path.isfile(idf):
            gen_files = [osw, 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])
                err_obj = Err(err)
                for error in err_obj.fatal_errors:
                    log_file.write(
                        err_obj.file_contents)  # log before raising the error
                    raise Exception(error)
            else:
                raise Exception('Running EnergyPlus failed.')
        else:
            raise Exception('Running OpenStudio CLI failed.')
        log_file.write(json.dumps(gen_files))
    except Exception as e:
        _logger.exception('OSM simulation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Ejemplo n.º 6
0
def model_to_gbxml(model_json, osw_folder, check_model, minimal, output_file):
    """Translate a Honeybee Model (HBJSON) to a gbXML file.

    \b
    Args:
        model_json: Full path to a Honeybee Model JSON file (HBJSON).
    """
    try:
        # set the default folder if it's not specified
        out_path = None
        out_directory = os.path.join(
                hb_folders.default_simulation_folder, 'temp_translate')
        if output_file.endswith('-'):
            f_name = os.path.basename(model_json).lower()
            f_name = f_name.replace('.hbjson', '.xml').replace('.json', '.xml')
            out_path = os.path.join(out_directory, f_name)

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

        # Write the osw file and translate the model to gbXML
        out_f = out_path if output_file.endswith('-') else output_file
        osw = to_gbxml_osw(model_json, out_f, osw_folder)
        if minimal:
            _run_translation_osw(osw, out_path)
        else:
            _, idf = run_osw(osw, silent=True)
            if idf is not None and os.path.isfile(idf):
                hb_model = Model.from_hbjson(model_json)
                add_gbxml_space_boundaries(out_f, hb_model)
                if out_path is not None:  # load the JSON string to stdout
                    with open(out_path) as json_file:
                        print(json_file.read())
            else:
                raise Exception('Running OpenStudio CLI failed.')
    except Exception as e:
        _logger.exception('Model translation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
    no_report_meas = True if measures is None else \
        all(meas.type != 'ReportingMeasure' for meas in measures)

    # collect the two jsons for output and write out the osw file
    jsons = [model_json, sim_par_json]
    osw = to_openstudio_osw(directory,
                            model_json,
                            sim_par_json,
                            additional_measures=measures,
                            epw_file=_epw_file,
                            schedule_directory=sch_directory)

    # run the measure to translate the model JSON to an openstudio measure
    silent = True if run_ == 3 else False
    if run_ > 0 and not no_report_meas:  # everything must run with OS CLI
        osm, idf = run_osw(osw, measures_only=False, silent=silent)
        sql, zsz, rdd, html, err = output_energyplus_files(
            os.path.dirname(idf))
    elif run_ > 0:  # no reporting measure; simulate separately from measure application
        osm, idf = run_osw(osw, silent=silent)
        # process the additional strings
        if add_str_ != [] and add_str_[0] is not None and idf is not None:
            add_str = '/n'.join(add_str_)
            with open(idf, "a") as idf_file:
                idf_file.write(add_str)
        if idf is None:  # measures failed to run correctly; parse out.osw
            log_osw = OSW(os.path.join(directory, 'out.osw'))
            for error, tb in zip(log_osw.errors, log_osw.error_tracebacks):
                if 'Cannot create a surface' in error:
                    error = 'Your Rhino Model units system is: {}\n{}'.format(
                        units_system(), error)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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.
    \n
    Args:
        model_json: Full path to a Model JSON file.\n
        epw_file: Full path to an .epw file.
    """
    try:
        # check that the model JSON and the EPW file is there
        assert os.path.isfile(model_json), \
            'No Model JSON file found at {}.'.format(model_json)
        assert os.path.isfile(epw_file), \
            'No EPW file found at {}.'.format(epw_file)
        # 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', '')
            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 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()
            if os.path.isfile(ddy_file):
                sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file)
            else:
                raise ValueError(
                    'No sim-par-json was input and there is no .ddy file next to '
                    'the .epw.\nAt least one of these two cirtieria must be satisfied '
                    'for a successful simulation.')
            sim_par_json = write_sim_par(sim_par)
        else:
            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)
            if len(sim_par.sizing_parameter.design_days
                   ) == 0 and os.path.isfile(ddy_file):
                sim_par.sizing_parameter.add_from_ddy_996_004(ddy_file)
                sim_par_json = write_sim_par(sim_par)
            elif len(sim_par.sizing_parameter.design_days) == 0:
                raise ValueError(
                    'No design days were found in the input sim-par-json and there is '
                    'no .ddy file next to the .epw.\nAt least one of these two cirtieria '
                    'must be satisfied for a successful simulation.')

        # 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)
Ejemplo n.º 10
0
def simulate_model(model_json, epw_file, sim_par_json, obj_per_model,
                   multiplier, no_plenum, no_cap, shade_dist, base_osw, folder,
                   log_file):
    """Simulate a Dragonfly Model JSON file in EnergyPlus.

    \b
    Args:
        model_json: Full path to a Dragonfly 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('.dfjson', '')
            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)

        # re-serialize the Dragonfly Model
        with open(model_json) as json_file:
            data = json.load(json_file)
        model = Model.from_dict(data)
        model.convert_to_units('Meters')

        # convert Dragonfly Model to Honeybee
        add_plenum = not no_plenum
        cap = not no_cap
        hb_models = model.to_honeybee(obj_per_model, shade_dist, multiplier,
                                      add_plenum, cap)

        # write out the honeybee JSONs
        osms = []
        idfs = []
        sqls = []
        for hb_model in hb_models:
            model_dict = hb_model.to_dict(triangulate_sub_faces=True)
            directory = os.path.join(folder, hb_model.identifier)
            file_path = os.path.join(directory,
                                     '{}.json'.format(hb_model.identifier))
            preparedir(directory, remove_content=False)  # create the directory
            with open(file_path, 'w') as fp:
                json.dump(model_dict, fp, indent=4)

            # Write the osw file to translate the model to osm
            osw = to_openstudio_osw(directory,
                                    file_path,
                                    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):
                if base_osw is None:  # separate the OS CLI run from the E+ run
                    osm, idf = run_osw(osw)
                    if idf is not None and os.path.isfile(idf):
                        sql, eio, rdd, html, err = run_idf(idf, epw_file)
                        osms.append(osm)
                        idfs.append(idf)
                        sqls.append(sql)
                        if err is None or not os.path.isfile(err):
                            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 None or not os.path.isfile(idf):
                        raise Exception('Running OpenStudio CLI failed.')
                    sql, eio, rdd, html, err = \
                        output_energyplus_files(os.path.dirname(idf))
                    if err is None or not os.path.isfile(err):
                        raise Exception('Running EnergyPlus failed.')
                    osms.append(osm)
                    idfs.append(idf)
                    sqls.append(sql)
            else:
                raise Exception('Writing OSW file failed.')
        log_file.write(json.dumps({'osm': osms, 'idf': idfs, 'sql': sqls}))
    except Exception as e:
        _logger.exception('Model translation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)
Ejemplo n.º 11
0
    with open(model_json, 'w') as fp:
        json.dump(model_dict, fp)

    # write the simulation parameter JSONs
    sim_par_dict = _sim_par_.to_dict()
    sim_par_json = os.path.join(directory, 'simulation_parameter.json')
    with open(sim_par_json, 'w') as fp:
        json.dump(sim_par_dict, fp)

    # collect the two jsons for output and write out the osw file
    jsons = [model_json, sim_par_json]
    osw = to_openstudio_osw(directory, model_json, sim_par_json, _epw_file)

    # run the measure to translate the model JSON to an openstudio measure
    if run_ > 0:
        osm, idf = run_osw(osw)
        # process the additional strings
        if add_str_ != [] and add_str_[0] is not None and idf is not None:
            add_str = '/n'.join(add_str_)
            with open(idf, "a") as idf_file:
                idf_file.write(add_str)

    # run the resulting idf throught EnergyPlus
    if run_ == 1:
        sql, zsz, rdd, html, err = run_idf(idf, _epw_file)
        if err is not None:
            err_obj = Err(err)
            print(err_obj.file_contents)
            for warn in err_obj.severe_errors:
                give_warning(ghenv.Component, warn)
            for error in err_obj.fatal_errors:
import os


if all_required_inputs(ghenv.Component) and _dump:
    # check the input and set the component defaults
    assert isinstance(_model, Model), \
        'Excpected Honeybee Model object. Got {}.'.format(type(_model))
    name = _name_ if _name_ is not None else _model.identifier
    lower_name = name.lower()
    gbxml_file = name if lower_name.endswith('.xml') or lower_name.endswith('.gbxml') \
        else '{}.xml'.format(name)
    folder = _folder_ if _folder_ is not None else folders.default_simulation_folder
    gbxml = os.path.join(folder, gbxml_file)

    # write out the HBJSON and OpenStudio Workflow (OSW) that translates models to gbXML
    out_directory = os.path.join(folders.default_simulation_folder, 'temp_translate')
    if not os.path.isdir(out_directory):
        os.makedirs(out_directory)
    hb_file = _model.to_hbjson(name, out_directory, included_prop=['energy'])
    osw = to_gbxml_osw(hb_file, gbxml, out_directory)

    # run the measure to translate the model JSON to an openstudio measure
    osm, idf = run_osw(osw, silent=True)
    if idf is None:
        raise Exception('Running OpenStudio CLI failed.')

    # add in the space boundary geometry if the user has requested it
    if full_geo_:
        add_gbxml_space_boundaries(gbxml, _model)
Ejemplo n.º 13
0
def model_to_osm(model_json, sim_par_json, obj_per_model, multiplier,
                 no_plenum, no_cap, shade_dist, folder, log_file):
    """Translate a Model JSON file into an OpenStudio Model.

    \b
    Args:
        model_json: Full path to a Dragonfly Model JSON file.
    """
    try:
        # 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('.dfjson', '')
            folder = os.path.join(hb_folders.default_simulation_folder,
                                  proj_name, 'OpenStudio')
        preparedir(folder, remove_content=False)

        # generate default simulation parameters
        if sim_par_json is None:
            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)

        # re-serialize the Dragonfly Model
        with open(model_json) as json_file:
            data = json.load(json_file)
        model = Model.from_dict(data)
        model.convert_to_units('Meters')

        # convert Dragonfly Model to Honeybee
        add_plenum = not no_plenum
        cap = not no_cap
        hb_models = model.to_honeybee(obj_per_model, shade_dist, multiplier,
                                      add_plenum, cap)

        # write out the honeybee JSONs
        osms = []
        idfs = []
        for hb_model in hb_models:
            model_dict = hb_model.to_dict(triangulate_sub_faces=True)
            directory = os.path.join(folder, hb_model.identifier)
            file_path = os.path.join(directory,
                                     '{}.json'.format(hb_model.identifier))
            preparedir(directory, remove_content=False)  # create the directory
            with open(file_path, 'w') as fp:
                json.dump(model_dict, fp, indent=4)

            # Write the osw file to translate the model to osm
            osw = to_openstudio_osw(directory, file_path, sim_par_json)

            # run the measure to translate the model JSON to an openstudio measure
            if os.path.isfile(osw):
                osm, idf = run_osw(osw)
                if osm is not None and os.path.isfile(osm):
                    osms.append(osm)
                    idfs.append(idf)
                else:
                    raise Exception('Running OpenStudio CLI failed.')
            else:
                raise Exception('Writing OSW file failed.')
        log_file.write(json.dumps({'osm': osms, 'idf': idfs}))
    except Exception as e:
        _logger.exception('Model translation failed.\n{}'.format(e))
        sys.exit(1)
    else:
        sys.exit(0)