text
stringlengths
81
112k
get the ranges for this field def getrange(bch, fieldname): """get the ranges for this field""" keys = ['maximum', 'minimum', 'maximum<', 'minimum>', 'type'] index = bch.objls.index(fieldname) fielddct_orig = bch.objidd[index] fielddct = copy.deepcopy(fielddct_orig) therange = {} for key in keys: therange[key] = fielddct.setdefault(key, None) if therange['type']: therange['type'] = therange['type'][0] if therange['type'] == 'real': for key in keys[:-1]: if therange[key]: therange[key] = float(therange[key][0]) if therange['type'] == 'integer': for key in keys[:-1]: if therange[key]: therange[key] = int(therange[key][0]) return therange
throw exception if the out of range def checkrange(bch, fieldname): """throw exception if the out of range""" fieldvalue = bch[fieldname] therange = bch.getrange(fieldname) if therange['maximum'] != None: if fieldvalue > therange['maximum']: astr = "Value %s is not less or equal to the 'maximum' of %s" astr = astr % (fieldvalue, therange['maximum']) raise RangeError(astr) if therange['minimum'] != None: if fieldvalue < therange['minimum']: astr = "Value %s is not greater or equal to the 'minimum' of %s" astr = astr % (fieldvalue, therange['minimum']) raise RangeError(astr) if therange['maximum<'] != None: if fieldvalue >= therange['maximum<']: astr = "Value %s is not less than the 'maximum<' of %s" astr = astr % (fieldvalue, therange['maximum<']) raise RangeError(astr) if therange['minimum>'] != None: if fieldvalue <= therange['minimum>']: astr = "Value %s is not greater than the 'minimum>' of %s" astr = astr % (fieldvalue, therange['minimum>']) raise RangeError(astr) return fieldvalue """get the idd dict for this field Will return {} if the fieldname does not exist"""
get the idd dict for this field Will return {} if the fieldname does not exist def getfieldidd(bch, fieldname): """get the idd dict for this field Will return {} if the fieldname does not exist""" # print(bch) try: fieldindex = bch.objls.index(fieldname) except ValueError as e: return {} # the fieldname does not exist # so there is no idd fieldidd = bch.objidd[fieldindex] return fieldidd
return an item from the fieldidd, given the iddkey will return and empty list if it does not have the iddkey or if the fieldname does not exist def getfieldidd_item(bch, fieldname, iddkey): """return an item from the fieldidd, given the iddkey will return and empty list if it does not have the iddkey or if the fieldname does not exist""" fieldidd = getfieldidd(bch, fieldname) try: return fieldidd[iddkey] except KeyError as e: return []
return True if the field is equal to value def isequal(bch, fieldname, value, places=7): """return True if the field is equal to value""" def equalalphanumeric(bch, fieldname, value): if bch.get_retaincase(fieldname): return bch[fieldname] == value else: return bch[fieldname].upper() == value.upper() fieldidd = bch.getfieldidd(fieldname) try: ftype = fieldidd['type'][0] if ftype in ['real', 'integer']: return almostequal(bch[fieldname], float(value), places=places) else: return equalalphanumeric(bch, fieldname, value) except KeyError as e: return equalalphanumeric(bch, fieldname, value)
Get a list of objects that refer to this object def getreferingobjs(referedobj, iddgroups=None, fields=None): """Get a list of objects that refer to this object""" # pseudocode for code below # referringobjs = [] # referedobj has: -> Name # -> reference # for each obj in idf: # [optional filter -> objects in iddgroup] # each field of obj: # [optional filter -> field in fields] # has object-list [refname]: # if refname in reference: # if Name = field value: # referringobjs.append() referringobjs = [] idf = referedobj.theidf referedidd = referedobj.getfieldidd("Name") try: references = referedidd['reference'] except KeyError as e: return referringobjs idfobjs = idf.idfobjects.values() idfobjs = list(itertools.chain.from_iterable(idfobjs)) # flatten list if iddgroups: # optional filter idfobjs = [anobj for anobj in idfobjs if anobj.getfieldidd('key')['group'] in iddgroups] for anobj in idfobjs: if not fields: thefields = anobj.objls else: thefields = fields for field in thefields: try: itsidd = anobj.getfieldidd(field) except ValueError as e: continue if 'object-list' in itsidd: refname = itsidd['object-list'][0] if refname in references: if referedobj.isequal('Name', anobj[field]): referringobjs.append(anobj) return referringobjs
Get an object referred to by a field in another object. For example an object of type Construction has fields for each layer, each of which refers to a Material. This functions allows the object representing a Material to be fetched using the name of the layer. Returns the first item found since if there is more than one matching item, it is a malformed IDF. Parameters ---------- referring_object : EpBunch The object which contains a reference to another object, fieldname : str The name of the field in the referring object which contains the reference to another object. Returns ------- EpBunch def get_referenced_object(referring_object, fieldname): """ Get an object referred to by a field in another object. For example an object of type Construction has fields for each layer, each of which refers to a Material. This functions allows the object representing a Material to be fetched using the name of the layer. Returns the first item found since if there is more than one matching item, it is a malformed IDF. Parameters ---------- referring_object : EpBunch The object which contains a reference to another object, fieldname : str The name of the field in the referring object which contains the reference to another object. Returns ------- EpBunch """ idf = referring_object.theidf object_list = referring_object.getfieldidd_item(fieldname, u'object-list') for obj_type in idf.idfobjects: for obj in idf.idfobjects[obj_type]: valid_object_lists = obj.getfieldidd_item("Name", u'reference') if set(object_list).intersection(set(valid_object_lists)): referenced_obj_name = referring_object[fieldname] if obj.Name == referenced_obj_name: return obj
return True if the field == value Will retain case if get_retaincase == True for real value will compare to decimal 'places' def isequal(self, fieldname, value, places=7): """return True if the field == value Will retain case if get_retaincase == True for real value will compare to decimal 'places' """ return isequal(self, fieldname, value, places=places)
Get a list of objects that refer to this object def getreferingobjs(self, iddgroups=None, fields=None): """Get a list of objects that refer to this object""" return getreferingobjs(self, iddgroups=iddgroups, fields=fields)
volume of a irregular tetrahedron def vol_tehrahedron(poly): """volume of a irregular tetrahedron""" p_a = np.array(poly[0]) p_b = np.array(poly[1]) p_c = np.array(poly[2]) p_d = np.array(poly[3]) return abs(np.dot( np.subtract(p_a, p_d), np.cross( np.subtract(p_b, p_d), np.subtract(p_c, p_d))) / 6)
volume of a zone defined by two polygon bases def vol(poly1, poly2): """"volume of a zone defined by two polygon bases """ c_point = central_p(poly1, poly2) c_point = (c_point[0], c_point[1], c_point[2]) vol_therah = 0 num = len(poly1) poly1.append(poly1[0]) poly2.append(poly2[0]) for i in range(num - 2): # the upper part tehrahedron = [c_point, poly1[0], poly1[i+1], poly1[i+2]] vol_therah += vol_tehrahedron(tehrahedron) # the bottom part tehrahedron = [c_point, poly2[0], poly2[i+1], poly2[i+2]] vol_therah += vol_tehrahedron(tehrahedron) # the middle part for i in range(num): tehrahedron = [c_point, poly1[i], poly2[i], poly2[i+1]] vol_therah += vol_tehrahedron(tehrahedron) tehrahedron = [c_point, poly1[i], poly1[i+1], poly2[i]] vol_therah += vol_tehrahedron(tehrahedron) return vol_therah
make the name2refs dict in the idd_index def makename2refdct(commdct): """make the name2refs dict in the idd_index""" refdct = {} for comm in commdct: # commdct is a list of dict try: idfobj = comm[0]['idfobj'].upper() field1 = comm[1] if 'Name' in field1['field']: references = field1['reference'] refdct[idfobj] = references except (KeyError, IndexError) as e: continue # not the expected pattern for reference return refdct
make the ref2namesdct in the idd_index def makeref2namesdct(name2refdct): """make the ref2namesdct in the idd_index""" ref2namesdct = {} for key, values in name2refdct.items(): for value in values: ref2namesdct.setdefault(value, set()).add(key) return ref2namesdct
embed ref2names into commdct def ref2names2commdct(ref2names, commdct): """embed ref2names into commdct""" for comm in commdct: for cdct in comm: try: refs = cdct['object-list'][0] validobjects = ref2names[refs] cdct.update({'validobjects':validobjects}) except KeyError as e: continue return commdct
Calculation of zone area def area(poly): """Calculation of zone area""" poly_xy = [] num = len(poly) for i in range(num): poly[i] = poly[i][0:2] + (0,) poly_xy.append(poly[i]) return surface.area(poly)
get the pervious component in the loop def prevnode(edges, component): """get the pervious component in the loop""" e = edges c = component n2c = [(a, b) for a, b in e if type(a) == tuple] c2n = [(a, b) for a, b in e if type(b) == tuple] node2cs = [(a, b) for a, b in e if b == c] c2nodes = [] for node2c in node2cs: c2node = [(a, b) for a, b in c2n if b == node2c[0]] if len(c2node) == 0: # return [] c2nodes = [] break c2nodes.append(c2node[0]) cs = [a for a, b in c2nodes] # test for connections that have no nodes # filter for no nodes nonodes = [(a, b) for a, b in e if type(a) != tuple and type(b) != tuple] for a, b in nonodes: if b == component: cs.append(a) return cs
height def height(poly): """height""" num = len(poly) hgt = 0.0 for i in range(num): hgt += (poly[i][2]) return hgt/num
unit normal def unit_normal(apnt, bpnt, cpnt): """unit normal""" xvar = np.tinylinalg.det([ [1, apnt[1], apnt[2]], [1, bpnt[1], bpnt[2]], [1, cpnt[1], cpnt[2]]]) yvar = np.tinylinalg.det([ [apnt[0], 1, apnt[2]], [bpnt[0], 1, bpnt[2]], [cpnt[0], 1, cpnt[2]]]) zvar = np.tinylinalg.det([ [apnt[0], apnt[1], 1], [bpnt[0], bpnt[1], 1], [cpnt[0], cpnt[1], 1]]) magnitude = (xvar**2 + yvar**2 + zvar**2)**.5 if magnitude < 0.00000001: mag = (0, 0, 0) else: mag = (xvar/magnitude, yvar/magnitude, zvar/magnitude) return mag
Insert an idfobject (bunch) to list1 and its object to list2. def insert(self, i, v): """Insert an idfobject (bunch) to list1 and its object to list2.""" self.list1.insert(i, v) self.list2.insert(i, v.obj) if isinstance(v, EpBunch): v.theidf = self.theidf
Collect data into fixed-length chunks or blocks def grouper(num, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx args = [iter(iterable)] * num return zip_longest(fillvalue=fillvalue, *args)
return the coordinates of the surface def getcoords(ddtt): """return the coordinates of the surface""" n_vertices_index = ddtt.objls.index('Number_of_Vertices') first_x = n_vertices_index + 1 # X of first coordinate pts = ddtt.obj[first_x:] return list(grouper(3, pts))
return building name def buildingname(ddtt): """return building name""" idf = ddtt.theidf building = idf.idfobjects['building'.upper()][0] return building.Name
massage the version number so it matches the format of install folder def cleanupversion(ver): """massage the version number so it matches the format of install folder""" lst = ver.split(".") if len(lst) == 1: lst.extend(['0', '0']) elif len(lst) == 2: lst.extend(['0']) elif len(lst) > 2: lst = lst[:3] lst[2] = '0' # ensure the 3rd number is 0 cleanver = '.'.join(lst) return cleanver
find the IDD file of the E+ installation def getiddfile(versionid): """find the IDD file of the E+ installation""" vlist = versionid.split('.') if len(vlist) == 1: vlist = vlist + ['0', '0'] elif len(vlist) == 2: vlist = vlist + ['0'] ver_str = '-'.join(vlist) eplus_exe, _ = eppy.runner.run_functions.install_paths(ver_str) eplusfolder = os.path.dirname(eplus_exe) iddfile = '{}/Energy+.idd'.format(eplusfolder, ) return iddfile
automatically set idd and open idf file. Uses version from idf to set correct idd It will work under the following circumstances: - the IDF file should have the VERSION object. - Needs the version of EnergyPlus installed that matches the IDF version. - Energyplus should be installed in the default location. Parameters ---------- fname : str, StringIO or IOBase Filepath IDF file, File handle of IDF file open to read StringIO with IDF contents within idd : str, StringIO or IOBase This is an optional argument. easyopen will find the IDD without this arg Filepath IDD file, File handle of IDD file open to read StringIO with IDD contents within epw : str path name to the weather file. This arg is needed to run EneryPlus from eppy. def easyopen(fname, idd=None, epw=None): """automatically set idd and open idf file. Uses version from idf to set correct idd It will work under the following circumstances: - the IDF file should have the VERSION object. - Needs the version of EnergyPlus installed that matches the IDF version. - Energyplus should be installed in the default location. Parameters ---------- fname : str, StringIO or IOBase Filepath IDF file, File handle of IDF file open to read StringIO with IDF contents within idd : str, StringIO or IOBase This is an optional argument. easyopen will find the IDD without this arg Filepath IDD file, File handle of IDD file open to read StringIO with IDD contents within epw : str path name to the weather file. This arg is needed to run EneryPlus from eppy. """ if idd: eppy.modeleditor.IDF.setiddname(idd) idf = eppy.modeleditor.IDF(fname, epw=epw) return idf # the rest of the code runs if idd=None if isinstance(fname, (IOBase, StringIO)): fhandle = fname else: fhandle = io.open(fname, 'r', encoding='latin-1') # latin-1 seems to read most things # - get the version number from the idf file txt = fhandle.read() # try: # txt = txt.decode('latin-1') # latin-1 seems to read most things # except AttributeError: # pass ntxt = eppy.EPlusInterfaceFunctions.parse_idd.nocomment(txt, '!') blocks = ntxt.split(';') blocks = [block.strip()for block in blocks] bblocks = [block.split(',') for block in blocks] bblocks1 = [[item.strip() for item in block] for block in bblocks] ver_blocks = [block for block in bblocks1 if block[0].upper() == 'VERSION'] ver_block = ver_blocks[0] versionid = ver_block[1] # - get the E+ folder based on version number iddfile = getiddfile(versionid) if os.path.exists(iddfile): pass # might be an old version of E+ else: iddfile = getoldiddfile(versionid) if os.path.exists(iddfile): # if True: # - set IDD and open IDF. eppy.modeleditor.IDF.setiddname(iddfile) if isinstance(fname, (IOBase, StringIO)): fhandle.seek(0) idf = eppy.modeleditor.IDF(fhandle, epw=epw) else: idf = eppy.modeleditor.IDF(fname, epw=epw) return idf else: # - can't find IDD -> throw an exception astr = "input idf file says E+ version {}. easyopen() cannot find the corresponding idd file '{}'" astr = astr.format(versionid, iddfile) raise MissingIDDException(astr)
the comment is similar to that in python. any charachter after the # is treated as a comment until the end of the line astr is the string to be de-commented cphrase is the comment phrase def removecomment(astr, cphrase): """ the comment is similar to that in python. any charachter after the # is treated as a comment until the end of the line astr is the string to be de-commented cphrase is the comment phrase""" # linesep = mylib3.getlinesep(astr) alist = astr.splitlines() for i in range(len(alist)): alist1 = alist[i].split(cphrase) alist[i] = alist1[0] # return string.join(alist, linesep) return '\n'.join(alist)
initdict2 def initdict2(self, dictfile): """initdict2""" dt = {} dtls = [] adict = dictfile for element in adict: dt[element[0].upper()] = [] # dict keys for objects always in caps dtls.append(element[0].upper()) return dt, dtls
create a blank dictionary def initdict(self, fname): """create a blank dictionary""" if isinstance(fname, Idd): self.dt, self.dtls = fname.dt, fname.dtls return self.dt, self.dtls astr = mylib2.readfile(fname) nocom = removecomment(astr, '!') idfst = nocom alist = idfst.split(';') lss = [] for element in alist: lst = element.split(',') lss.append(lst) for i in range(0, len(lss)): for j in range(0, len(lss[i])): lss[i][j] = lss[i][j].strip() dt = {} dtls = [] for element in lss: if element[0] == '': continue dt[element[0].upper()] = [] dtls.append(element[0].upper()) self.dt, self.dtls = dt, dtls return dt, dtls
stuff file data into the blank dictionary def makedict(self, dictfile, fnamefobject): """stuff file data into the blank dictionary""" #fname = './exapmlefiles/5ZoneDD.idf' #fname = './1ZoneUncontrolled.idf' if isinstance(dictfile, Idd): localidd = copy.deepcopy(dictfile) dt, dtls = localidd.dt, localidd.dtls else: dt, dtls = self.initdict(dictfile) # astr = mylib2.readfile(fname) astr = fnamefobject.read() try: astr = astr.decode('ISO-8859-2') except AttributeError: pass fnamefobject.close() nocom = removecomment(astr, '!') idfst = nocom # alist = string.split(idfst, ';') alist = idfst.split(';') lss = [] for element in alist: # lst = string.split(element, ',') lst = element.split(',') lss.append(lst) for i in range(0, len(lss)): for j in range(0, len(lss[i])): lss[i][j] = lss[i][j].strip() for element in lss: node = element[0].upper() if node in dt: # stuff data in this key dt[node.upper()].append(element) else: # scream if node == '': continue print('this node -%s-is not present in base dictionary' % (node)) self.dt, self.dtls = dt, dtls return dt, dtls
replace the node here with the node from othereplus def replacenode(self, othereplus, node): """replace the node here with the node from othereplus""" node = node.upper() self.dt[node.upper()] = othereplus.dt[node.upper()]
add the node here with the node from othereplus this will potentially have duplicates def add2node(self, othereplus, node): """add the node here with the node from othereplus this will potentially have duplicates""" node = node.upper() self.dt[node.upper()] = self.dt[node.upper()] + \ othereplus.dt[node.upper()]
add an item to the node. example: add a new zone to the element 'ZONE' def addinnode(self, otherplus, node, objectname): """add an item to the node. example: add a new zone to the element 'ZONE' """ # do a test for unique object here newelement = otherplus.dt[node.upper()]
reflist is got from getobjectref in parse_idd.py getobjectref returns a dictionary. reflist is an item in the dictionary getrefs gathers all the fields refered by reflist def getrefs(self, reflist): """ reflist is got from getobjectref in parse_idd.py getobjectref returns a dictionary. reflist is an item in the dictionary getrefs gathers all the fields refered by reflist """ alist = [] for element in reflist: if element[0].upper() in self.dt: for elm in self.dt[element[0].upper()]: alist.append(elm[element[1]]) return alist
draw a graph without the nodes def dropnodes(edges): """draw a graph without the nodes""" newedges = [] added = False for edge in edges: if bothnodes(edge): newtup = (edge[0][0], edge[1][0]) newedges.append(newtup) added = True elif firstisnode(edge): for edge1 in edges: if edge[0] == edge1[1]: newtup = (edge1[0], edge[1]) try: newedges.index(newtup) except ValueError as e: newedges.append(newtup) added = True elif secondisnode(edge): for edge1 in edges: if edge[1] == edge1[0]: newtup = (edge[0], edge1[1]) try: newedges.index(newtup) except ValueError as e: newedges.append(newtup) added = True # gets the hanging nodes - nodes with no connection if not added: if firstisnode(edge): newedges.append((edge[0][0], edge[1])) if secondisnode(edge): newedges.append((edge[0], edge[1][0])) added = False return newedges
gather the nodes from the edges def edges2nodes(edges): """gather the nodes from the edges""" nodes = [] for e1, e2 in edges: nodes.append(e1) nodes.append(e2) nodedict = dict([(n, None) for n in nodes]) justnodes = list(nodedict.keys()) # justnodes.sort() justnodes = sorted(justnodes, key=lambda x: str(x[0])) return justnodes
make the diagram with the edges def makediagram(edges): """make the diagram with the edges""" graph = pydot.Dot(graph_type='digraph') nodes = edges2nodes(edges) epnodes = [(node, makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"] endnodes = [(node, makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"] epbr = [(node, makeabranch(node)) for node in nodes if not istuple(node)] nodedict = dict(epnodes + epbr + endnodes) for value in list(nodedict.values()): graph.add_node(value) for e1, e2 in edges: graph.add_edge(pydot.Edge(nodedict[e1], nodedict[e2])) return graph
return the edges jointing the components of a branch def makebranchcomponents(data, commdct, anode="epnode"): """return the edges jointing the components of a branch""" alledges = [] objkey = 'BRANCH' cnamefield = "Component %s Name" inletfield = "Component %s Inlet Node Name" outletfield = "Component %s Outlet Node Name" numobjects = len(data.dt[objkey]) cnamefields = loops.repeatingfields(data, commdct, objkey, cnamefield) inletfields = loops.repeatingfields(data, commdct, objkey, inletfield) outletfields = loops.repeatingfields(data, commdct, objkey, outletfield) inlts = loops.extractfields(data, commdct, objkey, [inletfields] * numobjects) cmps = loops.extractfields(data, commdct, objkey, [cnamefields] * numobjects) otlts = loops.extractfields(data, commdct, objkey, [outletfields] * numobjects) zipped = list(zip(inlts, cmps, otlts)) tzipped = [transpose2d(item) for item in zipped] for i in range(len(data.dt[objkey])): tt = tzipped[i] # branchname = data.dt[objkey][i][1] edges = [] for t0 in tt: edges = edges + [((t0[0], anode), t0[1]), (t0[1], (t0[2], anode))] alledges = alledges + edges return alledges
make the edges for the airloop and the plantloop def makeairplantloop(data, commdct): """make the edges for the airloop and the plantloop""" anode = "epnode" endnode = "EndNode" # in plantloop get: # demand inlet, outlet, branchlist # supply inlet, outlet, branchlist plantloops = loops.plantloopfields(data, commdct) # splitters # inlet # outlet1 # outlet2 splitters = loops.splitterfields(data, commdct) # # mixer # outlet # inlet1 # inlet2 mixers = loops.mixerfields(data, commdct) # # supply barnchlist # branch1 -> inlet, outlet # branch2 -> inlet, outlet # branch3 -> inlet, outlet # # CONNET INLET OUTLETS edges = [] # get all branches branchkey = "branch".upper() branches = data.dt[branchkey] branch_i_o = {} for br in branches: br_name = br[1] in_out = loops.branch_inlet_outlet(data, commdct, br_name) branch_i_o[br_name] = dict(list(zip(["inlet", "outlet"], in_out))) # for br_name, in_out in branch_i_o.items(): # edges.append(((in_out["inlet"], anode), br_name)) # edges.append((br_name, (in_out["outlet"], anode))) # instead of doing the branch # do the content of the branch edges = makebranchcomponents(data, commdct) # connect splitter to nodes for splitter in splitters: # splitter_inlet = inletbranch.node splittername = splitter[0] inletbranchname = splitter[1] splitter_inlet = branch_i_o[inletbranchname]["outlet"] # edges = splitter_inlet -> splittername edges.append(((splitter_inlet, anode), splittername)) # splitter_outlets = ouletbranches.nodes outletbranchnames = [br for br in splitter[2:]] splitter_outlets = [branch_i_o[br]["inlet"] for br in outletbranchnames] # edges = [splittername -> outlet for outlet in splitter_outlets] moreedges = [(splittername, (outlet, anode)) for outlet in splitter_outlets] edges = edges + moreedges for mixer in mixers: # mixer_outlet = outletbranch.node mixername = mixer[0] outletbranchname = mixer[1] mixer_outlet = branch_i_o[outletbranchname]["inlet"] # edges = mixername -> mixer_outlet edges.append((mixername, (mixer_outlet, anode))) # mixer_inlets = inletbranches.nodes inletbranchnames = [br for br in mixer[2:]] mixer_inlets = [branch_i_o[br]["outlet"] for br in inletbranchnames] # edges = [mixername -> inlet for inlet in mixer_inlets] moreedges = [((inlet, anode), mixername) for inlet in mixer_inlets] edges = edges + moreedges # connect demand and supply side # for plantloop in plantloops: # supplyinlet = plantloop[1] # supplyoutlet = plantloop[2] # demandinlet = plantloop[4] # demandoutlet = plantloop[5] # # edges = [supplyoutlet -> demandinlet, demandoutlet -> supplyinlet] # moreedges = [((supplyoutlet, endnode), (demandinlet, endnode)), # ((demandoutlet, endnode), (supplyinlet, endnode))] # edges = edges + moreedges # # -----------air loop stuff---------------------- # from s_airloop2.py # Get the demand and supply nodes from 'airloophvac' # in airloophvac get: # get branch, supplyinlet, supplyoutlet, demandinlet, demandoutlet objkey = "airloophvac".upper() fieldlists = [["Branch List Name", "Supply Side Inlet Node Name", "Demand Side Outlet Node Name", "Demand Side Inlet Node Names", "Supply Side Outlet Node Names"]] * loops.objectcount(data, objkey) airloophvacs = loops.extractfields(data, commdct, objkey, fieldlists) # airloophvac = airloophvacs[0] # in AirLoopHVAC:ZoneSplitter: # get Name, inlet, all outlets objkey = "AirLoopHVAC:ZoneSplitter".upper() singlefields = ["Name", "Inlet Node Name"] fld = "Outlet %s Node Name" repeatfields = loops.repeatingfields(data, commdct, objkey, fld) fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) zonesplitters = loops.extractfields(data, commdct, objkey, fieldlists) # in AirLoopHVAC:SupplyPlenum: # get Name, Zone Name, Zone Node Name, inlet, all outlets objkey = "AirLoopHVAC:SupplyPlenum".upper() singlefields = ["Name", "Zone Name", "Zone Node Name", "Inlet Node Name"] fld = "Outlet %s Node Name" repeatfields = loops.repeatingfields(data, commdct, objkey, fld) fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) supplyplenums = loops.extractfields(data, commdct, objkey, fieldlists) # in AirLoopHVAC:ZoneMixer: # get Name, outlet, all inlets objkey = "AirLoopHVAC:ZoneMixer".upper() singlefields = ["Name", "Outlet Node Name"] fld = "Inlet %s Node Name" repeatfields = loops.repeatingfields(data, commdct, objkey, fld) fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) zonemixers = loops.extractfields(data, commdct, objkey, fieldlists) # in AirLoopHVAC:ReturnPlenum: # get Name, Zone Name, Zone Node Name, outlet, all inlets objkey = "AirLoopHVAC:ReturnPlenum".upper() singlefields = ["Name", "Zone Name", "Zone Node Name", "Outlet Node Name"] fld = "Inlet %s Node Name" repeatfields = loops.repeatingfields(data, commdct, objkey, fld) fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) returnplenums = loops.extractfields(data, commdct, objkey, fieldlists) # connect room to each equip in equiplist # in ZoneHVAC:EquipmentConnections: # get Name, equiplist, zoneairnode, returnnode objkey = "ZoneHVAC:EquipmentConnections".upper() singlefields = ["Zone Name", "Zone Conditioning Equipment List Name", "Zone Air Node Name", "Zone Return Air Node Name"] repeatfields = [] fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) equipconnections = loops.extractfields(data, commdct, objkey, fieldlists) # in ZoneHVAC:EquipmentList: # get Name, all equiptype, all equipnames objkey = "ZoneHVAC:EquipmentList".upper() singlefields = ["Name", ] fieldlist = singlefields flds = ["Zone Equipment %s Object Type", "Zone Equipment %s Name"] repeatfields = loops.repeatingfields(data, commdct, objkey, flds) fieldlist = fieldlist + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) equiplists = loops.extractfields(data, commdct, objkey, fieldlists) equiplistdct = dict([(ep[0], ep[1:]) for ep in equiplists]) for key, equips in list(equiplistdct.items()): enames = [equips[i] for i in range(1, len(equips), 2)] equiplistdct[key] = enames # adistuunit -> room # adistuunit <- VAVreheat # airinlet -> VAVreheat # in ZoneHVAC:AirDistributionUnit: # get Name, equiplist, zoneairnode, returnnode objkey = "ZoneHVAC:AirDistributionUnit".upper() singlefields = ["Name", "Air Terminal Object Type", "Air Terminal Name"] repeatfields = [] fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) adistuunits = loops.extractfields(data, commdct, objkey, fieldlists) # code only for AirTerminal:SingleDuct:VAV:Reheat # get airinletnodes for vavreheats # in AirTerminal:SingleDuct:VAV:Reheat: # get Name, airinletnode adistuinlets = loops.makeadistu_inlets(data, commdct) alladistu_comps = [] for key in list(adistuinlets.keys()): objkey = key.upper() singlefields = ["Name"] + adistuinlets[key] repeatfields = [] fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) adistu_components = loops.extractfields(data, commdct, objkey, fieldlists) alladistu_comps.append(adistu_components) # in AirTerminal:SingleDuct:Uncontrolled: # get Name, airinletnode objkey = "AirTerminal:SingleDuct:Uncontrolled".upper() singlefields = ["Name", "Zone Supply Air Node Name"] repeatfields = [] fieldlist = singlefields + repeatfields fieldlists = [fieldlist] * loops.objectcount(data, objkey) uncontrolleds = loops.extractfields(data, commdct, objkey, fieldlists) anode = "epnode" endnode = "EndNode" # edges = [] # connect demand and supply side # for airloophvac in airloophvacs: # supplyinlet = airloophvac[1] # supplyoutlet = airloophvac[4] # demandinlet = airloophvac[3] # demandoutlet = airloophvac[2] # # edges = [supplyoutlet -> demandinlet, demandoutlet -> supplyinlet] # moreedges = [((supplyoutlet, endnode), (demandinlet, endnode)), # ((demandoutlet, endnode), (supplyinlet, endnode))] # edges = edges + moreedges # connect zonesplitter to nodes for zonesplitter in zonesplitters: name = zonesplitter[0] inlet = zonesplitter[1] outlets = zonesplitter[2:] edges.append(((inlet, anode), name)) for outlet in outlets: edges.append((name, (outlet, anode))) # connect supplyplenum to nodes for supplyplenum in supplyplenums: name = supplyplenum[0] inlet = supplyplenum[3] outlets = supplyplenum[4:] edges.append(((inlet, anode), name)) for outlet in outlets: edges.append((name, (outlet, anode))) # connect zonemixer to nodes for zonemixer in zonemixers: name = zonemixer[0] outlet = zonemixer[1] inlets = zonemixer[2:] edges.append((name, (outlet, anode))) for inlet in inlets: edges.append(((inlet, anode), name)) # connect returnplenums to nodes for returnplenum in returnplenums: name = returnplenum[0] outlet = returnplenum[3] inlets = returnplenum[4:] edges.append((name, (outlet, anode))) for inlet in inlets: edges.append(((inlet, anode), name)) # connect room to return node for equipconnection in equipconnections: zonename = equipconnection[0] returnnode = equipconnection[-1] edges.append((zonename, (returnnode, anode))) # connect equips to room for equipconnection in equipconnections: zonename = equipconnection[0] zequiplistname = equipconnection[1] for zequip in equiplistdct[zequiplistname]: edges.append((zequip, zonename)) # adistuunit <- adistu_component for adistuunit in adistuunits: unitname = adistuunit[0] compname = adistuunit[2] edges.append((compname, unitname)) # airinlet -> adistu_component for adistu_comps in alladistu_comps: for adistu_comp in adistu_comps: name = adistu_comp[0] for airnode in adistu_comp[1:]: edges.append(((airnode, anode), name)) # supplyairnode -> uncontrolled for uncontrolled in uncontrolleds: name = uncontrolled[0] airnode = uncontrolled[1] edges.append(((airnode, anode), name)) # edges = edges + moreedges return edges
return the edges of the idf file fname def getedges(fname, iddfile): """return the edges of the idf file fname""" data, commdct, _idd_index = readidf.readdatacommdct(fname, iddfile=iddfile) edges = makeairplantloop(data, commdct) return edges
input 'astr' which is the Energy+.idd file as a string returns (st1, st2, lss) st1 = with all the ! comments striped st2 = strips all comments - both the '!' and '\\' lss = nested list of all the variables in Energy+.idd file def get_nocom_vars(astr): """ input 'astr' which is the Energy+.idd file as a string returns (st1, st2, lss) st1 = with all the ! comments striped st2 = strips all comments - both the '!' and '\\' lss = nested list of all the variables in Energy+.idd file """ nocom = nocomment(astr, '!')# remove '!' comments st1 = nocom nocom1 = nocomment(st1, '\\')# remove '\' comments st1 = nocom st2 = nocom1 # alist = string.split(st2, ';') alist = st2.split(';') lss = [] # break the .idd file into a nested list #======================================= for element in alist: # item = string.split(element, ',') item = element.split(',') lss.append(item) for i in range(0, len(lss)): for j in range(0, len(lss[i])): lss[i][j] = lss[i][j].strip() if len(lss) > 1: lss.pop(-1) #======================================= #st1 has the '\' comments --- looks like I don't use this #lss is the .idd file as a nested list return (st1, st2, lss)
remove the blank lines in astr def removeblanklines(astr): """remove the blank lines in astr""" lines = astr.splitlines() lines = [line for line in lines if line.strip() != ""] return "\n".join(lines)
copied from extractidddata below. It deals with all the types of fnames def _readfname(fname): """copied from extractidddata below. It deals with all the types of fnames""" try: if isinstance(fname, (file, StringIO)): astr = fname.read() else: astr = open(fname, 'rb').read() except NameError: if isinstance(fname, (FileIO, StringIO)): astr = fname.read() else: astr = mylib2.readfile(fname) return astr
generate the iddindex def make_idd_index(extract_func, fname, debug): """generate the iddindex""" astr = _readfname(fname) # fname is exhausted by the above read # reconstitute fname as a StringIO fname = StringIO(astr) # glist = iddgroups.iddtxt2grouplist(astr.decode('ISO-8859-2')) blocklst, commlst, commdct = extract_func(fname) name2refs = iddindex.makename2refdct(commdct) ref2namesdct = iddindex.makeref2namesdct(name2refs) idd_index = dict(name2refs=name2refs, ref2names=ref2namesdct) commdct = iddindex.ref2names2commdct(ref2namesdct, commdct) return blocklst, commlst, commdct, idd_index
insert group info into extracted idd def embedgroupdata(extract_func, fname, debug): """insert group info into extracted idd""" astr = _readfname(fname) # fname is exhausted by the above read # reconstitute fname as a StringIO fname = StringIO(astr) try: astr = astr.decode('ISO-8859-2') except Exception as e: pass # for python 3 glist = iddgroups.iddtxt2grouplist(astr) blocklst, commlst, commdct = extract_func(fname) # add group information to commlst and commdct # glist = getglist(fname) commlst = iddgroups.group2commlst(commlst, glist) commdct = iddgroups.group2commdct(commdct, glist) return blocklst, commlst, commdct
extracts all the needed information out of the idd file if debug is True, it generates a series of text files. Each text file is incrementally different. You can do a diff see what the change is - this code is from 2004. it works. I am trying not to change it (until I rewrite the whole thing) to add functionality to it, I am using decorators So if Does not integrate group data into the results (@embedgroupdata does it) Does not integrate iddindex into the results (@make_idd_index does it) def extractidddata(fname, debug=False): """ extracts all the needed information out of the idd file if debug is True, it generates a series of text files. Each text file is incrementally different. You can do a diff see what the change is - this code is from 2004. it works. I am trying not to change it (until I rewrite the whole thing) to add functionality to it, I am using decorators So if Does not integrate group data into the results (@embedgroupdata does it) Does not integrate iddindex into the results (@make_idd_index does it) """ try: if isinstance(fname, (file, StringIO)): astr = fname.read() try: astr = astr.decode('ISO-8859-2') except AttributeError: pass else: astr = mylib2.readfile(fname) # astr = astr.decode('ISO-8859-2') -> mylib1 does a decode except NameError: if isinstance(fname, (FileIO, StringIO)): astr = fname.read() try: astr = astr.decode('ISO-8859-2') except AttributeError: pass else: astr = mylib2.readfile(fname) # astr = astr.decode('ISO-8859-2') -> mylib2.readfile has decoded (nocom, nocom1, blocklst) = get_nocom_vars(astr) astr = nocom st1 = removeblanklines(astr) if debug: mylib1.write_str2file('nocom2.txt', st1.encode('latin-1')) #find the groups and the start object of the group #find all the group strings groupls = [] alist = st1.splitlines() for element in alist: lss = element.split() if lss[0].upper() == '\\group'.upper(): groupls.append(element) #find the var just after each item in groupls groupstart = [] for i in range(len(groupls)): iindex = alist.index(groupls[i]) groupstart.append([alist[iindex], alist[iindex+1]]) #remove the group commentline for element in groupls: alist.remove(element) if debug: st1 = '\n'.join(alist) mylib1.write_str2file('nocom3.txt', st1.encode('latin-1')) #strip each line for i in range(len(alist)): alist[i] = alist[i].strip() if debug: st1 = '\n'.join(alist) mylib1.write_str2file('nocom4.txt', st1.encode('latin-1')) #ensure that each line is a comment or variable #find lines that don't start with a comment #if this line has a comment in it # then move the comment to a new line below lss = [] for i in range(len(alist)): #find lines that don't start with a comment if alist[i][0] != '\\': #if this line has a comment in it pnt = alist[i].find('\\') if pnt != -1: #then move the comment to a new line below lss.append(alist[i][:pnt].strip()) lss.append(alist[i][pnt:].strip()) else: lss.append(alist[i]) else: lss.append(alist[i]) alist = lss[:] if debug: st1 = '\n'.join(alist) mylib1.write_str2file('nocom5.txt', st1.encode('latin-1')) #need to make sure that each line has only one variable - as in WindowGlassSpectralData, lss = [] for element in alist: # if the line is not a comment if element[0] != '\\': #test for more than one var llist = element.split(',') if llist[-1] == '': tmp = llist.pop() for elm in llist: if elm[-1] == ';': lss.append(elm.strip()) else: lss.append((elm+',').strip()) else: lss.append(element) ls_debug = alist[:] # needed for the next debug - 'nocom7.txt' alist = lss[:] if debug: st1 = '\n'.join(alist) mylib1.write_str2file('nocom6.txt', st1.encode('latin-1')) if debug: #need to make sure that each line has only one variable - as in WindowGlassSpectralData, #this is same as above. # but the variables are put in without the ';' and ',' #so we can do a diff between 'nocom7.txt' and 'nocom8.txt'. Should be identical lss_debug = [] for element in ls_debug: # if the line is not a comment if element[0] != '\\': #test for more than one var llist = element.split(',') if llist[-1] == '': tmp = llist.pop() for elm in llist: if elm[-1] == ';': lss_debug.append(elm[:-1].strip()) else: lss_debug.append((elm).strip()) else: lss_debug.append(element) ls_debug = lss_debug[:] st1 = '\n'.join(ls_debug) mylib1.write_str2file('nocom7.txt', st1.encode('latin-1')) #replace each var with '=====var======' #join into a string, #split using '=====var=====' for i in range(len(lss)): #if the line is not a comment if lss[i][0] != '\\': lss[i] = '=====var=====' st2 = '\n'.join(lss) lss = st2.split('=====var=====\n') lss.pop(0) # the above split generates an extra item at start if debug: fname = 'nocom8.txt' fhandle = open(fname, 'wb') k = 0 for i in range(len(blocklst)): for j in range(len(blocklst[i])): atxt = blocklst[i][j]+'\n' fhandle.write(atxt) atxt = lss[k] fhandle.write(atxt.encode('latin-1')) k = k+1 fhandle.close() #map the structure of the comments -(this is 'lss' now) to #the structure of blocklst - blocklst is a nested list #make lss a similar nested list k = 0 lst = [] for i in range(len(blocklst)): lst.append([]) for j in range(len(blocklst[i])): lst[i].append(lss[k]) k = k+1 if debug: fname = 'nocom9.txt' fhandle = open(fname, 'wb') k = 0 for i in range(len(blocklst)): for j in range(len(blocklst[i])): atxt = blocklst[i][j]+'\n' fhandle.write(atxt) fhandle.write(lst[i][j].encode('latin-1')) k = k+1 fhandle.close() #break up multiple line comment so that it is a list for i in range(len(lst)): for j in range(len(lst[i])): lst[i][j] = lst[i][j].splitlines() # remove the '\' for k in range(len(lst[i][j])): lst[i][j][k] = lst[i][j][k][1:] commlst = lst #copied with minor modifications from readidd2_2.py -- which has been erased ha ! clist = lst lss = [] for i in range(0, len(clist)): alist = [] for j in range(0, len(clist[i])): itt = clist[i][j] ddtt = {} for element in itt: if len(element.split()) == 0: break ddtt[element.split()[0].lower()] = [] for element in itt: if len(element.split()) == 0: break # ddtt[element.split()[0].lower()].append(string.join(element.split()[1:])) ddtt[element.split()[0].lower()].append(' '.join(element.split()[1:])) alist.append(ddtt) lss.append(alist) commdct = lss # add group information to commlst and commdct # glist = iddgroups.idd2grouplist(fname) # commlst = group2commlst(commlst, glist) # commdct = group2commdct(commdct, glist) return blocklst, commlst, commdct
makes a dictionary of object-lists each item in the dictionary points to a list of tuples the tuple is (objectname, fieldindex) def getobjectref(blocklst, commdct): """ makes a dictionary of object-lists each item in the dictionary points to a list of tuples the tuple is (objectname, fieldindex) """ objlst_dct = {} for eli in commdct: for elj in eli: if 'object-list' in elj: objlist = elj['object-list'][0] objlst_dct[objlist] = [] for objlist in list(objlst_dct.keys()): for i in range(len(commdct)): for j in range(len(commdct[i])): if 'reference' in commdct[i][j]: for ref in commdct[i][j]['reference']: if ref == objlist: objlst_dct[objlist].append((blocklst[i][0], j)) return objlst_dct
read the idf file def readdatacommlst(idfname): """read the idf file""" # iddfile = sys.path[0] + '/EplusCode/Energy+.idd' iddfile = 'Energy+.idd' # iddfile = './EPlusInterfaceFunctions/E1.idd' # TODO : can the path name be not hard coded iddtxt = open(iddfile, 'r').read() block, commlst, commdct = parse_idd.extractidddata(iddfile) theidd = eplusdata.Idd(block, 2) data = eplusdata.Eplusdata(theidd, idfname) return data, commlst
read the idf file def readdatacommdct(idfname, iddfile='Energy+.idd', commdct=None): """read the idf file""" if not commdct: block, commlst, commdct, idd_index = parse_idd.extractidddata(iddfile) theidd = eplusdata.Idd(block, 2) else: theidd = iddfile data = eplusdata.Eplusdata(theidd, idfname) return data, commdct, idd_index
get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the contents of those fields def extractfields(data, commdct, objkey, fieldlists): """get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the contents of those fields""" # TODO : this assumes that the field list identical for # each instance of the object. This is not true. # So we should have a field list for each instance of the object # and map them with a zip objindex = data.dtls.index(objkey) objcomm = commdct[objindex] objfields = [] # get the field names of that object for dct in objcomm[0:]: try: thefieldcomms = dct['field'] objfields.append(thefieldcomms[0]) except KeyError as err: objfields.append(None) fieldindexes = [] for fieldlist in fieldlists: fieldindex = [] for item in fieldlist: if isinstance(item, int): fieldindex.append(item) else: fieldindex.append(objfields.index(item) + 0) # the index starts at 1, not at 0 fieldindexes.append(fieldindex) theobjects = data.dt[objkey] fieldcontents = [] for theobject, fieldindex in zip(theobjects, fieldindexes): innerlst = [] for item in fieldindex: try: innerlst.append(theobject[item]) except IndexError as err: break fieldcontents.append(innerlst) # fieldcontents.append([theobject[item] for item in fieldindex]) return fieldcontents
return the plantloopfield list def plantloopfieldlists(data): """return the plantloopfield list""" objkey = 'plantloop'.upper() numobjects = len(data.dt[objkey]) return [[ 'Name', 'Plant Side Inlet Node Name', 'Plant Side Outlet Node Name', 'Plant Side Branch List Name', 'Demand Side Inlet Node Name', 'Demand Side Outlet Node Name', 'Demand Side Branch List Name']] * numobjects
get plantloop fields to diagram it def plantloopfields(data, commdct): """get plantloop fields to diagram it""" fieldlists = plantloopfieldlists(data) objkey = 'plantloop'.upper() return extractfields(data, commdct, objkey, fieldlists)
get branches from the branchlist def branchlist2branches(data, commdct, branchlist): """get branches from the branchlist""" objkey = 'BranchList'.upper() theobjects = data.dt[objkey] fieldlists = [] objnames = [obj[1] for obj in theobjects] for theobject in theobjects: fieldlists.append(list(range(2, len(theobject)))) blists = extractfields(data, commdct, objkey, fieldlists) thebranches = [branches for name, branches in zip(objnames, blists) if name == branchlist] return thebranches[0]
return the inlet and outlet of a branch def branch_inlet_outlet(data, commdct, branchname): """return the inlet and outlet of a branch""" objkey = 'Branch'.upper() theobjects = data.dt[objkey] theobject = [obj for obj in theobjects if obj[1] == branchname] theobject = theobject[0] inletindex = 6 outletindex = len(theobject) - 2 return [theobject[inletindex], theobject[outletindex]]
docstring for splittermixerfieldlists def splittermixerfieldlists(data, commdct, objkey): """docstring for splittermixerfieldlists""" objkey = objkey.upper() objindex = data.dtls.index(objkey) objcomms = commdct[objindex] theobjects = data.dt[objkey] fieldlists = [] for theobject in theobjects: fieldlist = list(range(1, len(theobject))) fieldlists.append(fieldlist) return fieldlists
get splitter fields to diagram it def splitterfields(data, commdct): """get splitter fields to diagram it""" objkey = "Connector:Splitter".upper() fieldlists = splittermixerfieldlists(data, commdct, objkey) return extractfields(data, commdct, objkey, fieldlists)
get mixer fields to diagram it def mixerfields(data, commdct): """get mixer fields to diagram it""" objkey = "Connector:Mixer".upper() fieldlists = splittermixerfieldlists(data, commdct, objkey) return extractfields(data, commdct, objkey, fieldlists)
return a list of repeating fields fld is in format 'Component %s Name' so flds = [fld % (i, ) for i in range(n)] does not work for 'fields as indicated' def repeatingfields(theidd, commdct, objkey, flds): """return a list of repeating fields fld is in format 'Component %s Name' so flds = [fld % (i, ) for i in range(n)] does not work for 'fields as indicated' """ # TODO : make it work for 'fields as indicated' if type(flds) != list: flds = [flds] # for backward compatability objindex = theidd.dtls.index(objkey) objcomm = commdct[objindex] allfields = [] for fld in flds: thefields = [] indx = 1 for i in range(len(objcomm)): try: thefield = fld % (indx, ) if objcomm[i]['field'][0] == thefield: thefields.append(thefield) indx = indx + 1 except KeyError as err: pass allfields.append(thefields) allfields = list(zip(*allfields)) return [item for sublist in allfields for item in sublist]
return the count of objects of key def objectcount(data, key): """return the count of objects of key""" objkey = key.upper() return len(data.dt[objkey])
given objkey and fieldname, return its index def getfieldindex(data, commdct, objkey, fname): """given objkey and fieldname, return its index""" objindex = data.dtls.index(objkey) objcomm = commdct[objindex] for i_index, item in enumerate(objcomm): try: if item['field'] == [fname]: break except KeyError as err: pass return i_index
docstring for fname def getadistus(data, commdct): """docstring for fname""" objkey = "ZoneHVAC:AirDistributionUnit".upper() objindex = data.dtls.index(objkey) objcomm = commdct[objindex] adistutypefield = "Air Terminal Object Type" ifield = getfieldindex(data, commdct, objkey, adistutypefield) adistus = objcomm[ifield]['key'] return adistus
make the dict adistu_inlets def makeadistu_inlets(data, commdct): """make the dict adistu_inlets""" adistus = getadistus(data, commdct) # assume that the inlet node has the words "Air Inlet Node Name" airinletnode = "Air Inlet Node Name" adistu_inlets = {} for adistu in adistus: objkey = adistu.upper() objindex = data.dtls.index(objkey) objcomm = commdct[objindex] airinlets = [] for i, comm in enumerate(objcomm): try: if comm['field'][0].find(airinletnode) != -1: airinlets.append(comm['field'][0]) except KeyError as err: pass adistu_inlets[adistu] = airinlets return adistu_inlets
get the version number from the E+ install folder def folder2ver(folder): """get the version number from the E+ install folder""" ver = folder.split('EnergyPlus')[-1] ver = ver[1:] splitapp = ver.split('-') ver = '.'.join(splitapp) return ver
just like the comment in python. removes any text after the phrase 'com' def nocomment(astr, com='!'): """ just like the comment in python. removes any text after the phrase 'com' """ alist = astr.splitlines() for i in range(len(alist)): element = alist[i] pnt = element.find(com) if pnt != -1: alist[i] = element[:pnt] return '\n'.join(alist)
convert the idf text to a simple text def idf2txt(txt): """convert the idf text to a simple text""" astr = nocomment(txt) objs = astr.split(';') objs = [obj.split(',') for obj in objs] objs = [[line.strip() for line in obj] for obj in objs] objs = [[_tofloat(line) for line in obj] for obj in objs] objs = [tuple(obj) for obj in objs] objs.sort() lst = [] for obj in objs: for field in obj[:-1]: lst.append('%s,' % (field, )) lst.append('%s;\n' % (obj[-1], )) return '\n'.join(lst)
given the idd file or filehandle, return the version handle def iddversiontuple(afile): """given the idd file or filehandle, return the version handle""" def versiontuple(vers): """version tuple""" return tuple([int(num) for num in vers.split(".")]) try: fhandle = open(afile, 'rb') except TypeError: fhandle = afile line1 = fhandle.readline() try: line1 = line1.decode('ISO-8859-2') except AttributeError: pass line = line1.strip() if line1 == '': return (0,) vers = line.split()[-1] return versiontuple(vers)
make a bunch from the object def makeabunch(commdct, obj, obj_i): """make a bunch from the object""" objidd = commdct[obj_i] objfields = [comm.get('field') for comm in commdct[obj_i]] objfields[0] = ['key'] objfields = [field[0] for field in objfields] obj_fields = [bunchhelpers.makefieldname(field) for field in objfields] bobj = EpBunch(obj, obj_fields, objidd) return bobj
make bunches with data def makebunches(data, commdct): """make bunches with data""" bunchdt = {} ddtt, dtls = data.dt, data.dtls for obj_i, key in enumerate(dtls): key = key.upper() bunchdt[key] = [] objs = ddtt[key] for obj in objs: bobj = makeabunch(commdct, obj, obj_i) bunchdt[key].append(bobj) return bunchdt
make bunches with data def makebunches_alter(data, commdct, theidf): """make bunches with data""" bunchdt = {} dt, dtls = data.dt, data.dtls for obj_i, key in enumerate(dtls): key = key.upper() objs = dt[key] list1 = [] for obj in objs: bobj = makeabunch(commdct, obj, obj_i) list1.append(bobj) bunchdt[key] = Idf_MSequence(list1, objs, theidf) return bunchdt
convert the float and interger fields def convertfields_old(key_comm, obj, inblock=None): """convert the float and interger fields""" convinidd = ConvInIDD() typefunc = dict(integer=convinidd.integer, real=convinidd.real) types = [] for comm in key_comm: types.append(comm.get('type', [None])[0]) convs = [typefunc.get(typ, convinidd.no_type) for typ in types] try: inblock = list(inblock) except TypeError as e: inblock = ['does not start with N'] * len(obj) for i, (val, conv, avar) in enumerate(zip(obj, convs, inblock)): if i == 0: # inblock[0] is the key pass else: val = conv(val, inblock[i]) obj[i] = val return obj
convert field based on field info in IDD def convertafield(field_comm, field_val, field_iddname): """convert field based on field info in IDD""" convinidd = ConvInIDD() field_typ = field_comm.get('type', [None])[0] conv = convinidd.conv_dict().get(field_typ, convinidd.no_type) return conv(field_val, field_iddname)
convert based on float, integer, and A1, N1 def convertfields(key_comm, obj, inblock=None): """convert based on float, integer, and A1, N1""" # f_ stands for field_ convinidd = ConvInIDD() if not inblock: inblock = ['does not start with N'] * len(obj) for i, (f_comm, f_val, f_iddname) in enumerate(zip(key_comm, obj, inblock)): if i == 0: # inblock[0] is the iddobject key. No conversion here pass else: obj[i] = convertafield(f_comm, f_val, f_iddname) return obj
docstring for convertallfields def convertallfields(data, commdct, block=None): """docstring for convertallfields""" # import pdbdb; pdb.set_trace() for key in list(data.dt.keys()): objs = data.dt[key] for i, obj in enumerate(objs): key_i = data.dtls.index(key) key_comm = commdct[key_i] try: inblock = block[key_i] except TypeError as e: inblock = None obj = convertfields(key_comm, obj, inblock) objs[i] = obj
add functions to the objects def addfunctions(dtls, bunchdt): """add functions to the objects""" snames = [ "BuildingSurface:Detailed", "Wall:Detailed", "RoofCeiling:Detailed", "Floor:Detailed", "FenestrationSurface:Detailed", "Shading:Site:Detailed", "Shading:Building:Detailed", "Shading:Zone:Detailed", ] for sname in snames: if sname.upper() in bunchdt: surfaces = bunchdt[sname.upper()] for surface in surfaces: func_dict = { 'area': fh.area, 'height': fh.height, # not working correctly 'width': fh.width, # not working correctly 'azimuth': fh.azimuth, 'tilt': fh.tilt, 'coords': fh.getcoords, # needed for debugging } try: surface.__functions.update(func_dict) except KeyError as e: surface.__functions = func_dict
add functions to a new bunch/munch object def addfunctions2new(abunch, key): """add functions to a new bunch/munch object""" snames = [ "BuildingSurface:Detailed", "Wall:Detailed", "RoofCeiling:Detailed", "Floor:Detailed", "FenestrationSurface:Detailed", "Shading:Site:Detailed", "Shading:Building:Detailed", "Shading:Zone:Detailed", ] snames = [sname.upper() for sname in snames] if key in snames: func_dict = { 'area': fh.area, 'height': fh.height, # not working correctly 'width': fh.width, # not working correctly 'azimuth': fh.azimuth, 'tilt': fh.tilt, 'coords': fh.getcoords, # needed for debugging } try: abunch.__functions.update(func_dict) except KeyError as e: abunch.__functions = func_dict return abunch
read idf file and return bunches def idfreader(fname, iddfile, conv=True): """read idf file and return bunches""" data, commdct, idd_index = readidf.readdatacommdct(fname, iddfile=iddfile) if conv: convertallfields(data, commdct) # fill gaps in idd ddtt, dtls = data.dt, data.dtls # skiplist = ["TABLE:MULTIVARIABLELOOKUP"] nofirstfields = iddgaps.missingkeys_standard( commdct, dtls, skiplist=["TABLE:MULTIVARIABLELOOKUP"]) iddgaps.missingkeys_nonstandard(None, commdct, dtls, nofirstfields) bunchdt = makebunches(data, commdct) return bunchdt, data, commdct, idd_index
read idf file and return bunches def idfreader1(fname, iddfile, theidf, conv=True, commdct=None, block=None): """read idf file and return bunches""" versiontuple = iddversiontuple(iddfile) # import pdb; pdb.set_trace() block, data, commdct, idd_index = readidf.readdatacommdct1( fname, iddfile=iddfile, commdct=commdct, block=block) if conv: convertallfields(data, commdct, block) # fill gaps in idd ddtt, dtls = data.dt, data.dtls if versiontuple < (8,): skiplist = ["TABLE:MULTIVARIABLELOOKUP"] else: skiplist = None nofirstfields = iddgaps.missingkeys_standard( commdct, dtls, skiplist=skiplist) iddgaps.missingkeys_nonstandard(block, commdct, dtls, nofirstfields) # bunchdt = makebunches(data, commdct) bunchdt = makebunches_alter(data, commdct, theidf) return bunchdt, block, data, commdct, idd_index, versiontuple
dictionary of conversion def conv_dict(self): """dictionary of conversion""" return dict(integer=self.integer, real=self.real, no_type=self.no_type)
Find out if idjobject is mentioned an any object anywhere def getanymentions(idf, anidfobject): """Find out if idjobject is mentioned an any object anywhere""" name = anidfobject.obj[1] foundobjs = [] keys = idfobjectkeys(idf) idfkeyobjects = [idf.idfobjects[key.upper()] for key in keys] for idfobjects in idfkeyobjects: for idfobject in idfobjects: if name.upper() in [item.upper() for item in idfobject.obj if isinstance(item, basestring)]: foundobjs.append(idfobject) return foundobjs
field=object_name, prev_field=object_type. Return the object def getobject_use_prevfield(idf, idfobject, fieldname): """field=object_name, prev_field=object_type. Return the object""" if not fieldname.endswith("Name"): return None # test if prevfieldname ends with "Object_Type" fdnames = idfobject.fieldnames ifieldname = fdnames.index(fieldname) prevfdname = fdnames[ifieldname - 1] if not prevfdname.endswith("Object_Type"): return None objkey = idfobject[prevfdname].upper() objname = idfobject[fieldname] try: foundobj = idf.getobject(objkey, objname) except KeyError as e: return None return foundobj
return a list of keys of idfobjects that hve 'None Name' fields def getidfkeyswithnodes(): """return a list of keys of idfobjects that hve 'None Name' fields""" idf = IDF(StringIO("")) keys = idfobjectkeys(idf) keysfieldnames = ((key, idf.newidfobject(key.upper()).fieldnames) for key in keys) keysnodefdnames = ((key, (name for name in fdnames if (name.endswith('Node_Name')))) for key, fdnames in keysfieldnames) nodekeys = [key for key, fdnames in keysnodefdnames if list(fdnames)] return nodekeys
return all objects that mention this node name def getobjectswithnode(idf, nodekeys, nodename): """return all objects that mention this node name""" keys = nodekeys # TODO getidfkeyswithnodes needs to be done only once. take out of here listofidfobjects = (idf.idfobjects[key.upper()] for key in keys if idf.idfobjects[key.upper()]) idfobjects = [idfobj for idfobjs in listofidfobjects for idfobj in idfobjs] objwithnodes = [] for obj in idfobjects: values = obj.fieldvalues fdnames = obj.fieldnames for value, fdname in zip(values, fdnames): if fdname.endswith('Node_Name'): if value == nodename: objwithnodes.append(obj) break return objwithnodes
return the object, if the Name or some other field is known. send filed in **kwargs as Name='a name', Roughness='smooth' Returns the first find (field search is unordered) objkeys -> if objkeys=['ZONE', 'Material'], search only those groupnames -> not yet coded def name2idfobject(idf, groupnamess=None, objkeys=None, **kwargs): """return the object, if the Name or some other field is known. send filed in **kwargs as Name='a name', Roughness='smooth' Returns the first find (field search is unordered) objkeys -> if objkeys=['ZONE', 'Material'], search only those groupnames -> not yet coded""" # TODO : this is a very slow search. revist to speed it up. if not objkeys: objkeys = idfobjectkeys(idf) for objkey in objkeys: idfobjs = idf.idfobjects[objkey.upper()] for idfobj in idfobjs: for key, val in kwargs.items(): try: if idfobj[key] == val: return idfobj except BadEPFieldError as e: continue
return a list of all idfobjects in idf def getidfobjectlist(idf): """return a list of all idfobjects in idf""" idfobjects = idf.idfobjects # idfobjlst = [idfobjects[key] for key in idfobjects if idfobjects[key]] idfobjlst = [idfobjects[key] for key in idf.model.dtls if idfobjects[key]] # `for key in idf.model.dtls` maintains the order # `for key in idfobjects` does not have order idfobjlst = itertools.chain.from_iterable(idfobjlst) idfobjlst = list(idfobjlst) return idfobjlst
copy fromidf completely into toidf def copyidfintoidf(toidf, fromidf): """copy fromidf completely into toidf""" idfobjlst = getidfobjectlist(fromidf) for idfobj in idfobjlst: toidf.copyidfobject(idfobj)
return the diffs between the two idfs def idfdiffs(idf1, idf2): """return the diffs between the two idfs""" thediffs = {} keys = idf1.model.dtls # undocumented variable for akey in keys: idfobjs1 = idf1.idfobjects[akey] idfobjs2 = idf2.idfobjects[akey] names = set([getobjname(i) for i in idfobjs1] + [getobjname(i) for i in idfobjs2]) names = sorted(names) idfobjs1 = sorted(idfobjs1, key=lambda idfobj: idfobj['obj']) idfobjs2 = sorted(idfobjs2, key=lambda idfobj: idfobj['obj']) for name in names: n_idfobjs1 = [item for item in idfobjs1 if getobjname(item) == name] n_idfobjs2 = [item for item in idfobjs2 if getobjname(item) == name] for idfobj1, idfobj2 in itertools.zip_longest(n_idfobjs1, n_idfobjs2): if idfobj1 == None: thediffs[(idfobj2.key.upper(), getobjname(idfobj2))] = (None, idf1.idfname) #(idf1.idfname, None) break if idfobj2 == None: thediffs[(idfobj1.key.upper(), getobjname(idfobj1))] = (idf2.idfname, None) # (None, idf2.idfname) break # for i, (f1, f2) in enumerate(zip(idfobj1.obj, idfobj2.obj)): # if i == 0: # f1, f2 = f1.upper(), f2.upper() # if f1 != f2: # thediffs[(akey, # getobjname(idfobj1), # idfobj1.objidd[i]['field'][0])] = (f1, f2) return thediffs
return autsizeable field names in idfobject def autosize_fieldname(idfobject): """return autsizeable field names in idfobject""" # undocumented stuff in this code return [fname for (fname, dct) in zip(idfobject.objls, idfobject['objidd']) if 'autosizable' in dct]
wrapper for iddtxt2groups def idd2group(fhandle): """wrapper for iddtxt2groups""" try: txt = fhandle.read() return iddtxt2groups(txt) except AttributeError as e: txt = open(fhandle, 'r').read() return iddtxt2groups(txt)
wrapper for iddtxt2grouplist def idd2grouplist(fhandle): """wrapper for iddtxt2grouplist""" try: txt = fhandle.read() return iddtxt2grouplist(txt) except AttributeError as e: txt = open(fhandle, 'r').read() return iddtxt2grouplist(txt)
extract the groups from the idd file def iddtxt2groups(txt): """extract the groups from the idd file""" try: txt = txt.decode('ISO-8859-2') except AttributeError as e: pass # for python 3 txt = nocomment(txt, '!') txt = txt.replace("\\group", "!-group") # retains group in next line txt = nocomment(txt, '\\') # remove all other idd info lines = txt.splitlines() lines = [line.strip() for line in lines] # cleanup lines = [line for line in lines if line != ''] # cleanup txt = '\n'.join(lines) gsplits = txt.split('!') # split into groups, since we have !-group gsplits = [gsplit.splitlines() for gsplit in gsplits] # split group gsplits[0].insert(0, None) # Put None for the first group that does nothave a group name gdict = {} for gsplit in gsplits: gdict.update({gsplit[0]:gsplit[1:]}) # makes dict {groupname:[k1, k2], groupname2:[k3, k4]} gdict = {k:'\n'.join(v) for k, v in gdict.items()}# joins lines back gdict = {k:v.split(';') for k, v in gdict.items()} # splits into idfobjects gdict = {k:[i.strip() for i in v] for k, v in gdict.items()} # cleanup gdict = {k:[i.splitlines() for i in v] for k, v in gdict.items()} # splits idfobjects into lines gdict = {k:[i for i in v if len(i) > 0] for k, v in gdict.items()} # cleanup - removes blank lines gdict = {k:[i[0] for i in v] for k, v in gdict.items()} # use first line gdict = {k:[i.split(',')[0] for i in v] for k, v in gdict.items()} # remove ',' nvalue = gdict.pop(None) # remove group with no name gdict = {k[len('-group '):]:v for k, v in gdict.items()} # get group name gdict.update({None:nvalue}) # put back group with no name return gdict
return a list of group names the list in the same order as the idf objects in idd file def iddtxt2grouplist(txt): """return a list of group names the list in the same order as the idf objects in idd file """ def makenone(astr): if astr == 'None': return None else: return astr txt = nocomment(txt, '!') txt = txt.replace("\\group", "!-group") # retains group in next line txt = nocomment(txt, '\\') # remove all other idd info lines = txt.splitlines() lines = [line.strip() for line in lines] # cleanup lines = [line for line in lines if line != ''] # cleanup txt = '\n'.join(lines) gsplits = txt.split('!') # split into groups, since we have !-group gsplits = [gsplit.splitlines() for gsplit in gsplits] # split group gsplits[0].insert(0, u'-group None') # Put None for the first group that does nothave a group name glist = [] for gsplit in gsplits: glist.append((gsplit[0], gsplit[1:])) # makes dict {groupname:[k1, k2], groupname2:[k3, k4]} glist = [(k, '\n'.join(v)) for k, v in glist]# joins lines back glist = [(k, v.split(';')) for k, v in glist] # splits into idfobjects glist = [(k, [i.strip() for i in v]) for k, v in glist] # cleanup glist = [(k, [i.splitlines() for i in v]) for k, v in glist] # splits idfobjects into lines glist = [(k, [i for i in v if len(i) > 0]) for k, v in glist] # cleanup - removes blank lines glist = [(k, [i[0] for i in v]) for k, v in glist] # use first line fglist = [] for gnamelist in glist: gname = gnamelist[0] thelist = gnamelist[-1] for item in thelist: fglist.append((gname, item)) glist = [(gname[len("-group "):], obj) for gname, obj in fglist] # remove "-group " glist = [(makenone(gname), obj) for gname, obj in glist] # make str None into None glist = [(gname, obj.split(',')[0]) for gname, obj in glist] # remove comma return glist
add group info to commlst def group2commlst(commlst, glist): """add group info to commlst""" for (gname, objname), commitem in zip(glist, commlst): newitem1 = "group %s" % (gname, ) newitem2 = "idfobj %s" % (objname, ) commitem[0].insert(0, newitem1) commitem[0].insert(1, newitem2) return commlst
add group info tocomdct def group2commdct(commdct, glist): """add group info tocomdct""" for (gname, objname), commitem in zip(glist, commdct): commitem[0]['group'] = gname commitem[0]['idfobj'] = objname return commdct
extract embedded group data from commdct. return gdict -> {g1:[obj1, obj2, obj3], g2:[obj4, ..]} def commdct2grouplist(gcommdct): """extract embedded group data from commdct. return gdict -> {g1:[obj1, obj2, obj3], g2:[obj4, ..]}""" gdict = {} for objidd in gcommdct: group = objidd[0]['group'] objname = objidd[0]['idfobj'] if group in gdict: gdict[group].append(objname) else: gdict[group] = [objname, ] return gdict
flatten and return a copy of the list indefficient on large lists def flattencopy(lst): """flatten and return a copy of the list indefficient on large lists""" # modified from # http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python thelist = copy.deepcopy(lst) list_is_nested = True while list_is_nested: # outer loop keepchecking = False atemp = [] for element in thelist: # inner loop if isinstance(element, list): atemp.extend(element) keepchecking = True else: atemp.append(element) list_is_nested = keepchecking # determine if outer loop exits thelist = atemp[:] return thelist
make a pipe component generate inlet outlet names def makepipecomponent(idf, pname): """make a pipe component generate inlet outlet names""" apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname) apipe.Inlet_Node_Name = "%s_inlet" % (pname,) apipe.Outlet_Node_Name = "%s_outlet" % (pname,) return apipe
make a duct component generate inlet outlet names def makeductcomponent(idf, dname): """make a duct component generate inlet outlet names""" aduct = idf.newidfobject("duct".upper(), Name=dname) aduct.Inlet_Node_Name = "%s_inlet" % (dname,) aduct.Outlet_Node_Name = "%s_outlet" % (dname,) return aduct
make a branch with a pipe use standard inlet outlet names def makepipebranch(idf, bname): """make a branch with a pipe use standard inlet outlet names""" # make the pipe component first pname = "%s_pipe" % (bname,) apipe = makepipecomponent(idf, pname) # now make the branch with the pipe in it abranch = idf.newidfobject("BRANCH", Name=bname) abranch.Component_1_Object_Type = 'Pipe:Adiabatic' abranch.Component_1_Name = pname abranch.Component_1_Inlet_Node_Name = apipe.Inlet_Node_Name abranch.Component_1_Outlet_Node_Name = apipe.Outlet_Node_Name abranch.Component_1_Branch_Control_Type = "Bypass" return abranch
make a branch with a duct use standard inlet outlet names def makeductbranch(idf, bname): """make a branch with a duct use standard inlet outlet names""" # make the duct component first pname = "%s_duct" % (bname,) aduct = makeductcomponent(idf, pname) # now make the branch with the duct in it abranch = idf.newidfobject("BRANCH", Name=bname) abranch.Component_1_Object_Type = 'duct' abranch.Component_1_Name = pname abranch.Component_1_Inlet_Node_Name = aduct.Inlet_Node_Name abranch.Component_1_Outlet_Node_Name = aduct.Outlet_Node_Name abranch.Component_1_Branch_Control_Type = "Bypass" return abranch
get the components of the branch def getbranchcomponents(idf, branch, utest=False): """get the components of the branch""" fobjtype = 'Component_%s_Object_Type' fobjname = 'Component_%s_Name' complist = [] for i in range(1, 100000): try: objtype = branch[fobjtype % (i,)] if objtype.strip() == '': break objname = branch[fobjname % (i,)] complist.append((objtype, objname)) except bunch_subclass.BadEPFieldError: break if utest: return complist else: return [idf.getobject(ot, on) for ot, on in complist]
rename all the changed nodes def renamenodes(idf, fieldtype): """rename all the changed nodes""" renameds = [] for key in idf.model.dtls: for idfobject in idf.idfobjects[key]: for fieldvalue in idfobject.obj: if type(fieldvalue) is list: if fieldvalue not in renameds: cpvalue = copy.copy(fieldvalue) renameds.append(cpvalue) # do the renaming for key in idf.model.dtls: for idfobject in idf.idfobjects[key]: for i, fieldvalue in enumerate(idfobject.obj): itsidd = idfobject.objidd[i] if 'type' in itsidd: if itsidd['type'][0] == fieldtype: tempdct = dict(renameds) if type(fieldvalue) is list: fieldvalue = fieldvalue[-1] idfobject.obj[i] = fieldvalue else: if fieldvalue in tempdct: fieldvalue = tempdct[fieldvalue] idfobject.obj[i] = fieldvalue