示例#1
0
文件: daypym.py 项目: adambgnr/daypym
def view_idf_to_ax(fname=None, idf_txt=None, test=False):
    """This is originally from https://github.com/jamiebull1/geomeppy/blob/master/geomeppy/view_geometry.py
    This just returns an ax instead of viewing it on order to  plot it together with the sensorpoints"""
    from geomeppy.view_geometry import _get_collection, _get_collections, _get_surfaces, _get_limits  # probably these should not be imported here
    from io import StringIO
    from eppy.iddcurrent import iddcurrent
    # type: (Optional[str], Optional[str], Optional[bool]) -> None

    if fname and idf_txt:
        raise ValueError("Pass either fname or idf_txt, not both.")
    # set the IDD for the version of EnergyPlus
    iddfhandle = StringIO(iddcurrent.iddtxt)
    if IDF.getiddname() is None:
        IDF.setiddname(iddfhandle)

    if fname:
        # import the IDF
        idf = IDF(fname)
    elif idf_txt:
        idf = IDF()
        idf.initreadtxt(idf_txt)
    # create the figure and add the surfaces
    ax = plt.axes(projection="3d")
    collections = _get_collections(idf, opacity=0.5)
    for c in collections:
        ax.add_collection3d(c)

    # calculate and set the axis limits
    limits = _get_limits(idf=idf)
    ax.set_xlim(limits["x"])
    ax.set_ylim(limits["y"])
    ax.set_zlim(limits["z"])
    return ax
def test_perim_depth():
    idf_file = IDF(StringIO(""))

    with pytest.raises(ValueError) as excinfo:
        idf_file.add_block(
            name="footprint",
            coordinates=footprint,
            height=3,
            zoning="core/perim",
            num_stories=1,
            perim_depth=10,
        )
    assert str(excinfo.value) == "Perimeter depth is too great"
示例#3
0
    def get_daily_schedule_eppy(self, daily_id):
        """Return a formatted EnergyPlus Schedule:Day:Interval created using Eppy.
    
        Parameters
        ----------
        daily_id : int
    
        Returns
        -------
        str
    
        """
        schedule = self.select(
            'daily_schedules',
            where="ID='{daily_id}'".format(**locals())
        )
        off_vals = {'Cool': '100',
                     'Heat': '-100'}
        name = schedule['NAME'][0]
        s_type = name.split('_')[-2]
        time_cols = [col for col in schedule if
                     col.startswith('h') and
                     col != 'holiday']
        values = list(schedule[time_cols].iloc[0].astype(str))
        values = [v if v != 'None' else off_vals[s_type] for v in values]
        
        fhandle = StringIO("")
        idf = IDF(fhandle)
        sch = idf.newidfobject(
            'SCHEDULE:DAY:INTERVAL',
            Name=name,
            Schedule_Type_Limits_Name=s_type,
            Interpolate_to_Timestep='Yes',
            )
        t = 1
        for i, v in enumerate(values):
            if i == 0:
                continue
            if values[i-1] != v:
                sch['Time_%s' % t] = 'Until: %i:00' % i 
                sch['Value_Until_Time_%s' % t] = values[i-1]
                t += 1
                    
            if i == 23:
                sch['Time_%s' % t] = 'Until: 24:00'
                sch['Value_Until_Time_%s' % t] = v

        schedule_obj = str(sch) # = self.make_schedule_day_list(schedul

        return schedule_obj
示例#4
0
def set_geometry(idf, job, school):
    """Build the geometry for the IDF, or collect it from the cache.
    """
    name = school['name']
    cached_idf = os.path.join(GEOMETRY_CACHE, name) + '.idf'
    try:
        idf = IDF(cached_idf)
    except IOError:        
        blocks = school['blocks']
        shading_blocks = school['shading_blocks']
        
        idf = build_school(idf, name, blocks, shading_blocks)
        idf.saveas(cached_idf)
    return idf
    def final_idf(self, idf, idd):
        #per questa fase ricordarsi di installare pacchetto geomeppy in anaconda gia presente
        geom_IDF.setiddname(idd)
        idf1 = geom_IDF(idf)
        df = pd.read_excel(self.evaluation_output)
        #running the function to find the optimal values among all the simulations
        best_index = self.find_optimum(df)

        Material = idf1.idfobjects['MATERIAL']
        Window_Material = idf1.idfobjects['WINDOWMATERIAL:SIMPLEGLAZINGSYSTEM']
        #MATERIAL:#'WindowMaterial:SimpleGlazingSystem'
        #ROOF: 'SuperInsulating_01445', POSITION: 2
        #WALL: 'SuperInsulating_00795', POSITION: 7
        #window material simple glazing...
        #WINDOW: 'Simple 1001', POSITION: 0

        #print(df.keys())
        print('==================================')
        print('best configuration:')
        print('thick_wall: ', df.loc[best_index, 'Insulation Thickness wall'])
        print('thick_roof: ', df.loc[best_index, 'Insulation Thickness roof'])
        print('U_value: ', df.loc[best_index, 'windows-U-factor'])
        print('WWR: ', df.loc[best_index, 'Window to Wall Ratio'])
        print('==================================')

        Material[2].Thickness = df.loc[best_index, 'Insulation Thickness roof']
        Material[7].Thickness = df.loc[best_index, 'Insulation Thickness wall']
        Window_Material[0].UFactor = df.loc[best_index, 'windows-U-factor']

        #print (Window_Material[0].UFactor)

        #changing the wwr

        new_wwr = df.loc[best_index, 'Window to Wall Ratio']
        old_fen = idf1.idfobjects['FENESTRATIONSURFACE:DETAILED']
        idf1.set_wwr(wwr=new_wwr)
        new_fen = idf1.idfobjects['FENESTRATIONSURFACE:DETAILED']

        #SAVE THE ULTIMATE IDF FILE chose the directory in saveas
        idf1.saveas('/home/ict4db/Scrivania/ICT4BD_git-master/files/idf/' +
                    self.name + '_Optimal.idf')
示例#6
0
def init_idf():
    """Initialise an IDF.
    """
    if IDF.getiddname() == None:
        IDF.setiddname(IDD)
    idf = IDF()
    idf.initnew(None)
    return idf
示例#7
0
def view_idf(fname=None, idf_txt=None, test=False, idf=None):
    # type: (Optional[str], Optional[str], Optional[bool], Optional[IDF]) -> None
    """Display an IDF for inspection.

    :param fname: Path to the IDF.
    :param idf_txt: The string representation of an IDF.
    """
    from geomeppy import IDF

    try:
        plt.figure()
    except TclError:
        # this is as expected on the test server
        return
    if len([arg for arg in [fname, idf_txt, idf] if arg]) > 1:
        raise ValueError("Pass only one of fname, idf_txt or idf.")
    if not idf:
        # set the IDD for the version of EnergyPlus
        iddfhandle = StringIO(iddcurrent.iddtxt)
        if IDF.getiddname() is None:
            IDF.setiddname(iddfhandle)

        if fname:
            # import the IDF
            idf = IDF(fname)
        elif idf_txt:
            idf = IDF()
            idf.initreadtxt(idf_txt)
    # create the figure and add the surfaces
    ax = plt.axes(projection="3d")
    collections = _get_collections(idf, opacity=0.5)
    for c in collections:
        ax.add_collection3d(c)

    # calculate and set the axis limits
    limits = _get_limits(idf=idf)
    ax.set_xlim(limits["x"])
    ax.set_ylim(limits["y"])
    ax.set_zlim(limits["z"])

    if not test:
        plt.show()
differenceList = list()
for i in range(len(groundSurfaceMinimumZCoordinatePerPolygonList)):
  differenceList.append(roofSurfaceMaximumZCoordinatePerPolygonList[i] - groundSurfaceMinimumZCoordinatePerPolygonList[i])

groundSurfaceCoordinatesList = list()
for building in buildingList:
  groundSurfaceCoordinatesList.append(extract_poly_coords(unary_union(building[0]))['exterior_coords'])

finalGroundSurfaceCoordinatesList = list()
for groundSurface in groundSurfaceCoordinatesList:
  finalGroundSurfaceCoordinatesList.append([(x[0], x[1]) for x in (groundSurface)])

!pip install geomeppy

from geomeppy import IDF

IDF.setiddname("Energy+.idd")

idf = IDF("Montreal.idf")

!ls

idf.epw = "USA_CA_San.Francisco.Intl.AP.724940_TMY3.epw"

idf.set_default_constructions()

idf.set_wwr(0.6)

idf.run()
示例#9
0
from geomeppy import IDF
from geomeppy.geom.polygons import Polygon3D

IDF.setiddname('/Applications/EnergyPlus-8-8-0/Energy+.idd')
idf = IDF('/Users/soroush/Desktop/Noumena/bcn-energy/src/gh_template.idf')
# IDF.setiddname ("C:/EnergyPlusV8-8-0/Energy+.idd")
# idf = IDF ("C:/Users/Coroush/Desktop/git_noumena/Comparison/gh_result3/basic_test_gh/EnergyPlus/basic_test2.idf")
idf.epw = '/Users/soroush/Documents/ESP_Barcelona.081810_IWEC.epw'

idf.add_block(name='vivienda0',
              coordinates=[(5, 0), (15, 0), (15, 5), (5, 5)],
              height=3)

idf.add_block(name='vivienda1',
              coordinates=[(5, 5), (15, 5), (15, 10), (5, 10)],
              height=3)

idf.translate([0, 0, 3])

idf.add_block(name='comercio0',
              coordinates=[(0, 0), (10, 0), (10, 5), (0, 5)],
              height=3)

idf.add_block(name='comercio1',
              coordinates=[(0, 5), (10, 5), (10, 10), (0, 10)],
              height=3)

idf.intersect_match()

zones = idf.idfobjects["ZONE"]
target_zone_names = ["vivienda0", "vivienda1", "comercio0", "comercio1"]
示例#10
0
from geomeppy import IDF

IDF.setiddname('/Applications/EnergyPlus-8-8-0/Energy+.idd')
idf = IDF('/Users/soroush/Desktop/Noumena/bcn-energy/src/gh_template.idf')

idf.epw = '/Users/soroush/Desktop/Noumena/bcn-energy/src/ESP_Barcelona.081810_IWEC.epw'

constructions = idf.getobject("CONSTRUCTION", '')
print(constructions)
# idf.printidf()
示例#11
0
    poly1 = Polygon3D(s1.coords)
    poly2 = Polygon3D(s2.coords)
    if almostequal(abs(poly1.distance), abs(poly2.distance), 3):
        if almostequal(poly1.normal_vector,
                       poly2.normal_vector, 3) or almostequal(
                           poly1.normal_vector, -poly2.normal_vector, 3):
            return True


#######################################################################################################################
# DEFINE HERE THE MAIN PATH

path = '/Users/soroush/Desktop/Noumena/eixample-sample1'
# path = r'C:\Users\Coroush\Desktop\Noumena\bcn-energy-github\190531-Files\eixample-sample1'

IDF.setiddname('/Applications/EnergyPlus-8-8-0/Energy+.idd')
idf = IDF('/Applications/EnergyPlus-8-8-0/ExampleFiles/Minimal.idf')
# IDF.setiddname("C:/EnergyPlusV9-1-0/Energy+.idd")
# idf = IDF("C:/EnergyPlusV9-1-0/ExampleFiles/Minimal.idf")

idf.epw = 'USA_CA_San.Francisco.Intl.AP.724940_TMY3.epw'

#######################################################################################################################
# Making H building

# Extracting the elements
paths_H = find_paths('H')
H_root = get_roots(paths_H)[0]
polygon_element = extract_polygon_elements(H_root)

# Dividing the elements into two lists of blocks and surfaces
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Contact: https://www.empa.ch/web/s313
#
from geomeppy import IDF  # install geomeppy in your environment with pip install geomeppy
from pathlib import Path
import os

if __name__ == "__main__":
    # this script converts a IDF file to a 3d geometry you can view e.g. in an online viewer
    # useful to check your building footprints are as you expect and to check how cesar-p creates the building geometry incl adjacencies, neighbours and windows
    IDF.setiddname("C:/EnergyPlusV9-3-0/Energy+.idd"
                   )  # make sure to set IDD matching your IDF
    base = os.path.dirname(__file__) / Path("..") / Path(
        "simple_example") / Path("results") / Path("example") / Path(
            "idfs")  # run the basic example prior to running this script
    idf = IDF(str(base / Path("fid_1.idf")))
    dst = str(base / Path("fid_1.obj"))
    idf.to_obj(fname=dst)
    print(
        f"building 3D object has been saved to {dst}. ZIP the .obj an .mtl file and upload to www.creators3d.com/online-viewer to visualize."
    )
示例#13
0
    differenceList.append(roofSurfaceMaximumZCoordinatePerPolygonList[i] -
                          groundSurfaceMinimumZCoordinatePerPolygonList[i])

groundSurfaceCoordinatesList = list()
for building in buildingList:
    groundSurfaceCoordinatesList.append(
        extract_poly_coords(unary_union(building[0]))['exterior_coords'])

finalGroundSurfaceCoordinatesList = list()
for groundSurface in groundSurfaceCoordinatesList:
    finalGroundSurfaceCoordinatesList.append([(x[0] - 300950, x[1] - 5037400)
                                              for x in (groundSurface)])

from geomeppy import IDF

IDF.setiddname('/Applications/EnergyPlus-9-2-0/Energy+.idd')
idf = IDF('/Applications/EnergyPlus-9-2-0/ExampleFiles/Minimal.idf')
idf.epw = '/Applications/EnergyPlus-9-2-0/WeatherData/USA_CA_San.Francisco.Intl.AP.724940_TMY3.epw'

#for i in range(len(finalGroundSurfaceCoordinatesList)):
for i in range(300, 500):
    idf.add_block(name='Block' + str(i),
                  coordinates=finalGroundSurfaceCoordinatesList[i],
                  height=differenceList[i])

idf.set_wwr(0.6)
idf.view_model()
idf.intersect_match()
idf.translate_to_origin()
idf.set_default_constructions()
示例#14
0
def test_tutorial_2():
    IDF.setiddname("C:/EnergyPlusV9-1-0/Energy+.idd", testing=True)
    idf = IDF("C:/EnergyPlusV9-1-0/ExampleFiles/Minimal.idf")
    idf.epw = "USA_CO_Golden-NREL.724666_TMY3.epw"
    idf.add_block(
        name="Two storey",
        coordinates=[(10, 0), (10, 5), (0, 5), (0, 0)],
        height=6,
        num_stories=2,
    )
    idf.add_block(name="One storey",
                  coordinates=[(10, 5), (10, 10), (0, 10), (0, 5)],
                  height=3)
    idf.intersect_match()
    idf.set_default_constructions()
    # add a heating system
    stat = idf.newidfobject(
        "HVACTEMPLATE:THERMOSTAT",
        Name="Zone Stat",
        Constant_Heating_Setpoint=20,
        Constant_Cooling_Setpoint=25,
    )
    for zone in idf.idfobjects["ZONE"]:
        idf.newidfobject(
            "HVACTEMPLATE:ZONE:IDEALLOADSAIRSYSTEM",
            Zone_Name=zone.Name,
            Template_Thermostat_Name=stat.Name,
        )
    # add some output variables
    idf.newidfobject(
        "OUTPUT:VARIABLE",
        Variable_Name="Zone Ideal Loads Supply Air Total Heating Energy",
        Reporting_Frequency="Hourly",
    )
    idf.newidfobject(
        "OUTPUT:VARIABLE",
        Variable_Name="Zone Ideal Loads Supply Air Total Cooling Energy",
        Reporting_Frequency="Hourly",
    )
    # run a set of simulations, moving glazing from mostly on the South facade, to mostly on the North facade
    north_wwr = [i / 10 for i in range(1, 10)]
    south_wwr = [1 - wwr for wwr in north_wwr]
    for north, south in zip(north_wwr, south_wwr):
        idf.set_wwr(north,
                    construction="Project External Window",
                    orientation="north")
        idf.set_wwr(south,
                    construction="Project External Window",
                    orientation="south")
        idf.run(
            output_prefix=f"{north}_{south}_",
            output_directory="tests/tutorial",
            expandobjects=True,
            verbose="q",
        )
    results = []
    for north, south in zip(north_wwr, south_wwr):
        eso = ESO(f"tests/tutorial/{north}_{south}_out.eso")
        heat = eso.total_kwh(
            "Zone Ideal Loads Supply Air Total Heating Energy")
        cool = eso.total_kwh(
            "Zone Ideal Loads Supply Air Total Cooling Energy")
        results.append([north, south, heat, cool, heat + cool])
    # print out the results
    headers = ["WWR-N", "WWR-S", "Heat", "Cool", "Total"]
    header_format = "{:>10}" * (len(headers))
    print(header_format.format(*headers))
    row_format = "{:>10.1f}" * (len(headers))
    for row in results:
        print(row_format.format(*row))
示例#15
0
def test_tutorial_1():
    IDF.setiddname("C:/EnergyPlusV9-1-0/Energy+.idd", testing=True)
    idf = IDF("C:/EnergyPlusV9-1-0/ExampleFiles/Minimal.idf")
    idf.epw = "USA_CO_Golden-NREL.724666_TMY3.epw"
    idf.add_block(name="Boring hut",
                  coordinates=[(10, 0), (10, 10), (0, 10), (0, 0)],
                  height=3.5)
    idf.intersect_match()
    idf.set_wwr(0.6, construction="Project External Window")
    idf.set_default_constructions()
    idf.to_obj("tests/tutorial/boring_hut.obj")
    idf.run(output_directory="tests/tutorial")
示例#16
0
def test_tutorial_3():
    IDF.setiddname("C:/EnergyPlusV9-1-0/Energy+.idd", testing=True)
    idf = IDF("C:/EnergyPlusV9-1-0/ExampleFiles/Minimal.idf")
    idf.epw = "USA_CO_Golden-NREL.724666_TMY3.epw"
    idf.add_block(
        name="Two storey",
        coordinates=[(10, 0), (10, 5), (0, 5), (0, 0)],
        height=6,
        num_stories=2,
    )
    idf.add_block(name="One storey",
                  coordinates=[(10, 5), (10, 10), (0, 10), (0, 5)],
                  height=3)
    idf.intersect_match()
    idf.set_wwr(0.25, construction="Project External Window")
    idf.set_default_constructions()
    for c in idf.idfobjects["CONSTRUCTION"]:
        print(c)
    print(idf.getobject("MATERIAL", "DefaultMaterial"))
    print(idf.getobject("WINDOWMATERIAL:SIMPLEGLAZINGSYSTEM",
                        "DefaultGlazing"))

    src_idf = IDF("C:/EnergyPlusV9-1-0/ExampleFiles/WindowTestsSimple.idf")
    copy_constructions(source_idf=src_idf, target_idf=idf)
    for c in idf.idfobjects["CONSTRUCTION"]:
        print(c)
    for wall in idf.getsubsurfaces("wall"):
        wall.Construction_Name = "EXTERIOR"
    for roof in idf.getsubsurfaces("roof"):
        roof.Construction_Name = "ROOF31"
    for floor in idf.getsubsurfaces("floor"):
        floor.Construction_Name = "FLOOR38"
    idf.run(output_directory="tests/tutorial")
示例#17
0
from xml.etree.ElementTree import tostring
import pyproj
from geomeppy import IDF
from geomeppy.utilities import almostequal
from geomeppy.geom.polygons import Polygon3D
import platform as _platform

#######################################################################################################################
# DEFINE HERE THE MAIN PATH

os_name = _platform.system()

if os_name == "Darwin":  # if running on Mac use these files
    print("- Running on {}".format("Mac"))
    path = '/Users/soroush/Desktop/Noumena/eixample-sample1'
    IDF.setiddname('/Applications/EnergyPlus-8-8-0/Energy+.idd')
    idf = IDF('/Users/soroush/Desktop/Noumena/bcn-energy/src/gh_template.idf')
    idf.epw = '/Users/soroush/Desktop/Noumena/bcn-energy/src/ESP_Barcelona.081810_IWEC.epw'

elif os_name == "Windows":  # if running on Windows use these files
    print("- Running on {}".format("Windows"))
    path = r"C:\Users\Coroush\Desktop\git-noumena\bcn-energy\src\db-kml"
    IDF.setiddname("C:/EnergyPlusV8-8-0/Energy+.idd")
    idf = IDF(
        "C:/Users/Coroush/Desktop/git-noumena/bcn-energy/src/gh_template.idf")
    idf.epw = 'C:/ladybug/ESP_Barcelona.081810_IWEC/ESP_Barcelona.081810_IWEC.epw'

#######################################################################################################################
# Functions