Search is not available for this dataset
text
stringlengths
75
104k
def create(self, name, fields): """Create a new vdata, setting its name and allocating its fields. Args:: name Name to assign to the vdata fields Sequence of field definitions. Each field definition is a sequence with the following elements in order...
def find(self, vName): """Get the reference number of a vdata given its name. The vdata can then be opened (attached) by passing this reference number to the attach() method. Args:: vName Name of the vdata for which the reference number is needed. vdatas...
def next(self, vRef): """Get the reference number of the vdata following a given vdata. Args:: vRef Reference number of the vdata preceding the one we require. Set to -1 to get the first vdata in the HDF file. Knowing its reference number, ...
def vdatainfo(self, listAttr=0): """Return info about all the file vdatas. Args:: listAttr Set to 0 to ignore vdatas used to store attribute values, 1 to list them (see the VD._isattr readonly attribute) Returns:: List of vdata ...
def storedata(self, fieldName, values, data_type, vName, vClass): """Create and initialize a single field vdata, returning the vdata reference number. Args:: fieldName Name of the single field in the vadata to create values Sequence of values to store in the field;. ...
def fdefine(self, name, type, order): """Define a field. To initialize a newly created vdata with fields created with fdefine(), assign a tuple of field names to the _fields attribute or call the setfields() method. Args:: name field name type field data typ...
def setfields(self, *fldNames): """Define the name and order of the fields to access with the read() and write() methods. Args:: fldNames variable length argument specifying one or more vdata field names Returns:: None C library equiv...
def field(self, name_index): """Get a VDField instance representing a field of the vdata. Args:: name_index name or index number of the field Returns:: VDfield instance representing the field C library equivalent : no equivalent ...
def seek(self, recIndex): """Seek to the beginning of the record identified by its record index. A succeeding read will load this record in memory. Args:: recIndex index of the record in the vdata; numbering starts at 0. Legal values range from 0 ...
def seekend(self): """Set the current record position past the last vdata record. Subsequent write() calls will append records to the vdata. Args:: no argument Returns:: index of the last record plus 1 C library equivalent : no equivalent ...
def read(self, nRec=1): """Retrieve the values of a number of records, starting at the current record position. The current record position is advanced by the number of records read. Current position is 0 after "opening" the vdata with the attach() method. Args:: nRec...
def write(self, values): """Write records to the vdata. Writing starts at the current record position, which is advanced by the number of records written. Args:: values: 2-level sequence. First level is a sequence of records. A second level gives the sequenc...
def inquire(self): """Retrieve info about the vdata. Args:: no argument Returns:: 5-element tuple with the following elements: -number of records in the vdata -interlace mode -list of vdata field names -size in bytes of the ...
def fieldinfo(self): """Retrieve info about all vdata fields. Args:: no argument Returns:: list where each element describes a field of the vdata; each field is described by an 7-element tuple containing the following elements: - field name ...
def sizeof(self, fields): """Retrieve the size in bytes of the given fields. Args:: fields sequence of field names to query Returns:: total size of the fields in bytes C library equivalent : VSsizeof """ ...
def fexist(self, fields): """Check if a vdata contains a given set of fields. Args:: fields sequence of field names whose presence in the vdata must be checked Returns:: true (1) if the given fields are present false (0) otherwise ...
def find(self, name): """Search the field for a given attribute. Args:: name attribute name Returns:: if found, VDAttr instance describing the attribute None otherwise C library equivalent : VSfindattr ...
def set(self, data_type, values): """Set the attribute value. Args:: data_type : attribute data type (see constants HC.xxx) values : attribute value(s); specify a list to create a multi-valued attribute; a string valued att...
def info(self): """Retrieve info about the attribute. Args:: no argument Returns:: 4-element tuple with the following components: -attribute name -attribute data type (one of HC.xxx constants) -attribute order (number of values) ...
def getlibversion(): """Get the library version info. Args: no argument Returns: 4-element tuple with the following components: -major version number (int) -minor version number (int) -complete library version number (int) -additional information (string) C ...
def getfileversion(self): """Get file version info. Args: no argument Returns: 4-element tuple with the following components: -major version number (int) -minor version number (int) -complete library version number (int) -addit...
def txtToHDF(txtFile, hdfFile, varName, attr): """Inputs: txtFile = name of .txt file (passed as string) hdfFile = name of .hdf file (passed as string) varName = name of dataset to be added (passed as string) attr = dataset attributes (passed as dictionary) txtFile indicates a da...
def colorize(lead, num, color): """ Print 'lead' = 'num' in 'color' """ if num != 0 and ANSIBLE_COLOR and color is not None: return "%s%s%-15s" % (stringc(lead, color), stringc("=", color), stringc(str(num), color)) else: return "%s=%-4s" % (lead, str(num))
def get_fields(Model, parent_field="", model_stack=None, stack_limit=2, excludes=['permissions', 'comment', 'content_type']): """ Given a Model, return a list of lists of strings with important stuff: ... ['test_user__user__customuser', 'custo...
def give_model_field(full_field, Model): """ Given a field_name and Model: "test_user__unique_id", <AchievedGoal> Returns "test_user__unique_id", "id", <Model>, <ModelField> """ field_data = get_fields(Model, '', []) for full_key, name, _Model, _ModelField in field_data: if full_k...
def timeline(self, request, drip_id, into_past, into_future): """ Return a list of people who should get emails. """ from django.shortcuts import render, get_object_or_404 drip = get_object_or_404(Drip, id=drip_id) shifted_drips = [] seen_users = set() f...
def walk(self, into_past=0, into_future=0): """ Walk over a date range and create new instances of self with new ranges. """ walked_range = [] for shift in range(-into_past, into_future): kwargs = dict(drip_model=self.drip_model, name=self.na...
def apply_queryset_rules(self, qs): """ First collect all filter/exclude kwargs and apply any annotations. Then apply all filters at once, and all excludes at once. """ clauses = { 'filter': [], 'exclude': []} for rule in self.drip_model.queryset_...
def run(self): """ Get the queryset, prune sent people, and send it. """ if not self.drip_model.enabled: return None self.prune() count = self.send() return count
def prune(self): """ Do an exclude for all Users who have a SentDrip already. """ target_user_ids = self.get_queryset().values_list('id', flat=True) exclude_user_ids = SentDrip.objects.filter(date__lt=conditional_now(), drip=self...
def send(self): """ Send the message to each user on the queryset. Create SentDrip for each user that gets a message. Returns count of created SentDrips. """ if not self.from_email: self.from_email = getattr(settings, 'DRIP_FROM_EMAIL', settings.DEFAULT_FRO...
def angle(self, other): """Return the angle to the vector other""" return math.acos(self.dot(other) / (self.magnitude() * other.magnitude()))
def project(self, other): """Return one vector projected on the vector other""" n = other.normalized() return self.dot(n) * n
def flip(self): """Flip vector""" # added by Mostapha Sadeghipour self.x = -self.x self.y = -self.y self.z = -self.z return self
def rotate_around(self, axis, theta): """Return the vector rotated around axis through angle theta. Right hand rule applies. """ # Adapted from equations published by Glenn Murray. # http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html x, y,...
def to_ip(self, values, from_unit): """Return values in IP and the units to which the values have been converted.""" if from_unit == 'Btu/h-ft2-F': return values, from_unit else: return self.to_unit(values, 'Btu/h-ft2-F', from_unit), 'Btu/h-ft2-F'
def to_si(self, values, from_unit): """Return values in SI and the units to which the values have been converted.""" if from_unit == 'W/m2-K': return values, from_unit else: return self.to_unit(values, 'W/m2-K', from_unit), 'W/m2-K'
def preparedir(target_dir, remove_content=True): """Prepare a folder for analysis. This method creates the folder if it is not created, and removes the file in the folder if the folder already existed. """ if os.path.isdir(target_dir): if remove_content: nukedir(target_dir, Fals...
def nukedir(target_dir, rmdir=False): """Delete all the files inside target_dir. Usage: nukedir("c:/ladybug/libs", True) """ d = os.path.normpath(target_dir) if not os.path.isdir(d): return files = os.listdir(d) for f in files: if f == '.' or f == '..': ...
def write_to_file_by_name(folder, fname, data, mkdir=False): """Write a string of data to file by filename and folder. Args: folder: Target folder (e.g. c:/ladybug). fname: File name (e.g. testPts.pts). data: Any data as string. mkdir: Set to True to create the directory if does...
def write_to_file(file_path, data, mkdir=False): """Write a string of data to file. Args: file_path: Full path for a valid file path (e.g. c:/ladybug/testPts.pts) data: Any data as string mkdir: Set to True to create the directory if doesn't exist (Default: False) """ folder, fn...
def copy_files_to_folder(files, target_folder, overwrite=True): """Copy a list of files to a new target folder. Returns: A list of fullpath of the new files. """ if not files: return [] for f in files: target = os.path.join(target_folder, os.path.split(f)[-1]) if t...
def bat_to_sh(file_path): """Convert honeybee .bat file to .sh file. WARNING: This is a very simple function and doesn't handle any edge cases. """ sh_file = file_path[:-4] + '.sh' with open(file_path, 'rb') as inf, open(sh_file, 'wb') as outf: outf.write('#!/usr/bin/env bash\n\n') ...
def _download_py2(link, path, __hdr__): """Download a file from a link in Python 2.""" try: req = urllib2.Request(link, headers=__hdr__) u = urllib2.urlopen(req) except Exception as e: raise Exception(' Download failed with the error:\n{}'.format(e)) with open(path, 'wb') as out...
def _download_py3(link, path, __hdr__): """Download a file from a link in Python 3.""" try: req = urllib.request.Request(link, headers=__hdr__) u = urllib.request.urlopen(req) except Exception as e: raise Exception(' Download failed with the error:\n{}'.format(e)) with open(path...
def download_file_by_name(url, target_folder, file_name, mkdir=False): """Download a file to a directory. Args: url: A string to a valid URL. target_folder: Target folder for download (e.g. c:/ladybug) file_name: File name (e.g. testPts.zip). mkdir: Set to True to create the dir...
def download_file(url, file_path, mkdir=False): """Write a string of data to file. Args: url: A string to a valid URL. file_path: Full path to intended download location (e.g. c:/ladybug/testPts.pts) mkdir: Set to True to create the directory if doesn't exist (Default: False) """ ...
def unzip_file(source_file, dest_dir=None, mkdir=False): """Unzip a compressed file. Args: source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip) dest_dir: Target folder to extract to (e.g. c:/ladybug). Default is set to the same directory as the source file...
def csv_to_matrix(csv_file_path): """Load a CSV file into a Python matrix of strings. Args: csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) """ mtx = [] with open(csv_file_path) as csv_data_file: for row in csv_data_file: mtx.append(row.split(',')...
def csv_to_num_matrix(csv_file_path): """Load a CSV file consisting only of numbers into a Python matrix of floats. Args: csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) """ mtx = [] with open(csv_file_path) as csv_data_file: for row in csv_data_file: ...
def from_json(cls, data): """ Create STAT from json dictionary. Args: data: { 'location': {} , // ladybug location schema 'ashrae_climate_zone': str, 'koppen_climate_zone': str, 'extreme_cold_week': {}, // ladybug analy...
def _import_data(self): """Import data from a stat file. """ # set default state to ironpython for very old ironpython (2.7.0) iron_python = True try: iron_python = True if platform.python_implementation() == 'IronPython' \ else False except Va...
def annual_heating_design_day_996(self): """A design day object representing the annual 99.6% heating design day.""" if bool(self._winter_des_day_dict) is True: return DesignDay.from_ashrae_dict_heating( self._winter_des_day_dict, self.location, False, self._s...
def annual_heating_design_day_990(self): """A design day object representing the annual 99.0% heating design day.""" if bool(self._winter_des_day_dict) is True: return DesignDay.from_ashrae_dict_heating( self._winter_des_day_dict, self.location, True, self._st...
def annual_cooling_design_day_004(self): """A design day object representing the annual 0.4% cooling design day.""" if bool(self._summer_des_day_dict) is True: tau = None month_num = int(self._summer_des_day_dict['Month']) if self._monthly_tau_beam != [] and self._mon...
def monthly_cooling_design_days_050(self): """A list of 12 objects representing monthly 5.0% cooling design days.""" if self.monthly_found is False or self._monthly_db_50 == [] \ or self._monthly_wb_50 == []: return [] else: db_conds = [DryBulbCond...
def monthly_cooling_design_days_100(self): """A list of 12 objects representing monthly 10.0% cooling design days.""" if self.monthly_found is False or self._monthly_db_100 == [] \ or self._monthly_wb_100 == []: return [] else: db_conds = [DryBulbC...
def monthly_cooling_design_days_020(self): """A list of 12 objects representing monthly 2.0% cooling design days.""" if self.monthly_found is False or self._monthly_db_20 == [] \ or self._monthly_wb_20 == []: return [] else: db_conds = [DryBulbCond...
def monthly_cooling_design_days_004(self): """A list of 12 objects representing monthly 0.4% cooling design days.""" if self.monthly_found is False or self._monthly_db_04 == [] \ or self._monthly_wb_04 == []: return [] else: db_conds = [DryBulbCond...
def monthly_wind_conditions(self): """A list of 12 monthly wind conditions that are used on the design days.""" return [WindCondition(x, y) for x, y in zip( self._monthly_wind, self.monthly_wind_dirs)]
def monthly_wind_dirs(self): """A list of prevailing wind directions for each month.""" mwd = zip(*self._monthly_wind_dirs) return [self._wind_dirs[mon.index(max(mon))] for mon in mwd]
def monthly_clear_sky_conditions(self): """A list of 12 monthly clear sky conditions that are used on the design days.""" if self._monthly_tau_diffuse is [] or self._monthly_tau_beam is []: return [OriginalClearSkyCondition(i, 21) for i in xrange(1, 13)] return [RevisedClearSkyCondit...
def to_json(self): """Convert the STAT object to a dictionary.""" def jsonify_dict(base_dict): new_dict = {} for key, val in base_dict.items(): if isinstance(val, list): new_dict[key] = [v.to_json() for v in val] else: ...
def from_json(cls, data): """Create a data type from a dictionary. Args: data: Data as a dictionary. { "name": data type name of the data type as a string "data_type": the class name of the data type as a string "ba...
def is_unit_acceptable(self, unit, raise_exception=True): """Check if a certain unit is acceptable for the data type. Args: unit: A text string representing the abbreviated unit. raise_exception: Set to True to raise an exception if not acceptable. """ _is_accept...
def is_in_range(self, values, unit=None, raise_exception=True): """Check if a list of values is within physically/mathematically possible range. Args: values: A list of values. unit: The unit of the values. If not specified, the default metric unit will be assum...
def _is_numeric(self, values): """Check to be sure values are numbers before doing numerical operations.""" if len(values) > 0: assert isinstance(values[0], (float, int)), \ "values must be numbers to perform math operations. Got {}".format( type(values[0]...
def _to_unit_base(self, base_unit, values, unit, from_unit): """Return values in a given unit given the input from_unit.""" self._is_numeric(values) namespace = {'self': self, 'values': values} if not from_unit == base_unit: self.is_unit_acceptable(from_unit, True) ...
def name(self): """The data type name.""" if self._name is None: return re.sub(r"(?<=\w)([A-Z])", r" \1", self.__class__.__name__) else: return self._name
def from_json(cls, data): """Create a header from a dictionary. Args: data: { "data_type": {}, //Type of data (e.g. Temperature) "unit": string, "analysis_period": {} // A Ladybug AnalysisPeriod "metadata": {}, // A dictionary ...
def duplicate(self): """Return a copy of the header.""" a_per = self.analysis_period.duplicate() if self.analysis_period else None return self.__class__(self.data_type, self.unit, a_per, deepcopy(self.metadata))
def to_tuple(self): """Return Ladybug header as a list.""" return ( self.data_type, self.unit, self.analysis_period, self.metadata )
def to_json(self): """Return a header as a dictionary.""" a_per = self.analysis_period.to_json() if self.analysis_period else None return {'data_type': self.data_type.to_json(), 'unit': self.unit, 'analysis_period': a_per, 'metadata': self.metadata...
def ashrae_clear_sky(altitudes, month, sky_clearness=1): """Calculate solar flux for an original ASHRAE Clear Sky Args: altitudes: A list of solar altitudes in degrees month: An integer (1-12) indicating the month the altitudes belong to sky_clearness: A factor that will be multiplied b...
def ashrae_revised_clear_sky(altitudes, tb, td, use_2017_model=False): """Calculate solar flux for an ASHRAE Revised Clear Sky ("Tau Model"). By default, this function returns clear sky values following the methods originally published in the ASHRAE 2009 HOF. Args: altitudes: A list of solar al...
def zhang_huang_solar(alt, cloud_cover, relative_humidity, dry_bulb_present, dry_bulb_t3_hrs, wind_speed, irr_0=1355): """Calculate global horizontal solar irradiance using the Zhang-Huang model. Note: [1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typ...
def zhang_huang_solar_split(altitudes, doys, cloud_cover, relative_humidity, dry_bulb_present, dry_bulb_t3_hrs, wind_speed, atm_pressure, use_disc=False): """Calculate direct and diffuse solar irradiance using the Zhang-Huang model. By default, this funct...
def calc_horizontal_infrared(sky_cover, dry_bulb, dew_point): """Calculate horizontal infrared radiation intensity. See EnergyPlus Enrineering Reference for more information: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference/climate-calculations.html#sky-radiation-modeling Note: ...
def dirint(ghi, altitudes, doys, pressures, use_delta_kt_prime=True, temp_dew=None, min_sin_altitude=0.065, min_altitude=3): """ Determine DNI from GHI using the DIRINT modification of the DISC model. Implements the modified DISC model known as "DIRINT" introduced in [1]. DIRINT predicts...
def _dirint_bins(ktp, alt, w, dktp): """ Determine the bins for the DIRINT coefficients. Args: ktp : Altitude-independent clearness index alt : Solar altitude angle w : precipitable water estimated from surface dew-point temperature dktp : stability index Returns: ...
def disc(ghi, altitude, doy, pressure=101325, min_sin_altitude=0.065, min_altitude=3, max_airmass=12): """ Estimate Direct Normal Irradiance from Global Horizontal Irradiance using the DISC model. The DISC algorithm converts global horizontal irradiance to direct normal irradiance through ...
def _disc_kn(clearness_index, airmass, max_airmass=12): """ Calculate Kn for `disc` Args: clearness_index : numeric airmass : numeric max_airmass : float airmass > max_airmass is set to max_airmass before being used in calculating Kn. Returns: Kn...
def get_extra_radiation(doy, solar_constant=1366.1): """ Determine extraterrestrial radiation from day of year (using the spencer method). Note: [1] M. Reno, C. Hansen, and J. Stein, "Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis", Sandia National Labora...
def clearness_index(ghi, altitude, extra_radiation, min_sin_altitude=0.065, max_clearness_index=2.0): """ Calculate the clearness index. The clearness index is the ratio of global to extraterrestrial irradiance on a horizontal plane. Note: [1] Maxwell, E. L., "A Quasi-P...
def clearness_index_zenith_independent(clearness_index, airmass, max_clearness_index=2.0): """ Calculate the zenith angle independent clearness index. Note: [1] Perez, R., P. Ineichen, E. Maxwell, R. Seals and A. Zelenka, (1992). "Dynamic Global-to-Dir...
def get_relative_airmass(altitude, model='kastenyoung1989'): """ Gives the relative (not pressure-corrected) airmass. Gives the airmass at sea-level when given a sun altitude angle (in degrees). The ``model`` variable allows selection of different airmass models (described below). If ``model`` is n...
def _get_dirint_coeffs(): """ Here be a large multi-dimensional matrix of dirint coefficients. Returns: Array with shape ``(6, 6, 7, 5)``. Ordering is ``[kt_prime_bin, zenith_bin, delta_kt_prime_bin, w_bin]`` """ coeffs = [[0 for i in range(6)] for j in range(6)] coeffs[0][0] =...
def set_domain(self, values): """Set domain of the colors based on min and max of a list of values.""" _flattenedList = sorted(flatten(values)) self.domain = tuple(_flattenedList[0] if d == 'min' else d for d in self.domain) self.domain = tuple(_flattenedList[-1] if d == 'max' else d for...
def calculate_colors(self, values): """Return a list (or list of lists) of colors based on input values.""" # set domain if it is not set _flattenedList = list(flatten(values)) if not self.is_domain_set: self.set_domain(_flattenedList) _flattenedColors = range(len(_f...
def from_json(cls, data): """Create a Data Collection from a dictionary. Args: { "header": A Ladybug Header, "values": An array of values, "datetimes": An array of datetimes, "validated_a_period": Boolean for whether header ana...
def timestep_text(self): """Return a text string representing the timestep of the collection.""" if self.header.analysis_period.timestep == 1: return 'Hourly' else: return '{} Minute'.format(int(60 / self.header.analysis_period.timestep))
def moys_dict(self): """Return a dictionary of this collection's values where the keys are the moys. This is useful for aligning the values with another list of datetimes. """ moy_dict = {} for val, dt in zip(self.values, self.datetimes): moy_dict[dt.moy] = val ...
def filter_by_analysis_period(self, analysis_period): """ Filter a Data Collection based on an analysis period. Args: analysis period: A Ladybug analysis period Return: A new Data Collection with filtered data """ self._check_analysis_period(analy...
def filter_by_hoys(self, hoys): """Filter the Data Collection based on an analysis period. Args: hoys: A List of hours of the year 0..8759 Return: A new Data Collection with filtered data """ _moys = tuple(int(hour * 60) for hour in hoys) return s...
def filter_by_moys(self, moys): """Filter the Data Collection based on a list of minutes of the year. Args: moys: A List of minutes of the year [0..8759 * 60] Return: A new Data Collection with filtered data """ _filt_values, _filt_datetimes = self._filte...
def group_by_day(self): """Return a dictionary of this collection's values grouped by each day of year. Key values are between 1-365. """ data_by_day = OrderedDict() for d in xrange(1, 366): data_by_day[d] = [] for v, dt in zip(self._values, self.datetimes): ...
def group_by_month(self): """Return a dictionary of this collection's values grouped by each month. Key values are between 1-12. """ data_by_month = OrderedDict() for d in xrange(1, 13): data_by_month[d] = [] for v, dt in zip(self._values, self.datetimes): ...
def group_by_month_per_hour(self): """Return a dictionary of this collection's values grouped by each month per hour. Key values are tuples of 2 integers: The first represents the month of the year between 1-12. The first represents the hour of the day between 0-24. (eg. (12, 23...
def interpolate_holes(self): """Linearly interpolate over holes in this collection to make it continuous. Returns: continuous_collection: A HourlyContinuousCollection with the same data as this collection but with missing data filled by means of a linear inte...
def cull_to_timestep(self, timestep=1): """Get a collection with only datetimes that fit a timestep.""" valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys() assert timestep in valid_s, \ 'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s) new_ap, new...