sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
def simplefenestration(idf, fsd, deletebsd=True, setto000=False):
"""convert a bsd (fenestrationsurface:detailed) into a simple
fenestrations"""
funcs = (window,
door,
glazeddoor,)
for func in funcs:
fenestration = func(idf, fsd, deletebsd=deletebsd, setto000=setto000)
if fenestration:
return fenestration
return None | convert a bsd (fenestrationsurface:detailed) into a simple
fenestrations | entailment |
def tdbr2EOL(td):
"""convert the <br/> in <td> block into line ending (EOL = \n)"""
for br in td.find_all("br"):
br.replace_with("\n")
txt = six.text_type(td) # make it back into test
# would be unicode(id) in python2
soup = BeautifulSoup(txt, 'lxml') # read it as a BeautifulSoup
ntxt = soup.find('td') # BeautifulSoup has lot of other html junk.
# this line will extract just the <td> block
return ntxt | convert the <br/> in <td> block into line ending (EOL = \n) | entailment |
def is_simpletable(table):
"""test if the table has only strings in the cells"""
tds = table('td')
for td in tds:
if td.contents != []:
td = tdbr2EOL(td)
if len(td.contents) == 1:
thecontents = td.contents[0]
if not isinstance(thecontents, NavigableString):
return False
else:
return False
return True | test if the table has only strings in the cells | entailment |
def table2matrix(table):
"""convert a table to a list of lists - a 2D matrix"""
if not is_simpletable(table):
raise NotSimpleTable("Not able read a cell in the table as a string")
rows = []
for tr in table('tr'):
row = []
for td in tr('td'):
td = tdbr2EOL(td) # convert any '<br>' in the td to line ending
try:
row.append(td.contents[0])
except IndexError:
row.append('')
rows.append(row)
return rows | convert a table to a list of lists - a 2D matrix | entailment |
def table2val_matrix(table):
"""convert a table to a list of lists - a 2D matrix
Converts numbers to float"""
if not is_simpletable(table):
raise NotSimpleTable("Not able read a cell in the table as a string")
rows = []
for tr in table('tr'):
row = []
for td in tr('td'):
td = tdbr2EOL(td)
try:
val = td.contents[0]
except IndexError:
row.append('')
else:
try:
val = float(val)
row.append(val)
except ValueError:
row.append(val)
rows.append(row)
return rows | convert a table to a list of lists - a 2D matrix
Converts numbers to float | entailment |
def titletable(html_doc, tofloat=True):
"""return a list of [(title, table), .....]
title = previous item with a <b> tag
table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]"""
soup = BeautifulSoup(html_doc, "html.parser")
btables = soup.find_all(['b', 'table']) # find all the <b> and <table>
titletables = []
for i, item in enumerate(btables):
if item.name == 'table':
for j in range(i + 1):
if btables[i-j].name == 'b':# step back to find a <b>
break
titletables.append((btables[i - j], item))
if tofloat:
t2m = table2val_matrix
else:
t2m = table2matrix
titlerows = [(tl.contents[0], t2m(tb)) for tl, tb in titletables]
return titlerows | return a list of [(title, table), .....]
title = previous item with a <b> tag
table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..] | entailment |
def _has_name(soup_obj):
"""checks if soup_obj is really a soup object or just a string
If it has a name it is a soup object"""
try:
name = soup_obj.name
if name == None:
return False
return True
except AttributeError:
return False | checks if soup_obj is really a soup object or just a string
If it has a name it is a soup object | entailment |
def lines_table(html_doc, tofloat=True):
"""return a list of [(lines, table), .....]
lines = all the significant lines before the table.
These are lines between this table and
the previous table or 'hr' tag
table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]
The lines act as a description for what is in the table
"""
soup = BeautifulSoup(html_doc, "html.parser")
linestables = []
elements = soup.p.next_elements # start after the first para
for element in elements:
tabletup = []
if not _has_name(element):
continue
if element.name == 'table': # hit the first table
beforetable = []
prev_elements = element.previous_elements # walk back and get the lines
for prev_element in prev_elements:
if not _has_name(prev_element):
continue
if prev_element.name not in ('br', None): # no lines here
if prev_element.name in ('table', 'hr', 'tr', 'td'):
# just hit the previous table. You got all the lines
break
if prev_element.parent.name == "p":
# if the parent is "p", you will get it's text anyways from the parent
pass
else:
if prev_element.get_text(): # skip blank lines
beforetable.append(prev_element.get_text())
beforetable.reverse()
tabletup.append(beforetable)
function_selector = {True:table2val_matrix, False:table2matrix}
function = function_selector[tofloat]
tabletup.append(function(element))
if tabletup:
linestables.append(tabletup)
return linestables | return a list of [(lines, table), .....]
lines = all the significant lines before the table.
These are lines between this table and
the previous table or 'hr' tag
table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]
The lines act as a description for what is in the table | entailment |
def _make_ntgrid(grid):
"""make a named tuple grid
[["", "a b", "b c", "c d"],
["x y", 1, 2, 3 ],
["y z", 4, 5, 6 ],
["z z", 7, 8, 9 ],]
will return
ntcol(x_y=ntrow(a_b=1, b_c=2, c_d=3),
y_z=ntrow(a_b=4, b_c=5, c_d=6),
z_z=ntrow(a_b=7, b_c=8, c_d=9))"""
hnames = [_nospace(n) for n in grid[0][1:]]
vnames = [_nospace(row[0]) for row in grid[1:]]
vnames_s = " ".join(vnames)
hnames_s = " ".join(hnames)
ntcol = collections.namedtuple('ntcol', vnames_s)
ntrow = collections.namedtuple('ntrow', hnames_s)
rdict = [dict(list(zip(hnames, row[1:]))) for row in grid[1:]]
ntrows = [ntrow(**rdict[i]) for i, name in enumerate(vnames)]
ntcols = ntcol(**dict(list(zip(vnames, ntrows))))
return ntcols | make a named tuple grid
[["", "a b", "b c", "c d"],
["x y", 1, 2, 3 ],
["y z", 4, 5, 6 ],
["z z", 7, 8, 9 ],]
will return
ntcol(x_y=ntrow(a_b=1, b_c=2, c_d=3),
y_z=ntrow(a_b=4, b_c=5, c_d=6),
z_z=ntrow(a_b=7, b_c=8, c_d=9)) | entailment |
def onlylegalchar(name):
"""return only legal chars"""
legalchar = ascii_letters + digits + ' '
return ''.join([s for s in name[:] if s in legalchar]) | return only legal chars | entailment |
def matchfieldnames(field_a, field_b):
"""Check match between two strings, ignoring case and spaces/underscores.
Parameters
----------
a : str
b : str
Returns
-------
bool
"""
normalised_a = field_a.replace(' ', '_').lower()
normalised_b = field_b.replace(' ', '_').lower()
return normalised_a == normalised_b | Check match between two strings, ignoring case and spaces/underscores.
Parameters
----------
a : str
b : str
Returns
-------
bool | entailment |
def intinlist(lst):
"""test if int in list"""
for item in lst:
try:
item = int(item)
return True
except ValueError:
pass
return False | test if int in list | entailment |
def replaceint(fname, replacewith='%s'):
"""replace int in lst"""
words = fname.split()
for i, word in enumerate(words):
try:
word = int(word)
words[i] = replacewith
except ValueError:
pass
return ' '.join(words) | replace int in lst | entailment |
def cleaniddfield(acomm):
"""make all the keys lower case"""
for key in list(acomm.keys()):
val = acomm[key]
acomm[key.lower()] = val
for key in list(acomm.keys()):
val = acomm[key]
if key != key.lower():
acomm.pop(key)
return acomm | make all the keys lower case | entailment |
def makecsvdiffs(thediffs, dtls, n1, n2):
"""return the csv to be displayed"""
def ishere(val):
if val == None:
return "not here"
else:
return "is here"
rows = []
rows.append(['file1 = %s' % (n1, )])
rows.append(['file2 = %s' % (n2, )])
rows.append('')
rows.append(theheader(n1, n2))
keys = list(thediffs.keys()) # ensures sorting by Name
keys.sort()
# sort the keys in the same order as in the idd
dtlssorter = DtlsSorter(dtls)
keys = sorted(keys, key=dtlssorter.getkey)
for key in keys:
if len(key) == 2:
rw2 = [''] + [ishere(i) for i in thediffs[key]]
else:
rw2 = list(thediffs[key])
rw1 = list(key)
rows.append(rw1 + rw2)
return rows | return the csv to be displayed | entailment |
def idfdiffs(idf1, idf2):
"""return the diffs between the two idfs"""
# for any object type, it is sorted by name
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 zip_longest(n_idfobjs1,
n_idfobjs2):
if idfobj1 == None:
thediffs[(idfobj2.key.upper(),
getobjname(idfobj2))] = (None, idf2.idfname) #(idf1.idfname, None) -> old
break
if idfobj2 == None:
thediffs[(idfobj1.key.upper(),
getobjname(idfobj1))] = (idf1.idfname, None) # (None, idf2.idfname) -> old
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 the diffs between the two idfs | entailment |
def printcsv(csvdiffs):
"""print the csv"""
for row in csvdiffs:
print(','.join([str(cell) for cell in row])) | print the csv | entailment |
def heading2table(soup, table, row):
"""add heading row to table"""
tr = Tag(soup, name="tr")
table.append(tr)
for attr in row:
th = Tag(soup, name="th")
tr.append(th)
th.append(attr) | add heading row to table | entailment |
def row2table(soup, table, row):
"""ad a row to the table"""
tr = Tag(soup, name="tr")
table.append(tr)
for attr in row:
td = Tag(soup, name="td")
tr.append(td)
td.append(attr) | ad a row to the table | entailment |
def printhtml(csvdiffs):
"""print the html"""
soup = BeautifulSoup()
html = Tag(soup, name="html")
para1 = Tag(soup, name="p")
para1.append(csvdiffs[0][0])
para2 = Tag(soup, name="p")
para2.append(csvdiffs[1][0])
table = Tag(soup, name="table")
table.attrs.update(dict(border="1"))
soup.append(html)
html.append(para1)
html.append(para2)
html.append(table)
heading2table(soup, table, csvdiffs[3])
for row in csvdiffs[4:]:
row = [str(cell) for cell in row]
row2table(soup, table, row)
# print soup.prettify()
print(soup) | print the html | entailment |
def extendlist(lst, i, value=''):
"""extend the list so that you have i-th value"""
if i < len(lst):
pass
else:
lst.extend([value, ] * (i - len(lst) + 1)) | extend the list so that you have i-th value | entailment |
def addfunctions(abunch):
"""add functions to epbunch"""
key = abunch.obj[0].upper()
#-----------------
# TODO : alternate strategy to avoid listing the objkeys in snames
# check if epbunch has field "Zone_Name" or "Building_Surface_Name"
# and is in group u'Thermal Zones and Surfaces'
# then it is likely to be a surface.
# of course we need to recode for surfaces that do not have coordinates :-(
# or we can filter those out since they do not have
# the field "Number_of_Vertices"
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
}
abunch.__functions.update(func_dict)
#-----------------
# print(abunch.getfieldidd )
names = [
"CONSTRUCTION",
"MATERIAL",
"MATERIAL:AIRGAP",
"MATERIAL:INFRAREDTRANSPARENT",
"MATERIAL:NOMASS",
"MATERIAL:ROOFVEGETATION",
"WINDOWMATERIAL:BLIND",
"WINDOWMATERIAL:GLAZING",
"WINDOWMATERIAL:GLAZING:REFRACTIONEXTINCTIONMETHOD",
"WINDOWMATERIAL:GAP",
"WINDOWMATERIAL:GAS",
"WINDOWMATERIAL:GASMIXTURE",
"WINDOWMATERIAL:GLAZINGGROUP:THERMOCHROMIC",
"WINDOWMATERIAL:SCREEN",
"WINDOWMATERIAL:SHADE",
"WINDOWMATERIAL:SIMPLEGLAZINGSYSTEM",
]
if key in names:
func_dict = {
'rvalue': fh.rvalue,
'ufactor': fh.ufactor,
'rvalue_ip': fh.rvalue_ip, # quick fix for Santosh. Needs to thought thru
'ufactor_ip': fh.ufactor_ip, # quick fix for Santosh. Needs to thought thru
'heatcapacity': fh.heatcapacity,
}
abunch.__functions.update(func_dict)
names = [
'FAN:CONSTANTVOLUME',
'FAN:VARIABLEVOLUME',
'FAN:ONOFF',
'FAN:ZONEEXHAUST',
'FANPERFORMANCE:NIGHTVENTILATION',
]
if key in names:
func_dict = {
'f_fanpower_bhp': fh.fanpower_bhp,
'f_fanpower_watts': fh.fanpower_watts,
'f_fan_maxcfm': fh.fan_maxcfm,
}
abunch.__functions.update(func_dict)
# =====
# code for references
#-----------------
# add function zonesurfaces
if key == 'ZONE':
func_dict = {'zonesurfaces':fh.zonesurfaces}
abunch.__functions.update(func_dict)
#-----------------
# add function subsurfaces
# going to cheat here a bit
# check if epbunch has field "Zone_Name"
# and is in group u'Thermal Zones and Surfaces'
# then it is likely to be a surface attached to a zone
fields = abunch.fieldnames
try:
group = abunch.getfieldidd('key')['group']
except KeyError as e: # some pytests don't have group
group = None
if group == u'Thermal Zones and Surfaces':
if "Zone_Name" in fields:
func_dict = {'subsurfaces':fh.subsurfaces}
abunch.__functions.update(func_dict)
return abunch | add functions to epbunch | entailment |
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 | get the ranges for this field | entailment |
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""" | throw exception if the out of range | entailment |
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 | get the idd dict for this field
Will return {} if the fieldname does not exist | entailment |
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 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 | entailment |
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) | return True if the field is equal to value | entailment |
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 a list of objects that refer to this object | entailment |
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 | 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 | entailment |
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) | return True if the field == value
Will retain case if get_retaincase == True
for real value will compare to decimal 'places' | entailment |
def getreferingobjs(self, iddgroups=None, fields=None):
"""Get a list of objects that refer to this object"""
return getreferingobjs(self, iddgroups=iddgroups, fields=fields) | Get a list of objects that refer to this object | entailment |
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 irregular tetrahedron | entailment |
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 | volume of a zone defined by two polygon bases | entailment |
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 name2refs dict in the idd_index | entailment |
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 | make the ref2namesdct in the idd_index | entailment |
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 | embed ref2names into commdct | entailment |
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) | Calculation of zone area | entailment |
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 | get the pervious component in the loop | entailment |
def height(poly):
"""height"""
num = len(poly)
hgt = 0.0
for i in range(num):
hgt += (poly[i][2])
return hgt/num | height | entailment |
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 | unit normal | entailment |
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 | Insert an idfobject (bunch) to list1 and its object to list2. | entailment |
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) | Collect data into fixed-length chunks or blocks | entailment |
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 the coordinates of the surface | entailment |
def buildingname(ddtt):
"""return building name"""
idf = ddtt.theidf
building = idf.idfobjects['building'.upper()][0]
return building.Name | return building name | entailment |
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 | massage the version number so it matches the format of install folder | entailment |
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 | find the IDD file of the E+ installation | entailment |
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) | 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. | entailment |
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) | 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 | entailment |
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 | initdict2 | entailment |
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 | create a blank dictionary | entailment |
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 | stuff file data into the blank dictionary | entailment |
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()] | replace the node here with the node from othereplus | entailment |
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 the node here with the node from othereplus
this will potentially have duplicates | entailment |
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()] | add an item to the node.
example: add a new zone to the element 'ZONE' | entailment |
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 | 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 | entailment |
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 | draw a graph without the nodes | entailment |
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 | gather the nodes from the edges | entailment |
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 | make the diagram with the edges | entailment |
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 | return the edges jointing the components of a branch | entailment |
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 | make the edges for the airloop and the plantloop | entailment |
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 | return the edges of the idf file fname | entailment |
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) | 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 | entailment |
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) | remove the blank lines in astr | entailment |
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 | copied from extractidddata below.
It deals with all the types of fnames | entailment |
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 | generate the iddindex | entailment |
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 | insert group info into extracted idd | entailment |
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 | 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) | entailment |
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 | makes a dictionary of object-lists
each item in the dictionary points to a list of tuples
the tuple is (objectname, fieldindex) | entailment |
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 | entailment |
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 | read the idf file | entailment |
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 | get all the objects of objkey.
fieldlists will have a fieldlist for each of those objects.
return the contents of those fields | entailment |
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 | return the plantloopfield list | entailment |
def plantloopfields(data, commdct):
"""get plantloop fields to diagram it"""
fieldlists = plantloopfieldlists(data)
objkey = 'plantloop'.upper()
return extractfields(data, commdct, objkey, fieldlists) | get plantloop fields to diagram it | entailment |
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] | get branches from the branchlist | entailment |
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]] | return the inlet and outlet of a branch | entailment |
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 | docstring for splittermixerfieldlists | entailment |
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 splitter fields to diagram it | entailment |
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) | get mixer fields to diagram it | entailment |
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 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' | entailment |
def objectcount(data, key):
"""return the count of objects of key"""
objkey = key.upper()
return len(data.dt[objkey]) | return the count of objects of key | entailment |
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 | given objkey and fieldname, return its index | entailment |
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 | docstring for fname | entailment |
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 | make the dict adistu_inlets | entailment |
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 | get the version number from the E+ install folder | entailment |
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) | just like the comment in python.
removes any text after the phrase 'com' | entailment |
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) | convert the idf text to a simple text | entailment |
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) | given the idd file or filehandle, return the version handle | entailment |
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 a bunch from the object | entailment |
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 | entailment |
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 | make bunches with data | entailment |
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 the float and interger fields | entailment |
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 field based on field info in IDD | entailment |
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 | convert based on float, integer, and A1, N1 | entailment |
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 | docstring for convertallfields | entailment |
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 the objects | entailment |
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 | add functions to a new bunch/munch object | entailment |
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 | entailment |
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 | read idf file and return bunches | entailment |
def conv_dict(self):
"""dictionary of conversion"""
return dict(integer=self.integer, real=self.real, no_type=self.no_type) | dictionary of conversion | entailment |
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 | Find out if idjobject is mentioned an any object anywhere | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.