Example #1
0
def test_makeductbranch():
    """py.test for makeductbranch"""
    tdata = (
        ('d_branch', [
            'BRANCH', 'd_branch', '0', '', 'duct', 'd_branch_duct',
            'd_branch_duct_inlet', 'd_branch_duct_outlet', 'Bypass'
        ], [
            'DUCT', 'd_branch_duct', 'd_branch_duct_inlet',
            'd_branch_duct_outlet'
        ]),  # db_name, branch_obj, duct_obj
    )
    for db_name, branch_obj, duct_obj in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = hvacbuilder.makeductbranch(idf, db_name)
        assert result.obj == branch_obj
        theduct = idf.getobject('DUCT', result.Component_1_Name)
        assert theduct.obj == duct_obj
Example #2
0
def test_makepipebranch():
    """py.test for makepipebranch"""
    tdata = (
        ("p_branch", [
            'BRANCH', 'p_branch', '0', '', 'Pipe:Adiabatic', 'p_branch_pipe',
            'p_branch_pipe_inlet', 'p_branch_pipe_outlet', 'Bypass'
        ], [
            'PIPE:ADIABATIC', 'p_branch_pipe', 'p_branch_pipe_inlet',
            'p_branch_pipe_outlet'
        ]),  # pb_name, branch_obj, pipe_obj
    )
    for pb_name, branch_obj, pipe_obj in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = hvacbuilder.makepipebranch(idf, pb_name)
        assert result.obj == branch_obj
        thepipe = idf.getobject('PIPE:ADIABATIC', result.Component_1_Name)
        assert thepipe.obj == pipe_obj
    def compute(self):
        from eppy.modeleditor import IDF, IDDAlreadySetError
        from StringIO import StringIO

        idf = self.force_get_input('idf', None)
        idd = self.get_input('idd').name

        try:
            IDF.setiddname(idd)
        except IDDAlreadySetError:
            pass

        if idf:
            idf_file = open(idf.name, 'r')
        else:
            idf_file = StringIO('')
        self.idf = IDF(idf_file)
        self.set_output('idf', self.idf)
Example #4
0
def run_single(idf_name_in, epw_name):
    dir_name = os.path.dirname(os.path.realpath(__file__))
    idd_file = "C:/EnergyPlusV9-0-0/Energy+.idd"
    IDF.setiddname(idd_file)

    idf_path = dir_name + '/' + idf_name_in
    epw_path = dir_name + '/' + epw_name

    out = dir_name + '/out_' + idf_name_in.split('.idf')[0]

    idf = IDF(idf_path, epw_path)

    idf.run(
        output_directory = out, 
        readvars = True,
        output_prefix = idf_name_in.split('.idf')[0],
        output_suffix = 'D'
        )
Example #5
0
def test_getallobjlists():
    """py.test for getallobjlists"""
    tdata = (
        (
            'TransformerNames',
            [
                ('ElectricLoadCenter:Distribution'.upper(), 'TransformerNames',
                 [
                     10,
                 ]),
            ],
        ),  # refname, objlists
    )
    for refname, objlists in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = modeleditor.getallobjlists(idf, refname)
        assert result == objlists
Example #6
0
def test_idfstr():
    """Test all outputtype options in IDF.idfstr()."""
    idf = IDF()
    idf.initreadtxt(idfsnippet)
    assert idf.outputtype == "standard"  # start with the default
    original = idf.idfstr()
    assert "!-" in original  # has comment
    assert "\n" in original  # has line break
    assert "\n\n" in original  # has empty line

    idf.outputtype = "standard"
    s = idf.idfstr()
    assert "!-" in s  # has comment
    assert "\n" in s  # has line break
    assert "\n\n" in s  # has empty line
    assert s == original  # is unchanged

    idf.outputtype = "nocomment"
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" in s  # has line break
    assert "\n\n" in s  # has empty line
    assert s != original  # is changed

    idf.outputtype = "nocomment1"
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" in s  # has line break
    assert "\n\n" in s  # has empty lines
    assert s != original  # is changed

    idf.outputtype = "nocomment2"
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" in s  # has line break
    assert "\n\n" not in s  # has no empty lines
    assert s != original  # is changed

    idf.outputtype = "compressed"
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" not in s  # has no line breaks
    assert "\n\n" not in s  # has no empty lines
    assert s != original  # is changed
Example #7
0
def test_getnodefieldname():
    """py.test for getnodefieldname"""
    tdata = (
        ("PIPE:ADIABATIC", "pipe1", "Inlet_Node_Name", "", "Inlet_Node_Name"),
        # objtype, objname, endswith, fluid, nodefieldname
        (
            "CHILLER:ELECTRIC",
            "pipe1",
            "Inlet_Node_Name",
            "",
            "Chilled_Water_Inlet_Node_Name",
        ),
        # objtype, objname, endswith, fluid, nodefieldname
        (
            "COIL:COOLING:WATER",
            "pipe1",
            "Inlet_Node_Name",
            "Water",
            "Water_Inlet_Node_Name",
        ),
        # objtype, objname, endswith, fluid, nodefieldname
        (
            "COIL:COOLING:WATER",
            "pipe1",
            "Inlet_Node_Name",
            "Air",
            "Air_Inlet_Node_Name",
        ),
        # objtype, objname, endswith, fluid, nodefieldname
        (
            "COIL:COOLING:WATER",
            "pipe1",
            "Outlet_Node_Name",
            "Air",
            "Air_Outlet_Node_Name",
        ),
        # objtype, objname, endswith, fluid, nodefieldname
    )
    for objtype, objname, endswith, fluid, nodefieldname in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        idfobject = idf.newidfobject(objtype, Name=objname)
        result = hvacbuilder.getnodefieldname(idfobject, endswith, fluid)
        assert result == nodefieldname
def collect_surface_geometries(idf_path: str) -> pd.DataFrame:

    idd_path = get_idd_path()
    IDF.setiddname(idd_path)
    idf = IDF(str(idf_path))

    detailed_surfaces = idf.idfobjects[DETAILED_BUILDING_SURFACE_IDF_TAG]

    srf_names = [x.Name.upper() for x in detailed_surfaces]
    srf_azis = [x.azimuth for x in detailed_surfaces]
    srf_tilts = [x.tilt for x in detailed_surfaces]
    srf_areas = [x.area for x in detailed_surfaces]
    srf_sun_expos = [x.Sun_Exposure for x in detailed_surfaces]

    surface_data = {COL_SURFACE_NAME: srf_names, COL_AZIMUTH: srf_azis, COL_TILT: srf_tilts, COL_SUN_EXPLOSURE: srf_sun_expos, COL_AREA: srf_areas}

    surface_df = pd.DataFrame(surface_data)

    return surface_df
Example #9
0
    def __init__(
            self,
            idf_file: str,
            weather_file: str,
            variables_file: str,
            env_name: str):
        """EnergyPlus simulator connector.

        Args:
            idf_file (str): IDF file with the building model.
            weather_file (str): EPW file with weather data.
            variables_file (str): Configuration file with the variables used in the simulation.
            env_name (str): Name of the environment.

        Raises:
            KeyError: the environment variable BCVTB_PATH has not been defined.
            KeyError: the environment variable EPLUS_PATH has not been defined.
        """

        # Access BCVTB and EnergyPlus locations
        try:
            self.bcvtb_path = os.environ['BCVTB_PATH']
        except BaseException:
            raise KeyError('BCVTB_PATH environment variable not set.')
        try:
            self.eplus_path = os.environ['EPLUS_PATH']
        except BaseException:
            raise KeyError('EPLUS_PATH environment variable not set.')

        # Read IDF and weather files
        IDF.setiddname(os.path.join(self.eplus_path, 'Energy+.idd'))
        self.idf = IDF(idf_file)
        self.idf_file = idf_file
        self.weather_file = weather_file
        # Max number of timesteps
        self.max_timesteps = self._get_run_period()
        self.run_number = 0
        # Create output folder
        self.env_name = env_name
        self.output_folder = env_name + '_' + datetime.now().strftime('%Y%m%d%H%M')
        os.makedirs(self.output_folder, exist_ok=True)
        # Create socket for communication with EnergyPlus
        self._socket, self._host, self._port = self._create_socket()
Example #10
0
def test_newidfobject():
    """py.test for newidfobject"""
    # make a blank idf
    # make a function for this and then continue.
    idf = IDF()
    idf.new()
    objtype = "material:airgap".upper()
    obj = idf.newidfobject(objtype, Name="Argon")
    obj = idf.newidfobject(objtype, Name="Krypton")
    obj = idf.newidfobject(objtype, Name="Xenon")
    assert idf.model.dt[objtype] == [
        ["MATERIAL:AIRGAP", "Argon"],
        ["MATERIAL:AIRGAP", "Krypton"],
        ["MATERIAL:AIRGAP", "Xenon"],
    ]
    # remove an object
    idf.popidfobject(objtype, 1)
    assert idf.model.dt[objtype] == [
        ["MATERIAL:AIRGAP", "Argon"],
        ["MATERIAL:AIRGAP", "Xenon"],
    ]
    lastobject = idf.idfobjects[objtype][-1]
    idf.removeidfobject(lastobject)
    assert idf.model.dt[objtype] == [["MATERIAL:AIRGAP", "Argon"]]
    # copyidfobject
    onlyobject = idf.idfobjects[objtype][0]
    idf.copyidfobject(onlyobject)

    assert idf.model.dt[objtype] == [
        ["MATERIAL:AIRGAP", "Argon"],
        ["MATERIAL:AIRGAP", "Argon"],
    ]
    # test some functions
    objtype = "FENESTRATIONSURFACE:DETAILED"
    obj = idf.newidfobject(objtype, Name="A Wall")
    assert obj.coords == []
    assert obj.fieldvalues[1] == "A Wall"

    # test defaultvalues=True and defaultvalues=False
    sim_deftrue = idf.newidfobject("SimulationControl".upper(), defaultvalues=True)
    assert sim_deftrue.Do_Zone_Sizing_Calculation == "No"
    sim_deffalse = idf.newidfobject("SimulationControl".upper(), defaultvalues=False)
    assert sim_deffalse.Do_Zone_Sizing_Calculation == ""
Example #11
0
def test_initinletoutlet():
    """py.test for initinletoutlet"""
    tdata = (
        (
            "PIPE:ADIABATIC",
            "apipe",
            None,
            True,
            ["apipe_Inlet_Node_Name"],
            ["apipe_Outlet_Node_Name"],
        ),
        # idfobjectkey, idfobjname, thisnode, force, inlets, outlets
        ("PIPE:ADIABATIC", "apipe", None, False, ["Gumby"],
         ["apipe_Outlet_Node_Name"]),
        # idfobjectkey, idfobjname, thisnode, force, inlets, outlets
        (
            "Coil:Cooling:Water",
            "acoil",
            "Water_",
            True,
            ["acoil_Water_Inlet_Node_Name", ""],
            ["acoil_Water_Outlet_Node_Name", ""],
        ),
        # idfobjectkey, idfobjname, thisnode, force, inlets, outlets
    )
    fhandle = StringIO("")
    idf = IDF(fhandle)
    for idfobjectkey, idfobjname, thisnode, force, inlets, outlets in tdata:
        idfobject = idf.newidfobject(idfobjectkey, Name=idfobjname)
        inodefields = hvacbuilder.getfieldnamesendswith(
            idfobject, "Inlet_Node_Name")
        idfobject[inodefields[0]] = "Gumby"
        hvacbuilder.initinletoutlet(idf, idfobject, thisnode, force=force)
        inodefields = hvacbuilder.getfieldnamesendswith(
            idfobject, "Inlet_Node_Name")
        for nodefield, inlet in zip(inodefields, inlets):
            result = idfobject[nodefield]
            assert result == inlet
        onodefields = hvacbuilder.getfieldnamesendswith(
            idfobject, "Outlet_Node_Name")
        for nodefield, outlet in zip(onodefields, outlets):
            result = idfobject[nodefield]
            assert result == outlet
    def compute(self):
        import requests
        from eppy.modeleditor import IDF, IDDAlreadySetError
        from StringIO import StringIO

        url = self.get_input('url')
        snapshot = self.get_input('snapshot')
        r = requests.post(url, etree.tostring(snapshot))
        if r.ok:
            idf_file = StringIO(r.text.strip().replace('\r\n', '\n'))
            idd = force_get_path(self, 'idd', find_idd())
            try:
                IDF.setiddname(idd)
            except IDDAlreadySetError:
                pass
            self.idf = IDF(idf_file)
            self.set_output('idf', self.idf)
        else:
            raise Exception('Could not request IDF from BIM')
Example #13
0
def main():
    """the main routine"""
    from io import StringIO
    import eppy.iddv7 as iddv7
    IDF.setiddname(StringIO(iddv7.iddtxt))
    idf1 = IDF(StringIO(''))
    loopname = "p_loop"
    sloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4']
    dloop = ['db0', ['db1', 'db2', 'db3'], 'db4']
    # makeplantloop(idf1, loopname, sloop, dloop)
    loopname = "c_loop"
    sloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4']
    dloop = ['db0', ['db1', 'db2', 'db3'], 'db4']
    # makecondenserloop(idf1, loopname, sloop, dloop)
    loopname = "a_loop"
    sloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4']
    dloop = ['zone1', 'zone2', 'zone3']
    makeairloop(idf1, loopname, sloop, dloop)
    idf1.savecopy("hh1.idf")
Example #14
0
def run_single(idf_name, epw_name, n=None):
    print('Simulation ' + str(n) + ' starts.')
    dir_name = os.path.dirname(os.path.realpath(__file__))
    idd_file = "C:/EnergyPlusV9-0-0/Energy+.idd"
    IDF.setiddname(idd_file)

    idf_path = dir_name + '/' + idf_name
    epw_path = dir_name + '/' + epw_name

    out = dir_name + '/out_' + idf_name.split('.idf')[0]

    idf = IDF(idf_path, epw_path)

    idf.run(output_directory=out,
            readvars=True,
            output_prefix=idf_name.split('.idf')[0],
            output_suffix='D')

    print('Simulation ' + str(n) + ' ends.')
Example #15
0
   def test_multiprocess_run_IDF(self):
       """
       Test that we can run a sequence of runs using the signature:
           runIDFs([[IDF, kwargs],...], num_CPUs)
       Fails if expected output files are not in the expected output
       directories.
 
       """
       iddfile = os.path.join(IDD_FILES, TEST_IDD)
       fname1 = os.path.join(IDF_FILES, TEST_IDF)
       IDF.setiddname(open(iddfile, 'r'), testing=True)
       runs = []
       for i in range(4):
           runs.append([IDF(open(fname1, 'r'), TEST_EPW),
                        {'output_directory': 'results_%i' % i}])
       num_CPUs = 2
       runIDFs(runs, num_CPUs)
 
       num_CPUs = -1
       runIDFs(runs, num_CPUs)
Example #16
0
def modify_idf(design, designs, idf_path):
    # Load idf file
    idf1 = IDF('./Models/ss1_idfs/ss1_{:02d}.idf'.format(design))

    # Setup fields to be changed
    building = 'Building'
    building = idf1.idfobjects[building.upper()][0]

    # Set object information
    building.Name = 'Building Design {:02d}/{:02d}'.format(design, designs)
    building.North_Axis = '0'

    print('IDF file setup for {} completed'.format(building.Name))

    idf_path = './Models/ss1_idfs'

    idf1.saveas('{}/ss1_{:02d}.idf'.format(idf_path, design))
    idf_file = '{}/ss1_{:02d}.idf'.format(idf_path, design)

    return idf_file
Example #17
0
def test_scientificnotation():
    """py.test to check if __repr__ for epbunch is printing scientific notation"""
    idftxt = """ScheduleTypeLimits,
    AnyValue,                !- Name
    -1e+019,                 !- Lower Limit Value
    1e+019,                  !- Upper Limit Value
    Continuous;              !- Numeric Type
"""
    expected = """
ScheduleTypeLimits,
    AnyValue,                 !- Name
    -1.000000e+19,            !- Lower Limit Value
    1.000000e+19,             !- Upper Limit Value
    Continuous;               !- Numeric Type
"""
    idffile = StringIO(idftxt)
    idf = IDF(idffile)
    sch = idf.idfobjects["ScheduleTypeLimits"][0]
    result = sch.__repr__()
    assert result == expected
Example #18
0
def main():
    """the main routine"""
    from io import StringIO
    import eppy.iddv7 as iddv7

    IDF.setiddname(StringIO(iddv7.iddtxt))
    idf1 = IDF(StringIO(""))
    loopname = "p_loop"
    sloop = ["sb0", ["sb1", "sb2", "sb3"], "sb4"]
    dloop = ["db0", ["db1", "db2", "db3"], "db4"]
    # makeplantloop(idf1, loopname, sloop, dloop)
    loopname = "c_loop"
    sloop = ["sb0", ["sb1", "sb2", "sb3"], "sb4"]
    dloop = ["db0", ["db1", "db2", "db3"], "db4"]
    # makecondenserloop(idf1, loopname, sloop, dloop)
    loopname = "a_loop"
    sloop = ["sb0", ["sb1", "sb2", "sb3"], "sb4"]
    dloop = ["zone1", "zone2", "zone3"]
    makeairloop(idf1, loopname, sloop, dloop)
    idf1.savecopy("hh1.idf")
Example #19
0
def test_initreadtxt():
    """Test for IDF.initreadtxt()."""
    idftxt = """
        Material,
          G01a 19mm gypsum board,  !- Name
          MediumSmooth,            !- Roughness
          0.019,                   !- Thickness {m}
          0.16,                    !- Conductivity {W/m-K}
          800,                     !- Density {kg/m3}
          1090;                    !- Specific Heat {J/kg-K}

        Construction,
          Interior Wall,           !- Name
          G01a 19mm gypsum board,  !- Outside Layer
          F04 Wall air space resistance,  !- Layer 2
          G01a 19mm gypsum board;  !- Layer 3
        """
    idf = IDF()
    idf.initreadtxt(idftxt)
    assert idf.getobject("MATERIAL", "G01a 19mm gypsum board")
Example #20
0
def main():
    """ 	main()

		This method will not be documented as it is not meant to be run. This method is used
		for debugging and testing only, and thus it may change from commit to commit without
		any mention.
	"""
    IDF.setiddname("EP.idd")
    idf = IDF("input.idf", "t.epw")
    myWindow = idf.idfobjects['FENESTRATIONSURFACE:DETAILED']
    for window in myWindow:
        print(window)
    exit()

    print(get_idfobject_from_name(idf, "Perimeter_ZN_3_wall_north_Window_6"))

    energies_used = []
    min_height = 0.91
    denom = 100

    for i in range(200, -1, -1):
        idf.idfobjects['FENESTRATIONSURFACE:DETAILED'][
            0].Vertex_1_Zcoordinate = round(min_height + (i / denom), 2)
        idf.idfobjects['FENESTRATIONSURFACE:DETAILED'][
            0].Vertex_4_Zcoordinate = round(min_height + (i / denom), 2)

        print("Running with window height {}".format(
            round(min_height + (i / denom), 2)))
        energies_used.append((round(min_height + (i / denom),
                                    2), get_energy_usage(idf)))

    energies_used = sorted(energies_used, key=lambda x: x[1])

    for index, use in enumerate(energies_used):
        print("{}th  best solution has window height {}".format(
            index + 1, use[0]),
              end='\n\t')
        print(use[1])

    print("Best window size is: ", end='\n\t')
    print(min(energies_used, key=lambda x: x[1]))
Example #21
0
def test_rename():
    """py.test for rename"""
    idftxt = """Material,
      G01a 19mm gypsum board,  !- Name
      MediumSmooth,            !- Roughness
      0.019,                   !- Thickness {m}
      0.16,                    !- Conductivity {W/m-K}
      800,                     !- Density {kg/m3}
      1090;                    !- Specific Heat {J/kg-K}

      Construction,
        Interior Wall,           !- Name
        G01a 19mm gypsum board,  !- Outside Layer
        F04 Wall air space resistance,  !- Layer 2
        G01a 19mm gypsum board;  !- Layer 3

    """
    ridftxt = """Material,
      peanut butter,  !- Name
      MediumSmooth,            !- Roughness
      0.019,                   !- Thickness {m}
      0.16,                    !- Conductivity {W/m-K}
      800,                     !- Density {kg/m3}
      1090;                    !- Specific Heat {J/kg-K}

      Construction,
        Interior Wall,           !- Name
        peanut butter,  !- Outside Layer
        F04 Wall air space resistance,  !- Layer 2
        peanut butter;  !- Layer 3

    """
    fhandle = StringIO(idftxt)
    idf = IDF(fhandle)
    result = modeleditor.rename(
        idf,
        'Material'.upper(),
        'G01a 19mm gypsum board', 'peanut butter')
    assert result.Name == 'peanut butter'
    assert idf.idfobjects['CONSTRUCTION'][0].Outside_Layer == 'peanut butter'
    assert idf.idfobjects['CONSTRUCTION'][0].Layer_3 == 'peanut butter'
Example #22
0
    def test_save_with_lineendings_and_encodings(self):
        """
        Test the IDF.save() function with combinations of encodings and line
        endings.

        """
        idf = IDF(self.startfile)
        lineendings = ("windows", "unix", "default")
        encodings = ("ascii", "latin-1", "UTF-8")

        for le, enc in product(lineendings, encodings):
            idf.save(lineendings=le, encoding=enc)

            with open(self.startfile, "rb") as sf:
                result = sf.read()
            if le == "windows":
                assert b"\r\n" in result
            elif le == "unix":
                assert b"\r\n" not in result
            elif le == "default":
                assert os.linesep.encode(enc) in result
Example #23
0
def test_true_azimuth_exception():
    """py.test for true_azimuth exception"""
    coord_system, bldg_north, zone_rel_north = (
        "Global",
        0,
        0,
    )

    fhandle = StringIO(idftxt)
    idf = IDF(fhandle)
    geom_rules = idf.idfobjects["GlobalGeometryRules"][0]
    building = idf.idfobjects["Building"][0]
    zone = idf.idfobjects["Zone"][0]
    surface = idf.idfobjects["BuildingSurface:Detailed"][0]

    geom_rules.Coordinate_System = coord_system
    building.North_Axis = bldg_north
    zone.Direction_of_Relative_North = zone_rel_north

    with pytest.raises(ValueError):
        result = fh.true_azimuth(surface)
Example #24
0
def test_getfieldnamesendswith():
    """py.test for getfieldnamesendswith"""
    idftxt = """PIPE:ADIABATIC,
        np2,                      !- Name
        np1_np2_node,             !- Inlet Node Name
        np2_outlet;               !- Outlet Node Name

    """
    tdata = (
        ("Inlet_Node_Name", ["Inlet_Node_Name"]),  # endswith, fieldnames
        ("Node_Name", ["Inlet_Node_Name",
                       "Outlet_Node_Name"]),  # endswith, fieldnames
        ("Name", ["Name", "Inlet_Node_Name",
                  "Outlet_Node_Name"]),  # endswith, fieldnames
    )
    fhandle = StringIO(idftxt)
    idf = IDF(fhandle)
    idfobject = idf.idfobjects["PIPE:ADIABATIC"][0]
    for endswith, fieldnames in tdata:
        result = hvacbuilder.getfieldnamesendswith(idfobject, endswith)
        assert result == fieldnames
Example #25
0
    def test_save_with_lineendings_and_encodings(self):
        """
        Test the IDF.save() function with combinations of encodings and line 
        endings.
    
        """
        idf = IDF(self.startfile)
        lineendings = ('windows', 'unix', 'default')
        encodings = ('ascii', 'latin-1', 'UTF-8')

        for le, enc in product(lineendings, encodings):
            idf.save(lineendings=le, encoding=enc)

            with open(self.startfile, 'rb') as sf:
                result = sf.read()
            if le == 'windows':
                assert b'\r\n' in result
            elif le == 'unix':
                assert b'\r\n' not in result
            elif le == 'default':
                assert os.linesep.encode(enc) in result
Example #26
0
def test_getrefnames():
    """py.test for getrefnames"""
    tdata = (
        (
            'ZONE',
            [
                'ZoneNames', 'OutFaceEnvNames', 'ZoneAndZoneListNames',
                'AirflowNetworkNodeAndZoneNames'
            ]
        ), # objkey, therefs
        (
            'FluidProperties:Name'.upper(),
            ['FluidNames', 'FluidAndGlycolNames']
        ), # objkey, therefs
        ('Building'.upper(), []), # objkey, therefs
    )
    for objkey, therefs in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = modeleditor.getrefnames(idf, objkey)
        assert result == therefs
Example #27
0
def test_savecopy():
    """Test the IDF.savecopy() function."""
    file_text = "Material,TestMaterial,  !- Name"
    idf = IDF(StringIO(file_text))
    idf.idfname = "test.idf"

    try:
        idf.savecopy()  # this should raise an error as no filename is passed
        assert False
    except TypeError:
        pass

    file_handle = StringIO()
    idf.savecopy(file_handle)  # save a copy with a different filename
    expected = "TestMaterial"
    file_handle.seek(0)
    result = file_handle.read()
    assert expected in result

    # test the idfname attribute has not been changed
    assert idf.idfname == "test.idf"
Example #28
0
def test_newidfobject_warning():
    """Test that the warning for newidfobject created with `aname` is working.

    Fails if the warning is not issued when `aname` is used, or if the warning
    is issued when `aname` is not used.
    """
    # make a blank idf
    # make a function for this and then continue.
    idf = IDF()
    idf.new()
    objtype = "material:airgap".upper()
    # expect warnings here
    with pytest.warns(UserWarning):
        idf.newidfobject(objtype, aname="Krypton")
    with pytest.warns(UserWarning):
        idf.newidfobject(objtype, "Krypton")

    # expect no warnings here - we pass None so as not to trigger the `Failed: DID NOT WARN` message from pytest
    with pytest.warns(None) as captured_warnings:
        idf.newidfobject(objtype, Name="Krypton")
    assert len(captured_warnings) == 0
Example #29
0
    def write_bldg_model(self, bldg_model: BuildingModel) -> None:
        """
        :param bldg_model: Building model to write to IDF
        :type bldg_model: BuildingModel
        """
        idf = IDF(str(self.idf_file_path))
        self.add_basic_simulation_settings(idf, bldg_model.site.site_ground_temperatures)
        constr_handler = ConstructionIDFWritingHandler(bldg_model.bldg_construction, bldg_model.neighbours_construction_props, self.unit_registry)
        self.add_building_geometry(idf, bldg_model.bldg_shape, constr_handler)

        self.add_neighbours(idf, bldg_model.neighbours, constr_handler)
        self.add_building_properties(
            idf,
            bldg_model.bldg_operation_mapping,
            bldg_model.bldg_construction.installation_characteristics,
            bldg_model.bldg_construction.infiltration_rate,
            self.__handle_profile_file(bldg_model.bldg_construction.infiltration_profile),
            bldg_model.bldg_construction.window_constr.shade,
        )
        idf = self.add_output_settings(idf)
        idf.save(filename=str(self.idf_file_path))
Example #30
0
    def __init__(self,
                 idf_file_name: str = None,
                 basement_type: str = None,
                 prototype: str = None,
                 climate_zone: str = None,
                 weather_file: str = None,
                 heating_type: str = None,
                 foundation_type: str = None,
                 agent: Agent = None
                 ):
        if not Model.model_import_flag:
            raise ImportError("You have to set the energyplus folder first")
        self.api = None
        self.idf = None
        self.run_parameters = None
#         self.queue = EventQueue()
        self.agent = agent
        self.current_state = None
        self.state_history = []
        self.zone_names = None
        self.thermal_names = None
        self.counter = 0
        self.historical_values = list()
        self.warmup_complete = False

        # TODO: Validate input parameters

        if idf_file_name is None:
            idf_file_name = f"./buildings/{prototype}_{climate_zone}_{heating_type}_{foundation_type}.idf"
            if weather_file is None:
                weather_file = f"./weathers/{climate_zone}.epw"

        self.run_parameters = ["-d", "result", "input.idf"]
        if weather_file:
            self.run_parameters = ["-w", weather_file] + self.run_parameters

        try:
            self.idf = IDF(idf_file_name)
        except:
            raise ValueError("IDF file is damaged or not match with your EnergyPlus version.")