text
stringlengths
81
112k
convert and return inputs for E+ in pascal and m3/s def watts2pascal(watts, cfm, fan_tot_eff): """convert and return inputs for E+ in pascal and m3/s""" bhp = watts2bhp(watts) return bhp2pascal(bhp, cfm, fan_tot_eff)
return fan power in bhp given the fan IDF object def fanpower_bhp(ddtt): """return fan power in bhp given the fan IDF object""" from eppy.bunch_subclass import BadEPFieldError # here to prevent circular dependency try: fan_tot_eff = ddtt.Fan_Total_Efficiency # from V+ V8.7.0 onwards except BadEPFieldError as e: fan_tot_eff = ddtt.Fan_Efficiency pascal = float(ddtt.Pressure_Rise) if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize': # str can fail with unicode chars :-( return 'autosize' else: m3s = float(ddtt.Maximum_Flow_Rate) return fan_bhp(fan_tot_eff, pascal, m3s)
return fan power in bhp given the fan IDF object def fanpower_watts(ddtt): """return fan power in bhp given the fan IDF object""" from eppy.bunch_subclass import BadEPFieldError # here to prevent circular dependency try: fan_tot_eff = ddtt.Fan_Total_Efficiency # from V+ V8.7.0 onwards except BadEPFieldError as e: fan_tot_eff = ddtt.Fan_Efficiency pascal = float(ddtt.Pressure_Rise) if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize': # str can fail with unicode chars :-( return 'autosize' else: m3s = float(ddtt.Maximum_Flow_Rate) return fan_watts(fan_tot_eff, pascal, m3s)
return the fan max cfm def fan_maxcfm(ddtt): """return the fan max cfm""" if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize': # str can fail with unicode chars :-( return 'autosize' else: m3s = float(ddtt.Maximum_Flow_Rate) return m3s2cfm(m3s)
Get the install paths for EnergyPlus executable and weather files. We prefer to get the install path from the IDD name but fall back to getting it from the version number for backwards compatibility and to simplify tests. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". iddname : str, optional File path to the IDD. Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_weather : str Full path to the EnergyPlus weather directory. def install_paths(version=None, iddname=None): """Get the install paths for EnergyPlus executable and weather files. We prefer to get the install path from the IDD name but fall back to getting it from the version number for backwards compatibility and to simplify tests. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". iddname : str, optional File path to the IDD. Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_weather : str Full path to the EnergyPlus weather directory. """ try: eplus_exe, eplus_home = paths_from_iddname(iddname) except (AttributeError, TypeError, ValueError): eplus_exe, eplus_home = paths_from_version(version) eplus_weather = os.path.join(eplus_home, 'WeatherData') return eplus_exe, eplus_weather
Get the EnergyPlus install directory and executable path. Parameters ---------- iddname : str, optional File path to the IDD. Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_home : str Full path to the EnergyPlus install directory. Raises ------ AttributeError (TypeError on Windows) If iddname does not have a directory component (e.g. if None). ValueError If eplus_exe is not a file. def paths_from_iddname(iddname): """Get the EnergyPlus install directory and executable path. Parameters ---------- iddname : str, optional File path to the IDD. Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_home : str Full path to the EnergyPlus install directory. Raises ------ AttributeError (TypeError on Windows) If iddname does not have a directory component (e.g. if None). ValueError If eplus_exe is not a file. """ eplus_home = os.path.abspath(os.path.dirname(iddname)) if platform.system() == 'Windows': eplus_exe = os.path.join(eplus_home, 'energyplus.exe') elif platform.system() == "Linux": eplus_exe = os.path.join(eplus_home, 'energyplus') else: eplus_exe = os.path.join(eplus_home, 'energyplus') if not os.path.isfile(eplus_exe): raise ValueError return eplus_exe, eplus_home
Get the EnergyPlus install directory and executable path. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_home : str Full path to the EnergyPlus install directory. def paths_from_version(version): """Get the EnergyPlus install directory and executable path. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_home : str Full path to the EnergyPlus install directory. """ if platform.system() == 'Windows': eplus_home = "C:/EnergyPlusV{version}".format(version=version) eplus_exe = os.path.join(eplus_home, 'energyplus.exe') elif platform.system() == "Linux": eplus_home = "/usr/local/EnergyPlus-{version}".format(version=version) eplus_exe = os.path.join(eplus_home, 'energyplus') else: eplus_home = "/Applications/EnergyPlus-{version}".format(version=version) eplus_exe = os.path.join(eplus_home, 'energyplus') return eplus_exe, eplus_home
Decorator to pass through the documentation from a wrapped function. def wrapped_help_text(wrapped_func): """Decorator to pass through the documentation from a wrapped function. """ def decorator(wrapper_func): """The decorator. Parameters ---------- f : callable The wrapped function. """ wrapper_func.__doc__ = ('This method wraps the following method:\n\n' + pydoc.text.document(wrapped_func)) return wrapper_func return decorator
Wrapper for run() to be used when running IDF5 runs in parallel. Parameters ---------- jobs : iterable A list or generator made up of an IDF5 object and a kwargs dict (see `run_functions.run` for valid keywords). processors : int, optional Number of processors to run on (default: 1). If 0 is passed then the process will run on all CPUs, -1 means one less than all CPUs, etc. def runIDFs(jobs, processors=1): """Wrapper for run() to be used when running IDF5 runs in parallel. Parameters ---------- jobs : iterable A list or generator made up of an IDF5 object and a kwargs dict (see `run_functions.run` for valid keywords). processors : int, optional Number of processors to run on (default: 1). If 0 is passed then the process will run on all CPUs, -1 means one less than all CPUs, etc. """ if processors <= 0: processors = max(1, mp.cpu_count() - processors) shutil.rmtree("multi_runs", ignore_errors=True) os.mkdir("multi_runs") prepared_runs = (prepare_run(run_id, run_data) for run_id, run_data in enumerate(jobs)) try: pool = mp.Pool(processors) pool.map(multirunner, prepared_runs) pool.close() except NameError: # multiprocessing not present so pass the jobs one at a time for job in prepared_runs: multirunner([job]) shutil.rmtree("multi_runs", ignore_errors=True)
Prepare run inputs for one of multiple EnergyPlus runs. :param run_id: An ID number for naming the IDF. :param run_data: Tuple of the IDF and keyword args to pass to EnergyPlus executable. :return: Tuple of the IDF path and EPW, and the keyword args. def prepare_run(run_id, run_data): """Prepare run inputs for one of multiple EnergyPlus runs. :param run_id: An ID number for naming the IDF. :param run_data: Tuple of the IDF and keyword args to pass to EnergyPlus executable. :return: Tuple of the IDF path and EPW, and the keyword args. """ idf, kwargs = run_data epw = idf.epw idf_dir = os.path.join('multi_runs', 'idf_%i' % run_id) os.mkdir(idf_dir) idf_path = os.path.join(idf_dir, 'in.idf') idf.saveas(idf_path) return (idf_path, epw), kwargs
Wrapper around the EnergyPlus command line interface. Parameters ---------- idf : str Full or relative path to the IDF file to be run, or an IDF object. weather : str Full or relative path to the weather file. output_directory : str, optional Full or relative path to an output directory (default: 'run_outputs) annual : bool, optional If True then force annual simulation (default: False) design_day : bool, optional Force design-day-only simulation (default: False) idd : str, optional Input data dictionary (default: Energy+.idd in EnergyPlus directory) epmacro : str, optional Run EPMacro prior to simulation (default: False). expandobjects : bool, optional Run ExpandObjects prior to simulation (default: False) readvars : bool, optional Run ReadVarsESO after simulation (default: False) output_prefix : str, optional Prefix for output file names (default: eplus) output_suffix : str, optional Suffix style for output file names (default: L) L: Legacy (e.g., eplustbl.csv) C: Capital (e.g., eplusTable.csv) D: Dash (e.g., eplus-table.csv) version : bool, optional Display version information (default: False) verbose: str Set verbosity of runtime messages (default: v) v: verbose q: quiet ep_version: str EnergyPlus version, used to find install directory. Required if run() is called with an IDF file path rather than an IDF object. Returns ------- str : status Raises ------ CalledProcessError AttributeError If no ep_version parameter is passed when calling with an IDF file path rather than an IDF object. def run(idf=None, weather=None, output_directory='', annual=False, design_day=False, idd=None, epmacro=False, expandobjects=False, readvars=False, output_prefix=None, output_suffix=None, version=False, verbose='v', ep_version=None): """ Wrapper around the EnergyPlus command line interface. Parameters ---------- idf : str Full or relative path to the IDF file to be run, or an IDF object. weather : str Full or relative path to the weather file. output_directory : str, optional Full or relative path to an output directory (default: 'run_outputs) annual : bool, optional If True then force annual simulation (default: False) design_day : bool, optional Force design-day-only simulation (default: False) idd : str, optional Input data dictionary (default: Energy+.idd in EnergyPlus directory) epmacro : str, optional Run EPMacro prior to simulation (default: False). expandobjects : bool, optional Run ExpandObjects prior to simulation (default: False) readvars : bool, optional Run ReadVarsESO after simulation (default: False) output_prefix : str, optional Prefix for output file names (default: eplus) output_suffix : str, optional Suffix style for output file names (default: L) L: Legacy (e.g., eplustbl.csv) C: Capital (e.g., eplusTable.csv) D: Dash (e.g., eplus-table.csv) version : bool, optional Display version information (default: False) verbose: str Set verbosity of runtime messages (default: v) v: verbose q: quiet ep_version: str EnergyPlus version, used to find install directory. Required if run() is called with an IDF file path rather than an IDF object. Returns ------- str : status Raises ------ CalledProcessError AttributeError If no ep_version parameter is passed when calling with an IDF file path rather than an IDF object. """ args = locals().copy() # get unneeded params out of args ready to pass the rest to energyplus.exe verbose = args.pop('verbose') idf = args.pop('idf') iddname = args.get('idd') if not isinstance(iddname, str): args.pop('idd') try: idf_path = os.path.abspath(idf.idfname) except AttributeError: idf_path = os.path.abspath(idf) ep_version = args.pop('ep_version') # get version from IDF object or by parsing the IDF file for it if not ep_version: try: ep_version = '-'.join(str(x) for x in idf.idd_version[:3]) except AttributeError: raise AttributeError( "The ep_version must be set when passing an IDF path. \ Alternatively, use IDF.run()") eplus_exe_path, eplus_weather_path = install_paths(ep_version, iddname) if version: # just get EnergyPlus version number and return cmd = [eplus_exe_path, '--version'] check_call(cmd) return # convert paths to absolute paths if required if os.path.isfile(args['weather']): args['weather'] = os.path.abspath(args['weather']) else: args['weather'] = os.path.join(eplus_weather_path, args['weather']) output_dir = os.path.abspath(args['output_directory']) args['output_directory'] = output_dir # store the directory we start in cwd = os.getcwd() run_dir = os.path.abspath(tempfile.mkdtemp()) os.chdir(run_dir) # build a list of command line arguments cmd = [eplus_exe_path] for arg in args: if args[arg]: if isinstance(args[arg], bool): args[arg] = '' cmd.extend(['--{}'.format(arg.replace('_', '-'))]) if args[arg] != "": cmd.extend([args[arg]]) cmd.extend([idf_path]) try: if verbose == 'v': print("\r\n" + " ".join(cmd) + "\r\n") check_call(cmd) elif verbose == 'q': check_call(cmd, stdout=open(os.devnull, 'w')) except CalledProcessError: message = parse_error(output_dir) raise EnergyPlusRunError(message) finally: os.chdir(cwd) return 'OK'
Add contents of stderr and eplusout.err and put it in the exception message. :param output_dir: str :return: str def parse_error(output_dir): """Add contents of stderr and eplusout.err and put it in the exception message. :param output_dir: str :return: str """ sys.stderr.seek(0) std_err = sys.stderr.read().decode('utf-8') err_file = os.path.join(output_dir, "eplusout.err") if os.path.isfile(err_file): with open(err_file, "r") as f: ep_err = f.read() else: ep_err = "<File not found>" message = "\r\n{std_err}\r\nContents of EnergyPlus error file at {err_file}\r\n{ep_err}".format(**locals()) return message
R value (W/K) of a construction or material. thickness (m) / conductivity (W/m-K) def rvalue(ddtt): """ R value (W/K) of a construction or material. thickness (m) / conductivity (W/m-K) """ object_type = ddtt.obj[0] if object_type == 'Construction': rvalue = INSIDE_FILM_R + OUTSIDE_FILM_R layers = ddtt.obj[2:] field_idd = ddtt.getfieldidd('Outside_Layer') validobjects = field_idd['validobjects'] for layer in layers: found = False for key in validobjects: try: rvalue += ddtt.theidf.getobject(key, layer).rvalue found = True except AttributeError: pass if not found: raise AttributeError("%s material not found in IDF" % layer) elif object_type == 'Material': thickness = ddtt.obj[ddtt.objls.index('Thickness')] conductivity = ddtt.obj[ddtt.objls.index('Conductivity')] rvalue = thickness / conductivity elif object_type == 'Material:AirGap': rvalue = ddtt.obj[ddtt.objls.index('Thermal_Resistance')] elif object_type == 'Material:InfraredTransparent': rvalue = 0 elif object_type == 'Material:NoMass': rvalue = ddtt.obj[ddtt.objls.index('Thermal_Resistance')] elif object_type == 'Material:RoofVegetation': warnings.warn( "Material:RoofVegetation thermal properties are based on dry soil", UserWarning) thickness = ddtt.obj[ddtt.objls.index('Thickness')] conductivity = ddtt.obj[ddtt.objls.index('Conductivity_of_Dry_Soil')] rvalue = thickness / conductivity else: raise AttributeError("%s rvalue property not implemented" % object_type) return rvalue
Heat capacity (kJ/m2-K) of a construction or material. thickness (m) * density (kg/m3) * specific heat (J/kg-K) * 0.001 def heatcapacity(ddtt): """ Heat capacity (kJ/m2-K) of a construction or material. thickness (m) * density (kg/m3) * specific heat (J/kg-K) * 0.001 """ object_type = ddtt.obj[0] if object_type == 'Construction': heatcapacity = 0 layers = ddtt.obj[2:] field_idd = ddtt.getfieldidd('Outside_Layer') validobjects = field_idd['validobjects'] for layer in layers: found = False for key in validobjects: try: heatcapacity += ddtt.theidf.getobject(key, layer).heatcapacity found = True except AttributeError: pass if not found: raise AttributeError("%s material not found in IDF" % layer) elif object_type == 'Material': thickness = ddtt.obj[ddtt.objls.index('Thickness')] density = ddtt.obj[ddtt.objls.index('Density')] specificheat = ddtt.obj[ddtt.objls.index('Specific_Heat')] heatcapacity = thickness * density * specificheat * 0.001 elif object_type == 'Material:AirGap': heatcapacity = 0 elif object_type == 'Material:InfraredTransparent': heatcapacity = 0 elif object_type == 'Material:NoMass': warnings.warn( "Material:NoMass materials included in heat capacity calculation", UserWarning) heatcapacity = 0 elif object_type == 'Material:RoofVegetation': warnings.warn( "Material:RoofVegetation thermal properties are based on dry soil", UserWarning) thickness = ddtt.obj[ddtt.objls.index('Thickness')] density = ddtt.obj[ddtt.objls.index('Density_of_Dry_Soil')] specificheat = ddtt.obj[ddtt.objls.index('Specific_Heat_of_Dry_Soil')] heatcapacity = thickness * density * specificheat * 0.001 else: raise AttributeError("%s has no heatcapacity property" % object_type) return heatcapacity
Test if two values are equal to a given number of places. This is based on python's unittest so may be covered by Python's license. def almostequal(first, second, places=7, printit=True): """ Test if two values are equal to a given number of places. This is based on python's unittest so may be covered by Python's license. """ if first == second: return True if round(abs(second - first), places) != 0: if printit: print(round(abs(second - first), places)) print("notalmost: %s != %s to %i places" % (first, second, places)) return False else: return True
Make a new object for the given key. Parameters ---------- data : Eplusdata object Data dictionary and list of objects for the entire model. commdct : list of dicts Comments from the IDD file describing each item type in `data`. key : str Object type of the object to add (in ALL_CAPS). Returns ------- list A list of field values for the new object. def newrawobject(data, commdct, key, block=None, defaultvalues=True): """Make a new object for the given key. Parameters ---------- data : Eplusdata object Data dictionary and list of objects for the entire model. commdct : list of dicts Comments from the IDD file describing each item type in `data`. key : str Object type of the object to add (in ALL_CAPS). Returns ------- list A list of field values for the new object. """ dtls = data.dtls key = key.upper() key_i = dtls.index(key) key_comm = commdct[key_i] # set default values if defaultvalues: obj = [comm.get('default', [''])[0] for comm in key_comm] else: obj = ['' for comm in key_comm] if not block: inblock = ['does not start with N'] * len(obj) else: inblock = block[key_i] for i, (f_comm, f_val, f_iddname) in enumerate(zip(key_comm, obj, inblock)): if i == 0: obj[i] = key else: obj[i] = convertafield(f_comm, f_val, f_iddname) obj = poptrailing(obj) # remove the blank items in a repeating field. return obj
add a bunch to model. abunch usually comes from another idf file or it can be used to copy within the idf file def addthisbunch(bunchdt, data, commdct, thisbunch, theidf): """add a bunch to model. abunch usually comes from another idf file or it can be used to copy within the idf file""" key = thisbunch.key.upper() obj = copy.copy(thisbunch.obj) abunch = obj2bunch(data, commdct, obj) bunchdt[key].append(abunch) return abunch
make a new bunch object using the data object def obj2bunch(data, commdct, obj): """make a new bunch object using the data object""" dtls = data.dtls key = obj[0].upper() key_i = dtls.index(key) abunch = makeabunch(commdct, obj, key_i) return abunch
add an object to the eplus model def addobject(bunchdt, data, commdct, key, theidf, aname=None, **kwargs): """add an object to the eplus model""" obj = newrawobject(data, commdct, key) abunch = obj2bunch(data, commdct, obj) if aname: namebunch(abunch, aname) data.dt[key].append(obj) bunchdt[key].append(abunch) for key, value in list(kwargs.items()): abunch[key] = value return abunch
allows you to pass a dict and named args so you can pass ({'a':5, 'b':3}, c=8) and get dict(a=5, b=3, c=8) def getnamedargs(*args, **kwargs): """allows you to pass a dict and named args so you can pass ({'a':5, 'b':3}, c=8) and get dict(a=5, b=3, c=8)""" adict = {} for arg in args: if isinstance(arg, dict): adict.update(arg) adict.update(kwargs) return adict
add an object to the eplus model def addobject1(bunchdt, data, commdct, key, **kwargs): """add an object to the eplus model""" obj = newrawobject(data, commdct, key) abunch = obj2bunch(data, commdct, obj) data.dt[key].append(obj) bunchdt[key].append(abunch) # adict = getnamedargs(*args, **kwargs) for kkey, value in iteritems(kwargs): abunch[kkey] = value return abunch
get the object if you have the key and the name returns a list of objects, in case you have more than one You should not have more than one def getobject(bunchdt, key, name): """get the object if you have the key and the name returns a list of objects, in case you have more than one You should not have more than one""" # TODO : throw exception if more than one object, or return more objects idfobjects = bunchdt[key] if idfobjects: # second item in list is a unique ID unique_id = idfobjects[0].objls[1] theobjs = [idfobj for idfobj in idfobjects if idfobj[unique_id].upper() == name.upper()] try: return theobjs[0] except IndexError: return None
test if the idf object has the field values in kwargs def __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs): """test if the idf object has the field values in kwargs""" for key, value in list(kwargs.items()): if not isfieldvalue( bunchdt, data, commdct, idfobject, key, value, places=places): return False return True
get all the objects of key that matches the fields in **kwargs def getobjects(bunchdt, data, commdct, key, places=7, **kwargs): """get all the objects of key that matches the fields in **kwargs""" idfobjects = bunchdt[key] allobjs = [] for obj in idfobjects: if __objecthasfields( bunchdt, data, commdct, obj, places=places, **kwargs): allobjs.append(obj) return allobjs
from commdct, return the idd of the object key def iddofobject(data, commdct, key): """from commdct, return the idd of the object key""" dtls = data.dtls i = dtls.index(key) return commdct[i]
get the index of the first extensible item def getextensibleindex(bunchdt, data, commdct, key, objname): """get the index of the first extensible item""" theobject = getobject(bunchdt, key, objname) if theobject == None: return None theidd = iddofobject(data, commdct, key) extensible_i = [ i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]] try: extensible_i = extensible_i[0] except IndexError: return theobject
remove the extensible items in the object def removeextensibles(bunchdt, data, commdct, key, objname): """remove the extensible items in the object""" theobject = getobject(bunchdt, key, objname) if theobject == None: return theobject theidd = iddofobject(data, commdct, key) extensible_i = [ i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]] try: extensible_i = extensible_i[0] except IndexError: return theobject while True: try: popped = theobject.obj.pop(extensible_i) except IndexError: break return theobject
get the idd comment for the field def getfieldcomm(bunchdt, data, commdct, idfobject, fieldname): """get the idd comment for the field""" key = idfobject.obj[0].upper() keyi = data.dtls.index(key) fieldi = idfobject.objls.index(fieldname) thiscommdct = commdct[keyi][fieldi] return thiscommdct
test if case has to be retained for that field def is_retaincase(bunchdt, data, commdct, idfobject, fieldname): """test if case has to be retained for that field""" thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobject, fieldname) return 'retaincase' in thiscommdct
test if idfobj.field == value def isfieldvalue(bunchdt, data, commdct, idfobj, fieldname, value, places=7): """test if idfobj.field == value""" # do a quick type check # if type(idfobj[fieldname]) != type(value): # return False # takes care of autocalculate and real # check float thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobj, fieldname) if 'type' in thiscommdct: if thiscommdct['type'][0] in ('real', 'integer'): # test for autocalculate try: if idfobj[fieldname].upper() == 'AUTOCALCULATE': if value.upper() == 'AUTOCALCULATE': return True except AttributeError: pass return almostequal(float(idfobj[fieldname]), float(value), places, False) # check retaincase if is_retaincase(bunchdt, data, commdct, idfobj, fieldname): return idfobj[fieldname] == value else: return idfobj[fieldname].upper() == value.upper()
returns true if the two fields are equal will test for retaincase places is used if the field is float/real def equalfield(bunchdt, data, commdct, idfobj1, idfobj2, fieldname, places=7): """returns true if the two fields are equal will test for retaincase places is used if the field is float/real""" # TODO test if both objects are of same type key1 = idfobj1.obj[0].upper() key2 = idfobj2.obj[0].upper() if key1 != key2: raise NotSameObjectError vee2 = idfobj2[fieldname] return isfieldvalue( bunchdt, data, commdct, idfobj1, fieldname, vee2, places=places)
get the reference names for this object def getrefnames(idf, objname): """get the reference names for this object""" iddinfo = idf.idd_info dtls = idf.model.dtls index = dtls.index(objname) fieldidds = iddinfo[index] for fieldidd in fieldidds: if 'field' in fieldidd: if fieldidd['field'][0].endswith('Name'): if 'reference' in fieldidd: return fieldidd['reference'] else: return []
get all object-list fields for refname return a list: [('OBJKEY', refname, fieldindexlist), ...] where fieldindexlist = index of the field where the object-list = refname def getallobjlists(idf, refname): """get all object-list fields for refname return a list: [('OBJKEY', refname, fieldindexlist), ...] where fieldindexlist = index of the field where the object-list = refname """ dtls = idf.model.dtls objlists = [] for i, fieldidds in enumerate(idf.idd_info): indexlist = [] for j, fieldidd in enumerate(fieldidds): if 'object-list' in fieldidd: if fieldidd['object-list'][0].upper() == refname.upper(): indexlist.append(j) if indexlist != []: objkey = dtls[i] objlists.append((objkey, refname, indexlist)) return objlists
rename all the refrences to this objname def rename(idf, objkey, objname, newname): """rename all the refrences to this objname""" refnames = getrefnames(idf, objkey) for refname in refnames: objlists = getallobjlists(idf, refname) # [('OBJKEY', refname, fieldindexlist), ...] for refname in refnames: # TODO : there seems to be a duplication in this loop. Check. # refname appears in both loops for robjkey, refname, fieldindexlist in objlists: idfobjects = idf.idfobjects[robjkey] for idfobject in idfobjects: for findex in fieldindexlist: # for each field if idfobject[idfobject.objls[findex]] == objname: idfobject[idfobject.objls[findex]] = newname theobject = idf.getobject(objkey, objname) fieldname = [item for item in theobject.objls if item.endswith('Name')][0] theobject[fieldname] = newname return theobject
zone area def zonearea(idf, zonename, debug=False): """zone area""" zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR'] if debug: print(len(floors)) print([floor.area for floor in floors]) # area = sum([floor.area for floor in floors]) if floors != []: area = zonearea_floor(idf, zonename) else: area = zonearea_roofceiling(idf, zonename) return area
zone height = max-min def zone_height_min2max(idf, zonename, debug=False): """zone height = max-min""" zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] surf_xyzs = [eppy.function_helpers.getcoords(s) for s in zone_surfs] surf_xyzs = list(itertools.chain(*surf_xyzs)) surf_zs = [z for x, y, z in surf_xyzs] topz = max(surf_zs) botz = min(surf_zs) height = topz - botz return height
zone height def zoneheight(idf, zonename, debug=False): """zone height""" zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR'] roofs = [s for s in zone_surfs if s.Surface_Type.upper() == 'ROOF'] if floors == [] or roofs == []: height = zone_height_min2max(idf, zonename) else: height = zone_floor2roofheight(idf, zonename) return height
zone floor to roof height def zone_floor2roofheight(idf, zonename, debug=False): """zone floor to roof height""" zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR'] roofs = [s for s in zone_surfs if s.Surface_Type.upper() == 'ROOF'] ceilings = [s for s in zone_surfs if s.Surface_Type.upper() == 'CEILING'] topsurfaces = roofs + ceilings topz = [] for topsurface in topsurfaces: for coord in topsurface.coords: topz.append(coord[-1]) topz = max(topz) botz = [] for floor in floors: for coord in floor.coords: botz.append(coord[-1]) botz = min(botz) height = topz - botz return height
zone volume def zonevolume(idf, zonename): """zone volume""" area = zonearea(idf, zonename) height = zoneheight(idf, zonename) volume = area * height return volume
Set the path to the EnergyPlus IDD for the version of EnergyPlus which is to be used by eppy. Parameters ---------- iddname : str Path to the IDD file. testing : bool Flag to use if running tests since we may want to ignore the `IDDAlreadySetError`. Raises ------ IDDAlreadySetError def setiddname(cls, iddname, testing=False): """ Set the path to the EnergyPlus IDD for the version of EnergyPlus which is to be used by eppy. Parameters ---------- iddname : str Path to the IDD file. testing : bool Flag to use if running tests since we may want to ignore the `IDDAlreadySetError`. Raises ------ IDDAlreadySetError """ if cls.iddname == None: cls.iddname = iddname cls.idd_info = None cls.block = None elif cls.iddname == iddname: pass else: if testing == False: errortxt = "IDD file is set to: %s" % (cls.iddname,) raise IDDAlreadySetError(errortxt)
Set the IDD to be used by eppy. Parameters ---------- iddinfo : list Comments and metadata about fields in the IDD. block : list Field names in the IDD. def setidd(cls, iddinfo, iddindex, block, idd_version): """Set the IDD to be used by eppy. Parameters ---------- iddinfo : list Comments and metadata about fields in the IDD. block : list Field names in the IDD. """ cls.idd_info = iddinfo cls.block = block cls.idd_index = iddindex cls.idd_version = idd_version
Use the current IDD and read an IDF from file. If the IDD has not yet been initialised then this is done first. Parameters ---------- idf_name : str Path to an IDF file. def initread(self, idfname): """ Use the current IDD and read an IDF from file. If the IDD has not yet been initialised then this is done first. Parameters ---------- idf_name : str Path to an IDF file. """ with open(idfname, 'r') as _: # raise nonexistent file error early if idfname doesn't exist pass iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) self.idfname = idfname self.read()
Use the current IDD and read an IDF from text data. If the IDD has not yet been initialised then this is done first. Parameters ---------- idftxt : str Text representing an IDF file. def initreadtxt(self, idftxt): """ Use the current IDD and read an IDF from text data. If the IDD has not yet been initialised then this is done first. Parameters ---------- idftxt : str Text representing an IDF file. """ iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) idfhandle = StringIO(idftxt) self.idfname = idfhandle self.read()
Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data structures: - idfobjects : list - model : list - idd_info : list - idd_index : dict def read(self): """ Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data structures: - idfobjects : list - model : list - idd_info : list - idd_index : dict """ if self.getiddname() == None: errortxt = ("IDD file needed to read the idf file. " "Set it using IDF.setiddname(iddfile)") raise IDDNotSetError(errortxt) readout = idfreader1( self.idfname, self.iddname, self, commdct=self.idd_info, block=self.block) (self.idfobjects, block, self.model, idd_info, idd_index, idd_version) = readout self.__class__.setidd(idd_info, idd_index, block, idd_version)
Use the current IDD and create a new empty IDF. If the IDD has not yet been initialised then this is done first. Parameters ---------- fname : str, optional Path to an IDF. This does not need to be set at this point. def initnew(self, fname): """ Use the current IDD and create a new empty IDF. If the IDD has not yet been initialised then this is done first. Parameters ---------- fname : str, optional Path to an IDF. This does not need to be set at this point. """ iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) idfhandle = StringIO('') self.idfname = idfhandle self.read() if fname: self.idfname = fname
Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interior Ceiling_class', Outside_Layer='LW Concrete', Layer_2='soundmat') Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. aname : str, deprecated This parameter is not used. It is left there for backward compatibility. defaultvalues: boolean default is True. If True default values WILL be set. If False, default values WILL NOT be set **kwargs Keyword arguments in the format `field=value` used to set the value of fields in the IDF object when it is created. Returns ------- EpBunch object def newidfobject(self, key, aname='', defaultvalues=True, **kwargs): """ Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interior Ceiling_class', Outside_Layer='LW Concrete', Layer_2='soundmat') Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. aname : str, deprecated This parameter is not used. It is left there for backward compatibility. defaultvalues: boolean default is True. If True default values WILL be set. If False, default values WILL NOT be set **kwargs Keyword arguments in the format `field=value` used to set the value of fields in the IDF object when it is created. Returns ------- EpBunch object """ obj = newrawobject(self.model, self.idd_info, key, block=self.block, defaultvalues=defaultvalues) abunch = obj2bunch(self.model, self.idd_info, obj) if aname: warnings.warn("The aname parameter should no longer be used.", UserWarning) namebunch(abunch, aname) self.idfobjects[key].append(abunch) for k, v in list(kwargs.items()): abunch[k] = v return abunch
Remove an IDF object from the IDF. Parameters ---------- idfobject : EpBunch object The IDF object to remove. def removeidfobject(self, idfobject): """Remove an IDF object from the IDF. Parameters ---------- idfobject : EpBunch object The IDF object to remove. """ key = idfobject.key.upper() self.idfobjects[key].remove(idfobject)
Add an IDF object to the IDF. Parameters ---------- idfobject : EpBunch object The IDF object to remove. This usually comes from another idf file, or it can be used to copy within this idf file. def copyidfobject(self, idfobject): """Add an IDF object to the IDF. Parameters ---------- idfobject : EpBunch object The IDF object to remove. This usually comes from another idf file, or it can be used to copy within this idf file. """ return addthisbunch(self.idfobjects, self.model, self.idd_info, idfobject, self)
Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- int def getextensibleindex(self, key, name): """ Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- int """ return getextensibleindex( self.idfobjects, self.model, self.idd_info, key, name)
Remove extensible items in the object of key and name. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- EpBunch object def removeextensibles(self, key, name): """ Remove extensible items in the object of key and name. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- EpBunch object """ return removeextensibles( self.idfobjects, self.model, self.idd_info, key, name)
String representation of the IDF. Returns ------- str def idfstr(self): """String representation of the IDF. Returns ------- str """ if self.outputtype == 'standard': astr = '' else: astr = self.model.__repr__() if self.outputtype == 'standard': astr = '' dtls = self.model.dtls for objname in dtls: for obj in self.idfobjects[objname]: astr = astr + obj.__repr__() elif self.outputtype == 'nocomment': return astr elif self.outputtype == 'nocomment1': slist = astr.split('\n') slist = [item.strip() for item in slist] astr = '\n'.join(slist) elif self.outputtype == 'nocomment2': slist = astr.split('\n') slist = [item.strip() for item in slist] slist = [item for item in slist if item != ''] astr = '\n'.join(slist) elif self.outputtype == 'compressed': slist = astr.split('\n') slist = [item.strip() for item in slist] astr = ' '.join(slist) else: raise ValueError("%s is not a valid outputtype" % self.outputtype) return astr
Save the IDF as a text file with the optional filename passed, or with the current idfname of the IDF. Parameters ---------- filename : str, optional Filepath to save the file. If None then use the IDF.idfname parameter. Also accepts a file handle. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. def save(self, filename=None, lineendings='default', encoding='latin-1'): """ Save the IDF as a text file with the optional filename passed, or with the current idfname of the IDF. Parameters ---------- filename : str, optional Filepath to save the file. If None then use the IDF.idfname parameter. Also accepts a file handle. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. """ if filename is None: filename = self.idfname s = self.idfstr() if lineendings == 'default': system = platform.system() s = '!- {} Line endings \n'.format(system) + s slines = s.splitlines() s = os.linesep.join(slines) elif lineendings == 'windows': s = '!- Windows Line endings \n' + s slines = s.splitlines() s = '\r\n'.join(slines) elif lineendings == 'unix': s = '!- Unix Line endings \n' + s slines = s.splitlines() s = '\n'.join(slines) s = s.encode(encoding) try: with open(filename, 'wb') as idf_out: idf_out.write(s) except TypeError: # in the case that filename is a file handle try: filename.write(s) except TypeError: filename.write(s.decode(encoding))
Save the IDF as a text file with the filename passed. Parameters ---------- filename : str Filepath to to set the idfname attribute to and save the file as. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. def saveas(self, filename, lineendings='default', encoding='latin-1'): """ Save the IDF as a text file with the filename passed. Parameters ---------- filename : str Filepath to to set the idfname attribute to and save the file as. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. """ self.idfname = filename self.save(filename, lineendings, encoding)
Save a copy of the file with the filename passed. Parameters ---------- filename : str Filepath to save the file. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. def savecopy(self, filename, lineendings='default', encoding='latin-1'): """Save a copy of the file with the filename passed. Parameters ---------- filename : str Filepath to save the file. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. """ self.save(filename, lineendings, encoding)
Run an IDF file with a given EnergyPlus weather file. This is a wrapper for the EnergyPlus command line interface. Parameters ---------- **kwargs See eppy.runner.functions.run() def run(self, **kwargs): """ Run an IDF file with a given EnergyPlus weather file. This is a wrapper for the EnergyPlus command line interface. Parameters ---------- **kwargs See eppy.runner.functions.run() """ # write the IDF to the current directory self.saveas('in.idf') # if `idd` is not passed explicitly, use the IDF.iddname idd = kwargs.pop('idd', self.iddname) epw = kwargs.pop('weather', self.epw) try: run(self, weather=epw, idd=idd, **kwargs) finally: os.remove('in.idf')
readfile def readfile(filename): """readfile""" fhandle = open(filename, 'rb') data = fhandle.read() try: data = data.decode('ISO-8859-2') except AttributeError: pass fhandle.close() return data
printdict def printdict(adict): """printdict""" dlist = list(adict.keys()) dlist.sort() for i in range(0, len(dlist)): print(dlist[i], adict[dlist[i]])
tabfile2list def tabfile2list(fname): "tabfile2list" #dat = mylib1.readfileasmac(fname) #data = string.strip(dat) data = mylib1.readfileasmac(fname) #data = data[:-2]#remove the last return alist = data.split('\r')#since I read it as a mac file blist = alist[1].split('\t') clist = [] for num in range(0, len(alist)): ilist = alist[num].split('\t') clist = clist+[ilist] cclist = clist[:-1]#the last element is turning out to be empty return cclist
tabstr2list def tabstr2list(data): """tabstr2list""" alist = data.split(os.linesep) blist = alist[1].split('\t') clist = [] for num in range(0, len(alist)): ilist = alist[num].split('\t') clist = clist+[ilist] cclist = clist[:-1] #the last element is turning out to be empty #this is because the string ends with a os.linesep return cclist
list2doe def list2doe(alist): """list2doe""" theequal = '' astr = '' lenj = len(alist) leni = len(alist[0]) for i in range(0, leni-1): for j in range(0, lenj): if j == 0: astr = astr + alist[j][i + 1] + theequal + alist[j][0] + RET else: astr = astr + alist[j][0] + theequal + alist[j][i + 1] + RET astr = astr + RET return astr
tabfile2doefile def tabfile2doefile(tabfile, doefile): """tabfile2doefile""" alist = tabfile2list(tabfile) astr = list2doe(alist) mylib1.write_str2file(doefile, astr)
makedoedict def makedoedict(str1): """makedoedict""" blocklist = str1.split('..') blocklist = blocklist[:-1]#remove empty item after last '..' blockdict = {} belongsdict = {} for num in range(0, len(blocklist)): blocklist[num] = blocklist[num].strip() linelist = blocklist[num].split(os.linesep) aline = linelist[0] alinelist = aline.split('=') name = alinelist[0].strip() aline = linelist[1] alinelist = aline.split('=') belongs = alinelist[-1].strip() theblock = blocklist[num] + os.linesep + '..' + os.linesep + os.linesep #put the '..' back in the block blockdict[name] = theblock belongsdict[name] = belongs return [blockdict, belongsdict]
makedoetree def makedoetree(ddict, bdict): """makedoetree""" dlist = list(ddict.keys()) blist = list(bdict.keys()) dlist.sort() blist.sort() #make space dict doesnot = 'DOES NOT' lst = [] for num in range(0, len(blist)): if bdict[blist[num]] == doesnot:#belong lst = lst + [blist[num]] doedict = {} for num in range(0, len(lst)): #print lst[num] doedict[lst[num]] = {} lv1list = list(doedict.keys()) lv1list.sort() #make wall dict #for each space for i in range(0, len(lv1list)): walllist = [] adict = doedict[lv1list[i]] #loop thru the entire blist dictonary and list the ones that belong into walllist for num in range(0, len(blist)): if bdict[blist[num]] == lv1list[i]: walllist = walllist + [blist[num]] #put walllist into dict for j in range(0, len(walllist)): adict[walllist[j]] = {} #make window dict #for each space for i in range(0, len(lv1list)): adict1 = doedict[lv1list[i]] #for each wall walllist = list(adict1.keys()) walllist.sort() for j in range(0, len(walllist)): windlist = [] adict2 = adict1[walllist[j]] #loop thru the entire blist dictonary and list the ones that belong into windlist for num in range(0, len(blist)): if bdict[blist[num]] == walllist[j]: windlist = windlist + [blist[num]] #put walllist into dict for k in range(0, len(windlist)): adict2[windlist[k]] = {} return doedict
tree2doe def tree2doe(str1): """tree2doe""" retstuff = makedoedict(str1) ddict = makedoetree(retstuff[0], retstuff[1]) ddict = retstuff[0] retstuff[1] = {}# don't need it anymore str1 = ''#just re-using it l1list = list(ddict.keys()) l1list.sort() for i in range(0, len(l1list)): str1 = str1 + ddict[l1list[i]] l2list = list(ddict[l1list[i]].keys()) l2list.sort() for j in range(0, len(l2list)): str1 = str1 + ddict[l2list[j]] l3list = list(ddict[l1list[i]][l2list[j]].keys()) l3list.sort() for k in range(0, len(l3list)): str1 = str1 + ddict[l3list[k]] return str1
mtabstr2doestr def mtabstr2doestr(st1): """mtabstr2doestr""" seperator = '$ ==============' alist = st1.split(seperator) #this removes all the tabs that excel #puts after the seperator and before the next line for num in range(0, len(alist)): alist[num] = alist[num].lstrip() st2 = '' for num in range(0, len(alist)): alist = tabstr2list(alist[num]) st2 = st2 + list2doe(alist) lss = st2.split('..') mylib1.write_str2file('forfinal.txt', st2)#for debugging print(len(lss)) st3 = tree2doe(st2) lsss = st3.split('..') print(len(lsss)) return st3
get the block bounded by start and end doesn't work for multiple blocks def getoneblock(astr, start, end): """get the block bounded by start and end doesn't work for multiple blocks""" alist = astr.split(start) astr = alist[-1] alist = astr.split(end) astr = alist[0] return astr
doestr2tabstr def doestr2tabstr(astr, kword): """doestr2tabstr""" alist = astr.split('..') del astr #strip junk put .. back for num in range(0, len(alist)): alist[num] = alist[num].strip() alist[num] = alist[num] + os.linesep + '..' + os.linesep alist.pop() lblock = [] for num in range(0, len(alist)): linels = alist[num].split(os.linesep) firstline = linels[0] assignls = firstline.split('=') keyword = assignls[-1].strip() if keyword == kword: lblock = lblock + [alist[num]] #print firstline #get all val lval = [] for num in range(0, len(lblock)): block = lblock[num] linel = block.split(os.linesep) lvalin = [] for k in range(0, len(linel)): line = linel[k] assignl = line.split('=') if k == 0: lvalin = lvalin + [assignl[0]] else: if assignl[-1] == '..': assignl[-1] = '.' lvalin = lvalin + [assignl[-1]] lvalin.pop() lval = lval + [lvalin] #get keywords kwordl = [] block = lblock[0] linel = block.split(os.linesep) for k in range(0, len(linel)): line = linel[k] assignl = line.split('=') if k == 0: kword = ' = ' + assignl[1].strip() else: if assignl[0] == '..': assignl[0] = '.' else: assignl[0] = assignl[0] + '=' kword = assignl[0].strip() kwordl = kwordl + [kword] kwordl.pop() astr = '' for num in range(0, len(kwordl)): linest = '' linest = linest + kwordl[num] for k in range(0, len(lval)): linest = linest + '\t' + lval[k][num] astr = astr + linest + os.linesep return astr
in string astr replace all occurences of thefind with thereplace def myreplace(astr, thefind, thereplace): """in string astr replace all occurences of thefind with thereplace""" alist = astr.split(thefind) new_s = alist.split(thereplace) return new_s
Return the slice after at sub in string astr def fsliceafter(astr, sub): """Return the slice after at sub in string astr""" findex = astr.find(sub) return astr[findex + len(sub):]
same as pickle.dump(theobject, fhandle).takes filename as parameter def pickledump(theobject, fname): """same as pickle.dump(theobject, fhandle).takes filename as parameter""" fhandle = open(fname, 'wb') pickle.dump(theobject, fhandle)
writes a string to file def write_str2file(pathname, astr): """writes a string to file""" fname = pathname fhandle = open(fname, 'wb') fhandle.write(astr) fhandle.close()
volume of a irregular tetrahedron def vol_tehrahedron(poly): """volume of a irregular tetrahedron""" a_pnt = np.array(poly[0]) b_pnt = np.array(poly[1]) c_pnt = np.array(poly[2]) d_pnt = np.array(poly[3]) return abs(np.dot( (a_pnt-d_pnt), np.cross((b_pnt-d_pnt), (c_pnt-d_pnt))) / 6)
volume of a zone defined by two polygon bases def vol_zone(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) 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-1): 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) tehrahedron = [c_point, poly1[num-1], poly2[num-1], poly2[0]] vol_therah += vol_tehrahedron(tehrahedron) tehrahedron = [c_point, poly1[num-1], poly1[0], poly2[0]] vol_therah += vol_tehrahedron(tehrahedron) return vol_therah
open a new idf file easy way to open a new idf file for particular version. Works only id Energyplus of that version is installed. Parameters ---------- version: string version of the new file you want to create. Will work only if this version of Energyplus has been installed. Returns ------- idf file of type eppy.modelmake.IDF def newidf(version=None): """open a new idf file easy way to open a new idf file for particular version. Works only id Energyplus of that version is installed. Parameters ---------- version: string version of the new file you want to create. Will work only if this version of Energyplus has been installed. Returns ------- idf file of type eppy.modelmake.IDF """ # noqa: E501 if not version: version = "8.9" import eppy.easyopen as easyopen idfstring = " Version,{};".format(str(version)) fhandle = StringIO(idfstring) return easyopen.easyopen(fhandle)
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 openidf(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. """ import eppy.easyopen as easyopen return easyopen.easyopen(fname, idd=idd, epw=epw)
return an wall:interzone object if the bsd (buildingsurface:detailed) is an interaone wall def wallinterzone(idf, bsdobject, deletebsd=True, setto000=False): """return an wall:interzone object if the bsd (buildingsurface:detailed) is an interaone wall""" # ('WALL:INTERZONE', Wall, Surface OR Zone OR OtherSideCoefficients) # test if it is an exterior wall if bsdobject.Surface_Type.upper() == 'WALL': # Surface_Type == wall if bsdobject.Outside_Boundary_Condition.upper() in ('SURFACE', 'ZONE', 'OtherSideCoefficients'.upper()): simpleobject = idf.newidfobject('WALL:INTERZONE') simpleobject.Name = bsdobject.Name simpleobject.Construction_Name = bsdobject.Construction_Name simpleobject.Zone_Name = bsdobject.Zone_Name obco = 'Outside_Boundary_Condition_Object' simpleobject[obco] = bsdobject[obco] simpleobject.Azimuth_Angle = bsdobject.azimuth simpleobject.Tilt_Angle = bsdobject.tilt surforigin = bsdorigin(bsdobject, setto000=setto000) simpleobject.Starting_X_Coordinate = surforigin[0] simpleobject.Starting_Y_Coordinate = surforigin[1] simpleobject.Starting_Z_Coordinate = surforigin[2] simpleobject.Length = bsdobject.width simpleobject.Height = bsdobject.height if deletebsd: idf.removeidfobject(bsdobject) return simpleobject return None
return an door object if the fsd (fenestrationsurface:detailed) is a door def door(idf, fsdobject, deletebsd=True, setto000=False): """return an door object if the fsd (fenestrationsurface:detailed) is a door""" # ('DOOR', Door, None) # test if it is aroof if fsdobject.Surface_Type.upper() == 'DOOR': # Surface_Type == w simpleobject = idf.newidfobject('DOOR') simpleobject.Name = fsdobject.Name simpleobject.Construction_Name = fsdobject.Construction_Name simpleobject.Building_Surface_Name = fsdobject.Building_Surface_Name simpleobject.Multiplier = fsdobject.Multiplier surforigin = fsdorigin(fsdobject, setto000=setto000) simpleobject.Starting_X_Coordinate = surforigin[0] simpleobject.Starting_Z_Coordinate = surforigin[1] simpleobject.Length = fsdobject.width simpleobject.Height = fsdobject.height if deletebsd: idf.removeidfobject(fsdobject) return simpleobject return None
convert a bsd (buildingsurface:detailed) into a simple surface def simplesurface(idf, bsd, deletebsd=True, setto000=False): """convert a bsd (buildingsurface:detailed) into a simple surface""" funcs = (wallexterior, walladiabatic, wallunderground, wallinterzone, roof, ceilingadiabatic, ceilinginterzone, floorgroundcontact, flooradiabatic, floorinterzone,) for func in funcs: surface = func(idf, bsd, deletebsd=deletebsd, setto000=setto000) if surface: return surface return None
convert a bsd (fenestrationsurface:detailed) into a simple fenestrations 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 the <br/> in <td> block into line ending (EOL = \n) 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
test if the table has only strings in the cells 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
convert a table to a list of lists - a 2D matrix 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 Converts numbers to float 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
return a list of [(title, table), .....] title = previous item with a <b> tag table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..] 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
checks if soup_obj is really a soup object or just a string If it has a name it is a soup object 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
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 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
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)) 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
return only legal chars def onlylegalchar(name): """return only legal chars""" legalchar = ascii_letters + digits + ' ' return ''.join([s for s in name[:] if s in legalchar])
Check match between two strings, ignoring case and spaces/underscores. Parameters ---------- a : str b : str Returns ------- bool 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
test if int in list def intinlist(lst): """test if int in list""" for item in lst: try: item = int(item) return True except ValueError: pass return False
replace int in lst 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)
make all the keys lower case 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
return the csv to be displayed 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 diffs between the two idfs 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
print the csv def printcsv(csvdiffs): """print the csv""" for row in csvdiffs: print(','.join([str(cell) for cell in row]))
add heading row to table 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)
ad a row to the table 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)
print the html 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)
extend the list so that you have i-th value 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))
add functions to epbunch 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