id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
4,600
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection.interpolate_holes
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 interpolation. """ # validate analysis_period and use the resulting period to generate datetimes assert self.validated_a_period is True, 'validated_a_period property must be' \ ' True to use interpolate_holes(). Run validate_analysis_period().' mins_per_step = int(60 / self.header.analysis_period.timestep) new_datetimes = self.header.analysis_period.datetimes new_values = [] # if the first steps are a hole, duplicate the first value. i = 0 if new_datetimes[0] != self.datetimes[0]: n_steps = int((self.datetimes[0].moy - new_datetimes[0].moy) / mins_per_step) new_values.extend([self._values[0]] * n_steps) i = n_steps - 1 # go through the values interpolating any holes. for j in xrange(len(self._values)): if new_datetimes[i] == self.datetimes[j]: # there is no hole. new_values.append(self._values[j]) i += 1 else: # there is a hole between this step and the previous step. n_steps = int((self.datetimes[j].moy - new_datetimes[i].moy) / mins_per_step) intp_vals = self._xxrange(self._values[j - 1], self._values[j], n_steps) new_values.extend(list(intp_vals)[1:] + [self._values[j]]) i += n_steps # if the last steps are a hole duplicate the last value. if len(new_values) != len(new_datetimes): n_steps = len(new_datetimes) - len(new_values) new_values.extend([self._values[-1]] * n_steps) # build the new continuous data collection. return HourlyContinuousCollection(self.header.duplicate(), new_values)
python
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 interpolation. """ # validate analysis_period and use the resulting period to generate datetimes assert self.validated_a_period is True, 'validated_a_period property must be' \ ' True to use interpolate_holes(). Run validate_analysis_period().' mins_per_step = int(60 / self.header.analysis_period.timestep) new_datetimes = self.header.analysis_period.datetimes new_values = [] # if the first steps are a hole, duplicate the first value. i = 0 if new_datetimes[0] != self.datetimes[0]: n_steps = int((self.datetimes[0].moy - new_datetimes[0].moy) / mins_per_step) new_values.extend([self._values[0]] * n_steps) i = n_steps - 1 # go through the values interpolating any holes. for j in xrange(len(self._values)): if new_datetimes[i] == self.datetimes[j]: # there is no hole. new_values.append(self._values[j]) i += 1 else: # there is a hole between this step and the previous step. n_steps = int((self.datetimes[j].moy - new_datetimes[i].moy) / mins_per_step) intp_vals = self._xxrange(self._values[j - 1], self._values[j], n_steps) new_values.extend(list(intp_vals)[1:] + [self._values[j]]) i += n_steps # if the last steps are a hole duplicate the last value. if len(new_values) != len(new_datetimes): n_steps = len(new_datetimes) - len(new_values) new_values.extend([self._values[-1]] * n_steps) # build the new continuous data collection. return HourlyContinuousCollection(self.header.duplicate(), new_values)
[ "def", "interpolate_holes", "(", "self", ")", ":", "# validate analysis_period and use the resulting period to generate datetimes", "assert", "self", ".", "validated_a_period", "is", "True", ",", "'validated_a_period property must be'", "' True to use interpolate_holes(). Run validate_analysis_period().'", "mins_per_step", "=", "int", "(", "60", "/", "self", ".", "header", ".", "analysis_period", ".", "timestep", ")", "new_datetimes", "=", "self", ".", "header", ".", "analysis_period", ".", "datetimes", "new_values", "=", "[", "]", "# if the first steps are a hole, duplicate the first value.", "i", "=", "0", "if", "new_datetimes", "[", "0", "]", "!=", "self", ".", "datetimes", "[", "0", "]", ":", "n_steps", "=", "int", "(", "(", "self", ".", "datetimes", "[", "0", "]", ".", "moy", "-", "new_datetimes", "[", "0", "]", ".", "moy", ")", "/", "mins_per_step", ")", "new_values", ".", "extend", "(", "[", "self", ".", "_values", "[", "0", "]", "]", "*", "n_steps", ")", "i", "=", "n_steps", "-", "1", "# go through the values interpolating any holes.", "for", "j", "in", "xrange", "(", "len", "(", "self", ".", "_values", ")", ")", ":", "if", "new_datetimes", "[", "i", "]", "==", "self", ".", "datetimes", "[", "j", "]", ":", "# there is no hole.", "new_values", ".", "append", "(", "self", ".", "_values", "[", "j", "]", ")", "i", "+=", "1", "else", ":", "# there is a hole between this step and the previous step.", "n_steps", "=", "int", "(", "(", "self", ".", "datetimes", "[", "j", "]", ".", "moy", "-", "new_datetimes", "[", "i", "]", ".", "moy", ")", "/", "mins_per_step", ")", "intp_vals", "=", "self", ".", "_xxrange", "(", "self", ".", "_values", "[", "j", "-", "1", "]", ",", "self", ".", "_values", "[", "j", "]", ",", "n_steps", ")", "new_values", ".", "extend", "(", "list", "(", "intp_vals", ")", "[", "1", ":", "]", "+", "[", "self", ".", "_values", "[", "j", "]", "]", ")", "i", "+=", "n_steps", "# if the last steps are a hole duplicate the last value.", "if", "len", "(", "new_values", ")", "!=", "len", "(", "new_datetimes", ")", ":", "n_steps", "=", "len", "(", "new_datetimes", ")", "-", "len", "(", "new_values", ")", "new_values", ".", "extend", "(", "[", "self", ".", "_values", "[", "-", "1", "]", "]", "*", "n_steps", ")", "# build the new continuous data collection.", "return", "HourlyContinuousCollection", "(", "self", ".", "header", ".", "duplicate", "(", ")", ",", "new_values", ")" ]
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 interpolation.
[ "Linearly", "interpolate", "over", "holes", "in", "this", "collection", "to", "make", "it", "continuous", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L247-L287
4,601
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection.cull_to_timestep
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_values, new_datetimes = self._timestep_cull(timestep) new_header = self.header.duplicate() new_header._analysis_period = new_ap new_coll = HourlyDiscontinuousCollection( new_header, new_values, new_datetimes) new_coll._validated_a_period = True return new_coll
python
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_values, new_datetimes = self._timestep_cull(timestep) new_header = self.header.duplicate() new_header._analysis_period = new_ap new_coll = HourlyDiscontinuousCollection( new_header, new_values, new_datetimes) new_coll._validated_a_period = True return new_coll
[ "def", "cull_to_timestep", "(", "self", ",", "timestep", "=", "1", ")", ":", "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_values", ",", "new_datetimes", "=", "self", ".", "_timestep_cull", "(", "timestep", ")", "new_header", "=", "self", ".", "header", ".", "duplicate", "(", ")", "new_header", ".", "_analysis_period", "=", "new_ap", "new_coll", "=", "HourlyDiscontinuousCollection", "(", "new_header", ",", "new_values", ",", "new_datetimes", ")", "new_coll", ".", "_validated_a_period", "=", "True", "return", "new_coll" ]
Get a collection with only datetimes that fit a timestep.
[ "Get", "a", "collection", "with", "only", "datetimes", "that", "fit", "a", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L289-L301
4,602
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection.convert_to_culled_timestep
def convert_to_culled_timestep(self, timestep=1): """Convert this collection to one that only has 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_values, new_datetimes = self._timestep_cull(timestep) self.header._analysis_period = new_ap self._values = new_values self._datetimes = new_datetimes
python
def convert_to_culled_timestep(self, timestep=1): """Convert this collection to one that only has 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_values, new_datetimes = self._timestep_cull(timestep) self.header._analysis_period = new_ap self._values = new_values self._datetimes = new_datetimes
[ "def", "convert_to_culled_timestep", "(", "self", ",", "timestep", "=", "1", ")", ":", "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_values", ",", "new_datetimes", "=", "self", ".", "_timestep_cull", "(", "timestep", ")", "self", ".", "header", ".", "_analysis_period", "=", "new_ap", "self", ".", "_values", "=", "new_values", "self", ".", "_datetimes", "=", "new_datetimes" ]
Convert this collection to one that only has datetimes that fit a timestep.
[ "Convert", "this", "collection", "to", "one", "that", "only", "has", "datetimes", "that", "fit", "a", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L303-L312
4,603
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection._xxrange
def _xxrange(self, start, end, step_count): """Generate n values between start and end.""" _step = (end - start) / float(step_count) return (start + (i * _step) for i in xrange(int(step_count)))
python
def _xxrange(self, start, end, step_count): """Generate n values between start and end.""" _step = (end - start) / float(step_count) return (start + (i * _step) for i in xrange(int(step_count)))
[ "def", "_xxrange", "(", "self", ",", "start", ",", "end", ",", "step_count", ")", ":", "_step", "=", "(", "end", "-", "start", ")", "/", "float", "(", "step_count", ")", "return", "(", "start", "+", "(", "i", "*", "_step", ")", "for", "i", "in", "xrange", "(", "int", "(", "step_count", ")", ")", ")" ]
Generate n values between start and end.
[ "Generate", "n", "values", "between", "start", "and", "end", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L409-L412
4,604
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection._filter_by_moys_slow
def _filter_by_moys_slow(self, moys): """Filter the Data Collection with a slow method that always works.""" _filt_values = [] _filt_datetimes = [] for i, d in enumerate(self.datetimes): if d.moy in moys: _filt_datetimes.append(d) _filt_values.append(self._values[i]) return _filt_values, _filt_datetimes
python
def _filter_by_moys_slow(self, moys): """Filter the Data Collection with a slow method that always works.""" _filt_values = [] _filt_datetimes = [] for i, d in enumerate(self.datetimes): if d.moy in moys: _filt_datetimes.append(d) _filt_values.append(self._values[i]) return _filt_values, _filt_datetimes
[ "def", "_filter_by_moys_slow", "(", "self", ",", "moys", ")", ":", "_filt_values", "=", "[", "]", "_filt_datetimes", "=", "[", "]", "for", "i", ",", "d", "in", "enumerate", "(", "self", ".", "datetimes", ")", ":", "if", "d", ".", "moy", "in", "moys", ":", "_filt_datetimes", ".", "append", "(", "d", ")", "_filt_values", ".", "append", "(", "self", ".", "_values", "[", "i", "]", ")", "return", "_filt_values", ",", "_filt_datetimes" ]
Filter the Data Collection with a slow method that always works.
[ "Filter", "the", "Data", "Collection", "with", "a", "slow", "method", "that", "always", "works", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L414-L422
4,605
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection._timestep_cull
def _timestep_cull(self, timestep): """Cull out values that do not fit a timestep.""" new_values = [] new_datetimes = [] mins_per_step = int(60 / timestep) for i, date_t in enumerate(self.datetimes): if date_t.moy % mins_per_step == 0: new_datetimes.append(date_t) new_values.append(self.values[i]) a_per = self.header.analysis_period new_ap = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_month, a_per.end_day, a_per.end_hour, timestep, a_per.is_leap_year) return new_ap, new_values, new_datetimes
python
def _timestep_cull(self, timestep): """Cull out values that do not fit a timestep.""" new_values = [] new_datetimes = [] mins_per_step = int(60 / timestep) for i, date_t in enumerate(self.datetimes): if date_t.moy % mins_per_step == 0: new_datetimes.append(date_t) new_values.append(self.values[i]) a_per = self.header.analysis_period new_ap = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_month, a_per.end_day, a_per.end_hour, timestep, a_per.is_leap_year) return new_ap, new_values, new_datetimes
[ "def", "_timestep_cull", "(", "self", ",", "timestep", ")", ":", "new_values", "=", "[", "]", "new_datetimes", "=", "[", "]", "mins_per_step", "=", "int", "(", "60", "/", "timestep", ")", "for", "i", ",", "date_t", "in", "enumerate", "(", "self", ".", "datetimes", ")", ":", "if", "date_t", ".", "moy", "%", "mins_per_step", "==", "0", ":", "new_datetimes", ".", "append", "(", "date_t", ")", "new_values", ".", "append", "(", "self", ".", "values", "[", "i", "]", ")", "a_per", "=", "self", ".", "header", ".", "analysis_period", "new_ap", "=", "AnalysisPeriod", "(", "a_per", ".", "st_month", ",", "a_per", ".", "st_day", ",", "a_per", ".", "st_hour", ",", "a_per", ".", "end_month", ",", "a_per", ".", "end_day", ",", "a_per", ".", "end_hour", ",", "timestep", ",", "a_per", ".", "is_leap_year", ")", "return", "new_ap", ",", "new_values", ",", "new_datetimes" ]
Cull out values that do not fit a timestep.
[ "Cull", "out", "values", "that", "do", "not", "fit", "a", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L424-L437
4,606
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyDiscontinuousCollection._time_interval_operation
def _time_interval_operation(self, interval, operation, percentile=0): """Get a collection of a certain time interval with a given math operation.""" # retrive the function that correctly describes the operation if operation == 'average': funct = self._average elif operation == 'total': funct = self._total else: assert 0 <= percentile <= 100, \ 'percentile must be between 0 and 100. Got {}'.format(percentile) funct = self._get_percentile_function(percentile) # retrive the data that correctly describes the time interval if interval == 'monthly': data_dict = self.group_by_month() dates = self.header.analysis_period.months_int elif interval == 'daily': data_dict = self.group_by_day() dates = self.header.analysis_period.doys_int elif interval == 'monthlyperhour': data_dict = self.group_by_month_per_hour() dates = self.header.analysis_period.months_per_hour else: raise ValueError('Invalid input value for interval: {}'.format(interval)) # get the data and header for the new collection new_data, d_times = [], [] for i in dates: vals = data_dict[i] if vals != []: new_data.append(funct(vals)) d_times.append(i) new_header = self.header.duplicate() if operation == 'percentile': new_header.metadata['operation'] = '{} percentile'.format(percentile) else: new_header.metadata['operation'] = operation # build the final data collection if interval == 'monthly': collection = MonthlyCollection(new_header, new_data, d_times) elif interval == 'daily': collection = DailyCollection(new_header, new_data, d_times) elif interval == 'monthlyperhour': collection = MonthlyPerHourCollection(new_header, new_data, d_times) collection._validated_a_period = True return collection
python
def _time_interval_operation(self, interval, operation, percentile=0): """Get a collection of a certain time interval with a given math operation.""" # retrive the function that correctly describes the operation if operation == 'average': funct = self._average elif operation == 'total': funct = self._total else: assert 0 <= percentile <= 100, \ 'percentile must be between 0 and 100. Got {}'.format(percentile) funct = self._get_percentile_function(percentile) # retrive the data that correctly describes the time interval if interval == 'monthly': data_dict = self.group_by_month() dates = self.header.analysis_period.months_int elif interval == 'daily': data_dict = self.group_by_day() dates = self.header.analysis_period.doys_int elif interval == 'monthlyperhour': data_dict = self.group_by_month_per_hour() dates = self.header.analysis_period.months_per_hour else: raise ValueError('Invalid input value for interval: {}'.format(interval)) # get the data and header for the new collection new_data, d_times = [], [] for i in dates: vals = data_dict[i] if vals != []: new_data.append(funct(vals)) d_times.append(i) new_header = self.header.duplicate() if operation == 'percentile': new_header.metadata['operation'] = '{} percentile'.format(percentile) else: new_header.metadata['operation'] = operation # build the final data collection if interval == 'monthly': collection = MonthlyCollection(new_header, new_data, d_times) elif interval == 'daily': collection = DailyCollection(new_header, new_data, d_times) elif interval == 'monthlyperhour': collection = MonthlyPerHourCollection(new_header, new_data, d_times) collection._validated_a_period = True return collection
[ "def", "_time_interval_operation", "(", "self", ",", "interval", ",", "operation", ",", "percentile", "=", "0", ")", ":", "# retrive the function that correctly describes the operation", "if", "operation", "==", "'average'", ":", "funct", "=", "self", ".", "_average", "elif", "operation", "==", "'total'", ":", "funct", "=", "self", ".", "_total", "else", ":", "assert", "0", "<=", "percentile", "<=", "100", ",", "'percentile must be between 0 and 100. Got {}'", ".", "format", "(", "percentile", ")", "funct", "=", "self", ".", "_get_percentile_function", "(", "percentile", ")", "# retrive the data that correctly describes the time interval", "if", "interval", "==", "'monthly'", ":", "data_dict", "=", "self", ".", "group_by_month", "(", ")", "dates", "=", "self", ".", "header", ".", "analysis_period", ".", "months_int", "elif", "interval", "==", "'daily'", ":", "data_dict", "=", "self", ".", "group_by_day", "(", ")", "dates", "=", "self", ".", "header", ".", "analysis_period", ".", "doys_int", "elif", "interval", "==", "'monthlyperhour'", ":", "data_dict", "=", "self", ".", "group_by_month_per_hour", "(", ")", "dates", "=", "self", ".", "header", ".", "analysis_period", ".", "months_per_hour", "else", ":", "raise", "ValueError", "(", "'Invalid input value for interval: {}'", ".", "format", "(", "interval", ")", ")", "# get the data and header for the new collection", "new_data", ",", "d_times", "=", "[", "]", ",", "[", "]", "for", "i", "in", "dates", ":", "vals", "=", "data_dict", "[", "i", "]", "if", "vals", "!=", "[", "]", ":", "new_data", ".", "append", "(", "funct", "(", "vals", ")", ")", "d_times", ".", "append", "(", "i", ")", "new_header", "=", "self", ".", "header", ".", "duplicate", "(", ")", "if", "operation", "==", "'percentile'", ":", "new_header", ".", "metadata", "[", "'operation'", "]", "=", "'{} percentile'", ".", "format", "(", "percentile", ")", "else", ":", "new_header", ".", "metadata", "[", "'operation'", "]", "=", "operation", "# build the final data collection", "if", "interval", "==", "'monthly'", ":", "collection", "=", "MonthlyCollection", "(", "new_header", ",", "new_data", ",", "d_times", ")", "elif", "interval", "==", "'daily'", ":", "collection", "=", "DailyCollection", "(", "new_header", ",", "new_data", ",", "d_times", ")", "elif", "interval", "==", "'monthlyperhour'", ":", "collection", "=", "MonthlyPerHourCollection", "(", "new_header", ",", "new_data", ",", "d_times", ")", "collection", ".", "_validated_a_period", "=", "True", "return", "collection" ]
Get a collection of a certain time interval with a given math operation.
[ "Get", "a", "collection", "of", "a", "certain", "time", "interval", "with", "a", "given", "math", "operation", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L449-L495
4,607
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyContinuousCollection.datetimes
def datetimes(self): """Return datetimes for this collection as a tuple.""" if self._datetimes is None: self._datetimes = tuple(self.header.analysis_period.datetimes) return self._datetimes
python
def datetimes(self): """Return datetimes for this collection as a tuple.""" if self._datetimes is None: self._datetimes = tuple(self.header.analysis_period.datetimes) return self._datetimes
[ "def", "datetimes", "(", "self", ")", ":", "if", "self", ".", "_datetimes", "is", "None", ":", "self", ".", "_datetimes", "=", "tuple", "(", "self", ".", "header", ".", "analysis_period", ".", "datetimes", ")", "return", "self", ".", "_datetimes" ]
Return datetimes for this collection as a tuple.
[ "Return", "datetimes", "for", "this", "collection", "as", "a", "tuple", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L554-L558
4,608
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyContinuousCollection.interpolate_to_timestep
def interpolate_to_timestep(self, timestep, cumulative=None): """Interpolate data for a finer timestep using a linear interpolation. Args: timestep: Target timestep as an integer. Target timestep must be divisable by current timestep. cumulative: A boolean that sets whether the interpolation should treat the data colection values as cumulative, in which case the value at each timestep is the value over that timestep (instead of over the hour). The default will check the DataType to see if this type of data is typically cumulative over time. Return: A continuous hourly data collection with data interpolated to the input timestep. """ assert timestep % self.header.analysis_period.timestep == 0, \ 'Target timestep({}) must be divisable by current timestep({})' \ .format(timestep, self.header.analysis_period.timestep) if cumulative is not None: assert isinstance(cumulative, bool), \ 'Expected Boolean. Got {}'.format(type(cumulative)) # generate new data _new_values = [] _data_length = len(self._values) for d in xrange(_data_length): for _v in self._xxrange(self[d], self[(d + 1) % _data_length], timestep): _new_values.append(_v) # divide cumulative values by the timestep native_cumulative = self.header.data_type.cumulative if cumulative is True or (cumulative is None and native_cumulative): for i, d in enumerate(_new_values): _new_values[i] = d / timestep # shift data by a half-hour if data is averaged or cumulative over an hour if self.header.data_type.point_in_time is False: shift_dist = int(timestep / 2) _new_values = _new_values[-shift_dist:] + _new_values[:-shift_dist] # build a new header a_per = self.header.analysis_period _new_a_per = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_month, a_per.end_day, a_per.end_hour, timestep, a_per.is_leap_year) _new_header = self.header.duplicate() _new_header._analysis_period = _new_a_per return HourlyContinuousCollection(_new_header, _new_values)
python
def interpolate_to_timestep(self, timestep, cumulative=None): """Interpolate data for a finer timestep using a linear interpolation. Args: timestep: Target timestep as an integer. Target timestep must be divisable by current timestep. cumulative: A boolean that sets whether the interpolation should treat the data colection values as cumulative, in which case the value at each timestep is the value over that timestep (instead of over the hour). The default will check the DataType to see if this type of data is typically cumulative over time. Return: A continuous hourly data collection with data interpolated to the input timestep. """ assert timestep % self.header.analysis_period.timestep == 0, \ 'Target timestep({}) must be divisable by current timestep({})' \ .format(timestep, self.header.analysis_period.timestep) if cumulative is not None: assert isinstance(cumulative, bool), \ 'Expected Boolean. Got {}'.format(type(cumulative)) # generate new data _new_values = [] _data_length = len(self._values) for d in xrange(_data_length): for _v in self._xxrange(self[d], self[(d + 1) % _data_length], timestep): _new_values.append(_v) # divide cumulative values by the timestep native_cumulative = self.header.data_type.cumulative if cumulative is True or (cumulative is None and native_cumulative): for i, d in enumerate(_new_values): _new_values[i] = d / timestep # shift data by a half-hour if data is averaged or cumulative over an hour if self.header.data_type.point_in_time is False: shift_dist = int(timestep / 2) _new_values = _new_values[-shift_dist:] + _new_values[:-shift_dist] # build a new header a_per = self.header.analysis_period _new_a_per = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_month, a_per.end_day, a_per.end_hour, timestep, a_per.is_leap_year) _new_header = self.header.duplicate() _new_header._analysis_period = _new_a_per return HourlyContinuousCollection(_new_header, _new_values)
[ "def", "interpolate_to_timestep", "(", "self", ",", "timestep", ",", "cumulative", "=", "None", ")", ":", "assert", "timestep", "%", "self", ".", "header", ".", "analysis_period", ".", "timestep", "==", "0", ",", "'Target timestep({}) must be divisable by current timestep({})'", ".", "format", "(", "timestep", ",", "self", ".", "header", ".", "analysis_period", ".", "timestep", ")", "if", "cumulative", "is", "not", "None", ":", "assert", "isinstance", "(", "cumulative", ",", "bool", ")", ",", "'Expected Boolean. Got {}'", ".", "format", "(", "type", "(", "cumulative", ")", ")", "# generate new data", "_new_values", "=", "[", "]", "_data_length", "=", "len", "(", "self", ".", "_values", ")", "for", "d", "in", "xrange", "(", "_data_length", ")", ":", "for", "_v", "in", "self", ".", "_xxrange", "(", "self", "[", "d", "]", ",", "self", "[", "(", "d", "+", "1", ")", "%", "_data_length", "]", ",", "timestep", ")", ":", "_new_values", ".", "append", "(", "_v", ")", "# divide cumulative values by the timestep", "native_cumulative", "=", "self", ".", "header", ".", "data_type", ".", "cumulative", "if", "cumulative", "is", "True", "or", "(", "cumulative", "is", "None", "and", "native_cumulative", ")", ":", "for", "i", ",", "d", "in", "enumerate", "(", "_new_values", ")", ":", "_new_values", "[", "i", "]", "=", "d", "/", "timestep", "# shift data by a half-hour if data is averaged or cumulative over an hour", "if", "self", ".", "header", ".", "data_type", ".", "point_in_time", "is", "False", ":", "shift_dist", "=", "int", "(", "timestep", "/", "2", ")", "_new_values", "=", "_new_values", "[", "-", "shift_dist", ":", "]", "+", "_new_values", "[", ":", "-", "shift_dist", "]", "# build a new header", "a_per", "=", "self", ".", "header", ".", "analysis_period", "_new_a_per", "=", "AnalysisPeriod", "(", "a_per", ".", "st_month", ",", "a_per", ".", "st_day", ",", "a_per", ".", "st_hour", ",", "a_per", ".", "end_month", ",", "a_per", ".", "end_day", ",", "a_per", ".", "end_hour", ",", "timestep", ",", "a_per", ".", "is_leap_year", ")", "_new_header", "=", "self", ".", "header", ".", "duplicate", "(", ")", "_new_header", ".", "_analysis_period", "=", "_new_a_per", "return", "HourlyContinuousCollection", "(", "_new_header", ",", "_new_values", ")" ]
Interpolate data for a finer timestep using a linear interpolation. Args: timestep: Target timestep as an integer. Target timestep must be divisable by current timestep. cumulative: A boolean that sets whether the interpolation should treat the data colection values as cumulative, in which case the value at each timestep is the value over that timestep (instead of over the hour). The default will check the DataType to see if this type of data is typically cumulative over time. Return: A continuous hourly data collection with data interpolated to the input timestep.
[ "Interpolate", "data", "for", "a", "finer", "timestep", "using", "a", "linear", "interpolation", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L567-L616
4,609
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyContinuousCollection.filter_by_hoys
def filter_by_hoys(self, hoys): """Filter the Data Collection based onva list of hoys. Args: hoys: A List of hours of the year 0..8759 Return: A new Data Collection with filtered data """ existing_hoys = self.header.analysis_period.hoys hoys = [h for h in hoys if h in existing_hoys] _moys = tuple(int(hour * 60) for hour in hoys) return self.filter_by_moys(_moys)
python
def filter_by_hoys(self, hoys): """Filter the Data Collection based onva list of hoys. Args: hoys: A List of hours of the year 0..8759 Return: A new Data Collection with filtered data """ existing_hoys = self.header.analysis_period.hoys hoys = [h for h in hoys if h in existing_hoys] _moys = tuple(int(hour * 60) for hour in hoys) return self.filter_by_moys(_moys)
[ "def", "filter_by_hoys", "(", "self", ",", "hoys", ")", ":", "existing_hoys", "=", "self", ".", "header", ".", "analysis_period", ".", "hoys", "hoys", "=", "[", "h", "for", "h", "in", "hoys", "if", "h", "in", "existing_hoys", "]", "_moys", "=", "tuple", "(", "int", "(", "hour", "*", "60", ")", "for", "hour", "in", "hoys", ")", "return", "self", ".", "filter_by_moys", "(", "_moys", ")" ]
Filter the Data Collection based onva list of hoys. Args: hoys: A List of hours of the year 0..8759 Return: A new Data Collection with filtered data
[ "Filter", "the", "Data", "Collection", "based", "onva", "list", "of", "hoys", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L683-L695
4,610
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyContinuousCollection.to_immutable
def to_immutable(self): """Get an immutable version of this collection.""" if self._enumeration is None: self._get_mutable_enumeration() col_obj = self._enumeration['immutable'][self._collection_type] return col_obj(self.header, self.values)
python
def to_immutable(self): """Get an immutable version of this collection.""" if self._enumeration is None: self._get_mutable_enumeration() col_obj = self._enumeration['immutable'][self._collection_type] return col_obj(self.header, self.values)
[ "def", "to_immutable", "(", "self", ")", ":", "if", "self", ".", "_enumeration", "is", "None", ":", "self", ".", "_get_mutable_enumeration", "(", ")", "col_obj", "=", "self", ".", "_enumeration", "[", "'immutable'", "]", "[", "self", ".", "_collection_type", "]", "return", "col_obj", "(", "self", ".", "header", ",", "self", ".", "values", ")" ]
Get an immutable version of this collection.
[ "Get", "an", "immutable", "version", "of", "this", "collection", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L782-L787
4,611
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyContinuousCollection.to_discontinuous
def to_discontinuous(self): """Return a discontinuous version of the current collection.""" collection = HourlyDiscontinuousCollection(self.header.duplicate(), self.values, self.datetimes) collection._validated_a_period = True return collection
python
def to_discontinuous(self): """Return a discontinuous version of the current collection.""" collection = HourlyDiscontinuousCollection(self.header.duplicate(), self.values, self.datetimes) collection._validated_a_period = True return collection
[ "def", "to_discontinuous", "(", "self", ")", ":", "collection", "=", "HourlyDiscontinuousCollection", "(", "self", ".", "header", ".", "duplicate", "(", ")", ",", "self", ".", "values", ",", "self", ".", "datetimes", ")", "collection", ".", "_validated_a_period", "=", "True", "return", "collection" ]
Return a discontinuous version of the current collection.
[ "Return", "a", "discontinuous", "version", "of", "the", "current", "collection", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L854-L859
4,612
ladybug-tools/ladybug
ladybug/datacollection.py
HourlyContinuousCollection._get_analysis_period_subset
def _get_analysis_period_subset(self, a_per): """Return an analysis_period is always a subset of the Data Collection""" if self.header.analysis_period.is_annual: return a_per new_needed = False n_ap = [a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_month, a_per.end_day, a_per.end_hour, a_per.timestep, a_per.is_leap_year] if a_per.st_hour < self.header.analysis_period.st_hour: n_ap[2] = self.header.analysis_period.st_hour new_needed = True if a_per.end_hour > self.header.analysis_period.end_hour: n_ap[5] = self.header.analysis_period.end_hour new_needed = True if a_per.st_time.doy < self.header.analysis_period.st_time.doy: n_ap[0] = self.header.analysis_period.st_month n_ap[1] = self.header.analysis_period.st_day new_needed = True if a_per.end_time.doy > self.header.analysis_period.end_time.doy: n_ap[3] = self.header.analysis_period.end_month n_ap[4] = self.header.analysis_period.end_day new_needed = True if new_needed is False: return a_per else: return AnalysisPeriod(*n_ap)
python
def _get_analysis_period_subset(self, a_per): """Return an analysis_period is always a subset of the Data Collection""" if self.header.analysis_period.is_annual: return a_per new_needed = False n_ap = [a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_month, a_per.end_day, a_per.end_hour, a_per.timestep, a_per.is_leap_year] if a_per.st_hour < self.header.analysis_period.st_hour: n_ap[2] = self.header.analysis_period.st_hour new_needed = True if a_per.end_hour > self.header.analysis_period.end_hour: n_ap[5] = self.header.analysis_period.end_hour new_needed = True if a_per.st_time.doy < self.header.analysis_period.st_time.doy: n_ap[0] = self.header.analysis_period.st_month n_ap[1] = self.header.analysis_period.st_day new_needed = True if a_per.end_time.doy > self.header.analysis_period.end_time.doy: n_ap[3] = self.header.analysis_period.end_month n_ap[4] = self.header.analysis_period.end_day new_needed = True if new_needed is False: return a_per else: return AnalysisPeriod(*n_ap)
[ "def", "_get_analysis_period_subset", "(", "self", ",", "a_per", ")", ":", "if", "self", ".", "header", ".", "analysis_period", ".", "is_annual", ":", "return", "a_per", "new_needed", "=", "False", "n_ap", "=", "[", "a_per", ".", "st_month", ",", "a_per", ".", "st_day", ",", "a_per", ".", "st_hour", ",", "a_per", ".", "end_month", ",", "a_per", ".", "end_day", ",", "a_per", ".", "end_hour", ",", "a_per", ".", "timestep", ",", "a_per", ".", "is_leap_year", "]", "if", "a_per", ".", "st_hour", "<", "self", ".", "header", ".", "analysis_period", ".", "st_hour", ":", "n_ap", "[", "2", "]", "=", "self", ".", "header", ".", "analysis_period", ".", "st_hour", "new_needed", "=", "True", "if", "a_per", ".", "end_hour", ">", "self", ".", "header", ".", "analysis_period", ".", "end_hour", ":", "n_ap", "[", "5", "]", "=", "self", ".", "header", ".", "analysis_period", ".", "end_hour", "new_needed", "=", "True", "if", "a_per", ".", "st_time", ".", "doy", "<", "self", ".", "header", ".", "analysis_period", ".", "st_time", ".", "doy", ":", "n_ap", "[", "0", "]", "=", "self", ".", "header", ".", "analysis_period", ".", "st_month", "n_ap", "[", "1", "]", "=", "self", ".", "header", ".", "analysis_period", ".", "st_day", "new_needed", "=", "True", "if", "a_per", ".", "end_time", ".", "doy", ">", "self", ".", "header", ".", "analysis_period", ".", "end_time", ".", "doy", ":", "n_ap", "[", "3", "]", "=", "self", ".", "header", ".", "analysis_period", ".", "end_month", "n_ap", "[", "4", "]", "=", "self", ".", "header", ".", "analysis_period", ".", "end_day", "new_needed", "=", "True", "if", "new_needed", "is", "False", ":", "return", "a_per", "else", ":", "return", "AnalysisPeriod", "(", "*", "n_ap", ")" ]
Return an analysis_period is always a subset of the Data Collection
[ "Return", "an", "analysis_period", "is", "always", "a", "subset", "of", "the", "Data", "Collection" ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L875-L901
4,613
ladybug-tools/ladybug
ladybug/datacollection.py
DailyCollection._monthly_operation
def _monthly_operation(self, operation, percentile=0): """Get a MonthlyCollection given a certain operation.""" # Retrive the correct operation. if operation == 'average': funct = self._average elif operation == 'total': funct = self._total else: assert 0 <= percentile <= 100, \ 'percentile must be between 0 and 100. Got {}'.format(percentile) funct = self._get_percentile_function(percentile) # Get the data for the new collection data_dict = self.group_by_month() new_data, d_times = [], [] for i in self.header.analysis_period.months_int: vals = data_dict[i] if vals != []: new_data.append(funct(vals)) d_times.append(i) # build the new monthly collection new_header = self.header.duplicate() if operation == 'percentile': new_header.metadata['operation'] = '{} percentile'.format(percentile) else: new_header.metadata['operation'] = operation collection = MonthlyCollection(new_header, new_data, d_times) collection._validated_a_period = True return collection
python
def _monthly_operation(self, operation, percentile=0): """Get a MonthlyCollection given a certain operation.""" # Retrive the correct operation. if operation == 'average': funct = self._average elif operation == 'total': funct = self._total else: assert 0 <= percentile <= 100, \ 'percentile must be between 0 and 100. Got {}'.format(percentile) funct = self._get_percentile_function(percentile) # Get the data for the new collection data_dict = self.group_by_month() new_data, d_times = [], [] for i in self.header.analysis_period.months_int: vals = data_dict[i] if vals != []: new_data.append(funct(vals)) d_times.append(i) # build the new monthly collection new_header = self.header.duplicate() if operation == 'percentile': new_header.metadata['operation'] = '{} percentile'.format(percentile) else: new_header.metadata['operation'] = operation collection = MonthlyCollection(new_header, new_data, d_times) collection._validated_a_period = True return collection
[ "def", "_monthly_operation", "(", "self", ",", "operation", ",", "percentile", "=", "0", ")", ":", "# Retrive the correct operation.", "if", "operation", "==", "'average'", ":", "funct", "=", "self", ".", "_average", "elif", "operation", "==", "'total'", ":", "funct", "=", "self", ".", "_total", "else", ":", "assert", "0", "<=", "percentile", "<=", "100", ",", "'percentile must be between 0 and 100. Got {}'", ".", "format", "(", "percentile", ")", "funct", "=", "self", ".", "_get_percentile_function", "(", "percentile", ")", "# Get the data for the new collection", "data_dict", "=", "self", ".", "group_by_month", "(", ")", "new_data", ",", "d_times", "=", "[", "]", ",", "[", "]", "for", "i", "in", "self", ".", "header", ".", "analysis_period", ".", "months_int", ":", "vals", "=", "data_dict", "[", "i", "]", "if", "vals", "!=", "[", "]", ":", "new_data", ".", "append", "(", "funct", "(", "vals", ")", ")", "d_times", ".", "append", "(", "i", ")", "# build the new monthly collection", "new_header", "=", "self", ".", "header", ".", "duplicate", "(", ")", "if", "operation", "==", "'percentile'", ":", "new_header", ".", "metadata", "[", "'operation'", "]", "=", "'{} percentile'", ".", "format", "(", "percentile", ")", "else", ":", "new_header", ".", "metadata", "[", "'operation'", "]", "=", "operation", "collection", "=", "MonthlyCollection", "(", "new_header", ",", "new_data", ",", "d_times", ")", "collection", ".", "_validated_a_period", "=", "True", "return", "collection" ]
Get a MonthlyCollection given a certain operation.
[ "Get", "a", "MonthlyCollection", "given", "a", "certain", "operation", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L1095-L1124
4,614
ladybug-tools/ladybug
ladybug/datatype/temperaturetime.py
TemperatureTime.to_unit
def to_unit(self, values, unit, from_unit): """Return values converted to the unit given the input from_unit.""" return self._to_unit_base('degC-days', values, unit, from_unit)
python
def to_unit(self, values, unit, from_unit): """Return values converted to the unit given the input from_unit.""" return self._to_unit_base('degC-days', values, unit, from_unit)
[ "def", "to_unit", "(", "self", ",", "values", ",", "unit", ",", "from_unit", ")", ":", "return", "self", ".", "_to_unit_base", "(", "'degC-days'", ",", "values", ",", "unit", ",", "from_unit", ")" ]
Return values converted to the unit given the input from_unit.
[ "Return", "values", "converted", "to", "the", "unit", "given", "the", "input", "from_unit", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/temperaturetime.py#L33-L35
4,615
ladybug-tools/ladybug
ladybug/rootfind.py
bisect
def bisect(a, b, fn, epsilon, target): """ The simplest root-finding algorithm. It is extremely reliable. However, it converges slowly for this reason, it is recommended that this only be used after the secant() method has returned None. Args: a: A lower guess of the value you are tying to find. b: A higher guess of the value you are tying to find. fn: A function representing the relationship between the value you are trying to find and the target condition you are trying to satisfy. It should typically be structured in the following way: `def fn(value_trying_to_find): funct(value_trying_to_find) - target_desired_from_funct` ...but the subtraction should be swtiched if value_trying_to_find has a negative relationship with the funct. epsilon: The acceptable error in the target_desired_from_funct. target: The target slope (typically 0 for a local minima or maxima). Returns: root: The value that gives the target_desired_from_funct. References ---------- [1] Wikipedia contributors. (2018, December 29). Root-finding algorithm. In Wikipedia, The Free Encyclopedia. Retrieved 18:16, December 30, 2018, from https://en.wikipedia.org/wiki/Root-finding_algorithm#Bisection_method """ while (abs(b - a) > 2 * epsilon): midpoint = (b + a) / 2 a_t = fn(a) b_t = fn(b) midpoint_t = fn(midpoint) if (a_t - target) * (midpoint_t - target) < 0: b = midpoint elif (b_t - target) * (midpoint_t - target) < 0: a = midpoint else: return -999 return midpoint
python
def bisect(a, b, fn, epsilon, target): """ The simplest root-finding algorithm. It is extremely reliable. However, it converges slowly for this reason, it is recommended that this only be used after the secant() method has returned None. Args: a: A lower guess of the value you are tying to find. b: A higher guess of the value you are tying to find. fn: A function representing the relationship between the value you are trying to find and the target condition you are trying to satisfy. It should typically be structured in the following way: `def fn(value_trying_to_find): funct(value_trying_to_find) - target_desired_from_funct` ...but the subtraction should be swtiched if value_trying_to_find has a negative relationship with the funct. epsilon: The acceptable error in the target_desired_from_funct. target: The target slope (typically 0 for a local minima or maxima). Returns: root: The value that gives the target_desired_from_funct. References ---------- [1] Wikipedia contributors. (2018, December 29). Root-finding algorithm. In Wikipedia, The Free Encyclopedia. Retrieved 18:16, December 30, 2018, from https://en.wikipedia.org/wiki/Root-finding_algorithm#Bisection_method """ while (abs(b - a) > 2 * epsilon): midpoint = (b + a) / 2 a_t = fn(a) b_t = fn(b) midpoint_t = fn(midpoint) if (a_t - target) * (midpoint_t - target) < 0: b = midpoint elif (b_t - target) * (midpoint_t - target) < 0: a = midpoint else: return -999 return midpoint
[ "def", "bisect", "(", "a", ",", "b", ",", "fn", ",", "epsilon", ",", "target", ")", ":", "while", "(", "abs", "(", "b", "-", "a", ")", ">", "2", "*", "epsilon", ")", ":", "midpoint", "=", "(", "b", "+", "a", ")", "/", "2", "a_t", "=", "fn", "(", "a", ")", "b_t", "=", "fn", "(", "b", ")", "midpoint_t", "=", "fn", "(", "midpoint", ")", "if", "(", "a_t", "-", "target", ")", "*", "(", "midpoint_t", "-", "target", ")", "<", "0", ":", "b", "=", "midpoint", "elif", "(", "b_t", "-", "target", ")", "*", "(", "midpoint_t", "-", "target", ")", "<", "0", ":", "a", "=", "midpoint", "else", ":", "return", "-", "999", "return", "midpoint" ]
The simplest root-finding algorithm. It is extremely reliable. However, it converges slowly for this reason, it is recommended that this only be used after the secant() method has returned None. Args: a: A lower guess of the value you are tying to find. b: A higher guess of the value you are tying to find. fn: A function representing the relationship between the value you are trying to find and the target condition you are trying to satisfy. It should typically be structured in the following way: `def fn(value_trying_to_find): funct(value_trying_to_find) - target_desired_from_funct` ...but the subtraction should be swtiched if value_trying_to_find has a negative relationship with the funct. epsilon: The acceptable error in the target_desired_from_funct. target: The target slope (typically 0 for a local minima or maxima). Returns: root: The value that gives the target_desired_from_funct. References ---------- [1] Wikipedia contributors. (2018, December 29). Root-finding algorithm. In Wikipedia, The Free Encyclopedia. Retrieved 18:16, December 30, 2018, from https://en.wikipedia.org/wiki/Root-finding_algorithm#Bisection_method
[ "The", "simplest", "root", "-", "finding", "algorithm", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/rootfind.py#L56-L98
4,616
ladybug-tools/ladybug
ladybug/location.py
Location.from_json
def from_json(cls, data): """Create a location from a dictionary. Args: data: { "city": "-", "latitude": 0, "longitude": 0, "time_zone": 0, "elevation": 0} """ optional_keys = ('city', 'state', 'country', 'latitude', 'longitude', 'time_zone', 'elevation', 'station_id', 'source') for key in optional_keys: if key not in data: data[key] = None return cls(data['city'], data['state'], data['country'], data['latitude'], data['longitude'], data['time_zone'], data['elevation'], data['station_id'], data['source'])
python
def from_json(cls, data): """Create a location from a dictionary. Args: data: { "city": "-", "latitude": 0, "longitude": 0, "time_zone": 0, "elevation": 0} """ optional_keys = ('city', 'state', 'country', 'latitude', 'longitude', 'time_zone', 'elevation', 'station_id', 'source') for key in optional_keys: if key not in data: data[key] = None return cls(data['city'], data['state'], data['country'], data['latitude'], data['longitude'], data['time_zone'], data['elevation'], data['station_id'], data['source'])
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "optional_keys", "=", "(", "'city'", ",", "'state'", ",", "'country'", ",", "'latitude'", ",", "'longitude'", ",", "'time_zone'", ",", "'elevation'", ",", "'station_id'", ",", "'source'", ")", "for", "key", "in", "optional_keys", ":", "if", "key", "not", "in", "data", ":", "data", "[", "key", "]", "=", "None", "return", "cls", "(", "data", "[", "'city'", "]", ",", "data", "[", "'state'", "]", ",", "data", "[", "'country'", "]", ",", "data", "[", "'latitude'", "]", ",", "data", "[", "'longitude'", "]", ",", "data", "[", "'time_zone'", "]", ",", "data", "[", "'elevation'", "]", ",", "data", "[", "'station_id'", "]", ",", "data", "[", "'source'", "]", ")" ]
Create a location from a dictionary. Args: data: { "city": "-", "latitude": 0, "longitude": 0, "time_zone": 0, "elevation": 0}
[ "Create", "a", "location", "from", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L40-L59
4,617
ladybug-tools/ladybug
ladybug/location.py
Location.from_location
def from_location(cls, location): """Try to create a Ladybug location from a location string. Args: locationString: Location string Usage: l = Location.from_location(locationString) """ if not location: return cls() try: if hasattr(location, 'isLocation'): # Ladybug location return location elif hasattr(location, 'Latitude'): # Revit's location return cls(city=str(location.Name.replace(",", " ")), latitude=location.Latitude, longitude=location.Longitude) elif location.startswith('Site:'): loc, city, latitude, longitude, time_zone, elevation = \ [x.strip() for x in re.findall(r'\r*\n*([^\r\n]*)[,|;]', location, re.DOTALL)] else: try: city, latitude, longitude, time_zone, elevation = \ [key.split(":")[-1].strip() for key in location.split(",")] except ValueError: # it's just the city name return cls(city=location) return cls(city=city, country=None, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation) except Exception as e: raise ValueError( "Failed to create a Location from %s!\n%s" % (location, e))
python
def from_location(cls, location): """Try to create a Ladybug location from a location string. Args: locationString: Location string Usage: l = Location.from_location(locationString) """ if not location: return cls() try: if hasattr(location, 'isLocation'): # Ladybug location return location elif hasattr(location, 'Latitude'): # Revit's location return cls(city=str(location.Name.replace(",", " ")), latitude=location.Latitude, longitude=location.Longitude) elif location.startswith('Site:'): loc, city, latitude, longitude, time_zone, elevation = \ [x.strip() for x in re.findall(r'\r*\n*([^\r\n]*)[,|;]', location, re.DOTALL)] else: try: city, latitude, longitude, time_zone, elevation = \ [key.split(":")[-1].strip() for key in location.split(",")] except ValueError: # it's just the city name return cls(city=location) return cls(city=city, country=None, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation) except Exception as e: raise ValueError( "Failed to create a Location from %s!\n%s" % (location, e))
[ "def", "from_location", "(", "cls", ",", "location", ")", ":", "if", "not", "location", ":", "return", "cls", "(", ")", "try", ":", "if", "hasattr", "(", "location", ",", "'isLocation'", ")", ":", "# Ladybug location", "return", "location", "elif", "hasattr", "(", "location", ",", "'Latitude'", ")", ":", "# Revit's location", "return", "cls", "(", "city", "=", "str", "(", "location", ".", "Name", ".", "replace", "(", "\",\"", ",", "\" \"", ")", ")", ",", "latitude", "=", "location", ".", "Latitude", ",", "longitude", "=", "location", ".", "Longitude", ")", "elif", "location", ".", "startswith", "(", "'Site:'", ")", ":", "loc", ",", "city", ",", "latitude", ",", "longitude", ",", "time_zone", ",", "elevation", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "re", ".", "findall", "(", "r'\\r*\\n*([^\\r\\n]*)[,|;]'", ",", "location", ",", "re", ".", "DOTALL", ")", "]", "else", ":", "try", ":", "city", ",", "latitude", ",", "longitude", ",", "time_zone", ",", "elevation", "=", "[", "key", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "for", "key", "in", "location", ".", "split", "(", "\",\"", ")", "]", "except", "ValueError", ":", "# it's just the city name", "return", "cls", "(", "city", "=", "location", ")", "return", "cls", "(", "city", "=", "city", ",", "country", "=", "None", ",", "latitude", "=", "latitude", ",", "longitude", "=", "longitude", ",", "time_zone", "=", "time_zone", ",", "elevation", "=", "elevation", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "\"Failed to create a Location from %s!\\n%s\"", "%", "(", "location", ",", "e", ")", ")" ]
Try to create a Ladybug location from a location string. Args: locationString: Location string Usage: l = Location.from_location(locationString)
[ "Try", "to", "create", "a", "Ladybug", "location", "from", "a", "location", "string", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L62-L104
4,618
ladybug-tools/ladybug
ladybug/location.py
Location.duplicate
def duplicate(self): """Duplicate location.""" return Location(self.city, self.state, self.country, self.latitude, self.longitude, self.time_zone, self.elevation, self.station_id, self.source)
python
def duplicate(self): """Duplicate location.""" return Location(self.city, self.state, self.country, self.latitude, self.longitude, self.time_zone, self.elevation, self.station_id, self.source)
[ "def", "duplicate", "(", "self", ")", ":", "return", "Location", "(", "self", ".", "city", ",", "self", ".", "state", ",", "self", ".", "country", ",", "self", ".", "latitude", ",", "self", ".", "longitude", ",", "self", ".", "time_zone", ",", "self", ".", "elevation", ",", "self", ".", "station_id", ",", "self", ".", "source", ")" ]
Duplicate location.
[ "Duplicate", "location", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L158-L162
4,619
ladybug-tools/ladybug
ladybug/location.py
Location.ep_style_location_string
def ep_style_location_string(self): """Return EnergyPlus's location string.""" return "Site:Location,\n " + \ self.city + ',\n ' + \ str(self.latitude) + ', !Latitude\n ' + \ str(self.longitude) + ', !Longitude\n ' + \ str(self.time_zone) + ', !Time Zone\n ' + \ str(self.elevation) + '; !Elevation'
python
def ep_style_location_string(self): """Return EnergyPlus's location string.""" return "Site:Location,\n " + \ self.city + ',\n ' + \ str(self.latitude) + ', !Latitude\n ' + \ str(self.longitude) + ', !Longitude\n ' + \ str(self.time_zone) + ', !Time Zone\n ' + \ str(self.elevation) + '; !Elevation'
[ "def", "ep_style_location_string", "(", "self", ")", ":", "return", "\"Site:Location,\\n \"", "+", "self", ".", "city", "+", "',\\n '", "+", "str", "(", "self", ".", "latitude", ")", "+", "', !Latitude\\n '", "+", "str", "(", "self", ".", "longitude", ")", "+", "', !Longitude\\n '", "+", "str", "(", "self", ".", "time_zone", ")", "+", "', !Time Zone\\n '", "+", "str", "(", "self", ".", "elevation", ")", "+", "'; !Elevation'" ]
Return EnergyPlus's location string.
[ "Return", "EnergyPlus", "s", "location", "string", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L165-L172
4,620
ladybug-tools/ladybug
ladybug/epw.py
EPW.from_missing_values
def from_missing_values(cls, is_leap_year=False): """Initalize an EPW object with all data missing or empty. Note that this classmethod is intended for workflows where one plans to set all of the data within the EPW object. The EPW file written out from the use of this method is not simulate-abe or useful since all hourly data slots just possess the missing value for that data type. To obtain a EPW that is simulate-able in EnergyPlus, one must at least set the following properties: location dry_bulb_temperature dew_point_temperature relative_humidity atmospheric_station_pressure direct_normal_radiation diffuse_horizontal_radiation wind_direction wind_speed total_sky_cover opaque_sky_cover or horizontal_infrared_radiation_intensity Args: is_leap_year: A boolean to set whether the EPW object is for a leap year. Usage: from ladybug.epw import EPW from ladybug.location import Location epw = EPW.from_missing_values() epw.location = Location('Denver Golden','CO','USA',39.74,-105.18,-7.0,1829.0) epw.dry_bulb_temperature.values = [20] * 8760 """ # Initialize the class with all data missing epw_obj = cls(None) epw_obj._is_leap_year = is_leap_year epw_obj._location = Location() # create an annual analysis period analysis_period = AnalysisPeriod(is_leap_year=is_leap_year) # create headers and an empty list for each field in epw file headers = [] for field_number in xrange(epw_obj._num_of_fields): field = EPWFields.field_by_number(field_number) header = Header(data_type=field.name, unit=field.unit, analysis_period=analysis_period) headers.append(header) epw_obj._data.append([]) # fill in missing datetime values and uncertainty flags. uncertainty = '?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9' for dt in analysis_period.datetimes: hr = dt.hour if dt.hour != 0 else 24 epw_obj._data[0].append(dt.year) epw_obj._data[1].append(dt.month) epw_obj._data[2].append(dt.day) epw_obj._data[3].append(hr) epw_obj._data[4].append(0) epw_obj._data[5].append(uncertainty) # generate missing hourly data calc_length = len(analysis_period.datetimes) for field_number in xrange(6, epw_obj._num_of_fields): field = EPWFields.field_by_number(field_number) mis_val = field.missing if field.missing is not None else 0 for dt in xrange(calc_length): epw_obj._data[field_number].append(mis_val) # finally, build the data collection objects from the headers and data for i in xrange(epw_obj._num_of_fields): epw_obj._data[i] = HourlyContinuousCollection(headers[i], epw_obj._data[i]) epw_obj._is_header_loaded = True epw_obj._is_data_loaded = True return epw_obj
python
def from_missing_values(cls, is_leap_year=False): """Initalize an EPW object with all data missing or empty. Note that this classmethod is intended for workflows where one plans to set all of the data within the EPW object. The EPW file written out from the use of this method is not simulate-abe or useful since all hourly data slots just possess the missing value for that data type. To obtain a EPW that is simulate-able in EnergyPlus, one must at least set the following properties: location dry_bulb_temperature dew_point_temperature relative_humidity atmospheric_station_pressure direct_normal_radiation diffuse_horizontal_radiation wind_direction wind_speed total_sky_cover opaque_sky_cover or horizontal_infrared_radiation_intensity Args: is_leap_year: A boolean to set whether the EPW object is for a leap year. Usage: from ladybug.epw import EPW from ladybug.location import Location epw = EPW.from_missing_values() epw.location = Location('Denver Golden','CO','USA',39.74,-105.18,-7.0,1829.0) epw.dry_bulb_temperature.values = [20] * 8760 """ # Initialize the class with all data missing epw_obj = cls(None) epw_obj._is_leap_year = is_leap_year epw_obj._location = Location() # create an annual analysis period analysis_period = AnalysisPeriod(is_leap_year=is_leap_year) # create headers and an empty list for each field in epw file headers = [] for field_number in xrange(epw_obj._num_of_fields): field = EPWFields.field_by_number(field_number) header = Header(data_type=field.name, unit=field.unit, analysis_period=analysis_period) headers.append(header) epw_obj._data.append([]) # fill in missing datetime values and uncertainty flags. uncertainty = '?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9' for dt in analysis_period.datetimes: hr = dt.hour if dt.hour != 0 else 24 epw_obj._data[0].append(dt.year) epw_obj._data[1].append(dt.month) epw_obj._data[2].append(dt.day) epw_obj._data[3].append(hr) epw_obj._data[4].append(0) epw_obj._data[5].append(uncertainty) # generate missing hourly data calc_length = len(analysis_period.datetimes) for field_number in xrange(6, epw_obj._num_of_fields): field = EPWFields.field_by_number(field_number) mis_val = field.missing if field.missing is not None else 0 for dt in xrange(calc_length): epw_obj._data[field_number].append(mis_val) # finally, build the data collection objects from the headers and data for i in xrange(epw_obj._num_of_fields): epw_obj._data[i] = HourlyContinuousCollection(headers[i], epw_obj._data[i]) epw_obj._is_header_loaded = True epw_obj._is_data_loaded = True return epw_obj
[ "def", "from_missing_values", "(", "cls", ",", "is_leap_year", "=", "False", ")", ":", "# Initialize the class with all data missing", "epw_obj", "=", "cls", "(", "None", ")", "epw_obj", ".", "_is_leap_year", "=", "is_leap_year", "epw_obj", ".", "_location", "=", "Location", "(", ")", "# create an annual analysis period", "analysis_period", "=", "AnalysisPeriod", "(", "is_leap_year", "=", "is_leap_year", ")", "# create headers and an empty list for each field in epw file", "headers", "=", "[", "]", "for", "field_number", "in", "xrange", "(", "epw_obj", ".", "_num_of_fields", ")", ":", "field", "=", "EPWFields", ".", "field_by_number", "(", "field_number", ")", "header", "=", "Header", "(", "data_type", "=", "field", ".", "name", ",", "unit", "=", "field", ".", "unit", ",", "analysis_period", "=", "analysis_period", ")", "headers", ".", "append", "(", "header", ")", "epw_obj", ".", "_data", ".", "append", "(", "[", "]", ")", "# fill in missing datetime values and uncertainty flags.", "uncertainty", "=", "'?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9'", "for", "dt", "in", "analysis_period", ".", "datetimes", ":", "hr", "=", "dt", ".", "hour", "if", "dt", ".", "hour", "!=", "0", "else", "24", "epw_obj", ".", "_data", "[", "0", "]", ".", "append", "(", "dt", ".", "year", ")", "epw_obj", ".", "_data", "[", "1", "]", ".", "append", "(", "dt", ".", "month", ")", "epw_obj", ".", "_data", "[", "2", "]", ".", "append", "(", "dt", ".", "day", ")", "epw_obj", ".", "_data", "[", "3", "]", ".", "append", "(", "hr", ")", "epw_obj", ".", "_data", "[", "4", "]", ".", "append", "(", "0", ")", "epw_obj", ".", "_data", "[", "5", "]", ".", "append", "(", "uncertainty", ")", "# generate missing hourly data", "calc_length", "=", "len", "(", "analysis_period", ".", "datetimes", ")", "for", "field_number", "in", "xrange", "(", "6", ",", "epw_obj", ".", "_num_of_fields", ")", ":", "field", "=", "EPWFields", ".", "field_by_number", "(", "field_number", ")", "mis_val", "=", "field", ".", "missing", "if", "field", ".", "missing", "is", "not", "None", "else", "0", "for", "dt", "in", "xrange", "(", "calc_length", ")", ":", "epw_obj", ".", "_data", "[", "field_number", "]", ".", "append", "(", "mis_val", ")", "# finally, build the data collection objects from the headers and data", "for", "i", "in", "xrange", "(", "epw_obj", ".", "_num_of_fields", ")", ":", "epw_obj", ".", "_data", "[", "i", "]", "=", "HourlyContinuousCollection", "(", "headers", "[", "i", "]", ",", "epw_obj", ".", "_data", "[", "i", "]", ")", "epw_obj", ".", "_is_header_loaded", "=", "True", "epw_obj", ".", "_is_data_loaded", "=", "True", "return", "epw_obj" ]
Initalize an EPW object with all data missing or empty. Note that this classmethod is intended for workflows where one plans to set all of the data within the EPW object. The EPW file written out from the use of this method is not simulate-abe or useful since all hourly data slots just possess the missing value for that data type. To obtain a EPW that is simulate-able in EnergyPlus, one must at least set the following properties: location dry_bulb_temperature dew_point_temperature relative_humidity atmospheric_station_pressure direct_normal_radiation diffuse_horizontal_radiation wind_direction wind_speed total_sky_cover opaque_sky_cover or horizontal_infrared_radiation_intensity Args: is_leap_year: A boolean to set whether the EPW object is for a leap year. Usage: from ladybug.epw import EPW from ladybug.location import Location epw = EPW.from_missing_values() epw.location = Location('Denver Golden','CO','USA',39.74,-105.18,-7.0,1829.0) epw.dry_bulb_temperature.values = [20] * 8760
[ "Initalize", "an", "EPW", "object", "with", "all", "data", "missing", "or", "empty", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L105-L178
4,621
ladybug-tools/ladybug
ladybug/epw.py
EPW.from_json
def from_json(cls, data): """ Create EPW from json dictionary. Args: data: { "location": {} , // ladybug location schema "data_collections": [], // list of hourly annual hourly data collection schemas for each of the 35 fields within the EPW file. "metadata": {}, // dict of metadata assigned to all data collections "heating_dict": {}, // dict containing heating design conditions "cooling_dict": {}, // dict containing cooling design conditions "extremes_dict": {}, // dict containing extreme design conditions "extreme_hot_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying extreme hot weeks. "extreme_cold_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying extreme cold weeks. "typical_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying typical weeks. "monthly_ground_temps": {}, // dict with keys as floats signifying depths in meters below ground and values of monthly collection schema "is_ip": Boolean // denote whether the data is in IP units "is_leap_year": Boolean, // denote whether data is for a leap year "daylight_savings_start": 0, // signify when daylight savings starts or 0 for no daylight savings "daylight_savings_end" 0, // signify when daylight savings ends or 0 for no daylight savings "comments_1": String, // epw comments "comments_2": String // epw comments } """ # Initialize the class with all data missing epw_obj = cls(None) epw_obj._is_header_loaded = True epw_obj._is_data_loaded = True # Check required and optional keys required_keys = ('location', 'data_collections') option_keys_dict = ('metadata', 'heating_dict', 'cooling_dict', 'extremes_dict', 'extreme_hot_weeks', 'extreme_cold_weeks', 'typical_weeks', 'monthly_ground_temps') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) assert len(data['data_collections']) == epw_obj._num_of_fields, \ 'The number of data_collections must be {}. Got {}.'.format( epw_obj._num_of_fields, len(data['data_collections'])) for key in option_keys_dict: if key not in data: data[key] = {} # Set the required properties of the EPW object. epw_obj._location = Location.from_json(data['location']) epw_obj._data = [HourlyContinuousCollection.from_json(dc) for dc in data['data_collections']] if 'is_leap_year' in data: epw_obj._is_leap_year = data['is_leap_year'] if 'is_ip' in data: epw_obj._is_ip = data['is_ip'] # Check that the required properties all make sense. for dc in epw_obj._data: assert isinstance(dc, HourlyContinuousCollection), 'data_collections must ' \ 'be of HourlyContinuousCollection schema. Got {}'.format(type(dc)) assert dc.header.analysis_period.is_annual, 'data_collections ' \ 'analysis_period must be annual.' assert dc.header.analysis_period.is_leap_year == epw_obj._is_leap_year, \ 'data_collections is_leap_year is not aligned with that of the EPW.' # Set all of the header properties if they exist in the dictionary. epw_obj._metadata = data['metadata'] epw_obj.heating_design_condition_dictionary = data['heating_dict'] epw_obj.cooling_design_condition_dictionary = data['cooling_dict'] epw_obj.extreme_design_condition_dictionary = data['extremes_dict'] def _dejson(parent_dict, obj): new_dict = {} for key, val in parent_dict.items(): new_dict[key] = obj.from_json(val) return new_dict epw_obj.extreme_hot_weeks = _dejson(data['extreme_hot_weeks'], AnalysisPeriod) epw_obj.extreme_cold_weeks = _dejson(data['extreme_cold_weeks'], AnalysisPeriod) epw_obj.typical_weeks = _dejson(data['typical_weeks'], AnalysisPeriod) epw_obj.monthly_ground_temperature = _dejson( data['monthly_ground_temps'], MonthlyCollection) if 'daylight_savings_start' in data: epw_obj.daylight_savings_start = data['daylight_savings_start'] if 'daylight_savings_end' in data: epw_obj.daylight_savings_end = data['daylight_savings_end'] if 'comments_1' in data: epw_obj.comments_1 = data['comments_1'] if 'comments_2' in data: epw_obj.comments_2 = data['comments_2'] return epw_obj
python
def from_json(cls, data): """ Create EPW from json dictionary. Args: data: { "location": {} , // ladybug location schema "data_collections": [], // list of hourly annual hourly data collection schemas for each of the 35 fields within the EPW file. "metadata": {}, // dict of metadata assigned to all data collections "heating_dict": {}, // dict containing heating design conditions "cooling_dict": {}, // dict containing cooling design conditions "extremes_dict": {}, // dict containing extreme design conditions "extreme_hot_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying extreme hot weeks. "extreme_cold_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying extreme cold weeks. "typical_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying typical weeks. "monthly_ground_temps": {}, // dict with keys as floats signifying depths in meters below ground and values of monthly collection schema "is_ip": Boolean // denote whether the data is in IP units "is_leap_year": Boolean, // denote whether data is for a leap year "daylight_savings_start": 0, // signify when daylight savings starts or 0 for no daylight savings "daylight_savings_end" 0, // signify when daylight savings ends or 0 for no daylight savings "comments_1": String, // epw comments "comments_2": String // epw comments } """ # Initialize the class with all data missing epw_obj = cls(None) epw_obj._is_header_loaded = True epw_obj._is_data_loaded = True # Check required and optional keys required_keys = ('location', 'data_collections') option_keys_dict = ('metadata', 'heating_dict', 'cooling_dict', 'extremes_dict', 'extreme_hot_weeks', 'extreme_cold_weeks', 'typical_weeks', 'monthly_ground_temps') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) assert len(data['data_collections']) == epw_obj._num_of_fields, \ 'The number of data_collections must be {}. Got {}.'.format( epw_obj._num_of_fields, len(data['data_collections'])) for key in option_keys_dict: if key not in data: data[key] = {} # Set the required properties of the EPW object. epw_obj._location = Location.from_json(data['location']) epw_obj._data = [HourlyContinuousCollection.from_json(dc) for dc in data['data_collections']] if 'is_leap_year' in data: epw_obj._is_leap_year = data['is_leap_year'] if 'is_ip' in data: epw_obj._is_ip = data['is_ip'] # Check that the required properties all make sense. for dc in epw_obj._data: assert isinstance(dc, HourlyContinuousCollection), 'data_collections must ' \ 'be of HourlyContinuousCollection schema. Got {}'.format(type(dc)) assert dc.header.analysis_period.is_annual, 'data_collections ' \ 'analysis_period must be annual.' assert dc.header.analysis_period.is_leap_year == epw_obj._is_leap_year, \ 'data_collections is_leap_year is not aligned with that of the EPW.' # Set all of the header properties if they exist in the dictionary. epw_obj._metadata = data['metadata'] epw_obj.heating_design_condition_dictionary = data['heating_dict'] epw_obj.cooling_design_condition_dictionary = data['cooling_dict'] epw_obj.extreme_design_condition_dictionary = data['extremes_dict'] def _dejson(parent_dict, obj): new_dict = {} for key, val in parent_dict.items(): new_dict[key] = obj.from_json(val) return new_dict epw_obj.extreme_hot_weeks = _dejson(data['extreme_hot_weeks'], AnalysisPeriod) epw_obj.extreme_cold_weeks = _dejson(data['extreme_cold_weeks'], AnalysisPeriod) epw_obj.typical_weeks = _dejson(data['typical_weeks'], AnalysisPeriod) epw_obj.monthly_ground_temperature = _dejson( data['monthly_ground_temps'], MonthlyCollection) if 'daylight_savings_start' in data: epw_obj.daylight_savings_start = data['daylight_savings_start'] if 'daylight_savings_end' in data: epw_obj.daylight_savings_end = data['daylight_savings_end'] if 'comments_1' in data: epw_obj.comments_1 = data['comments_1'] if 'comments_2' in data: epw_obj.comments_2 = data['comments_2'] return epw_obj
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "# Initialize the class with all data missing", "epw_obj", "=", "cls", "(", "None", ")", "epw_obj", ".", "_is_header_loaded", "=", "True", "epw_obj", ".", "_is_data_loaded", "=", "True", "# Check required and optional keys", "required_keys", "=", "(", "'location'", ",", "'data_collections'", ")", "option_keys_dict", "=", "(", "'metadata'", ",", "'heating_dict'", ",", "'cooling_dict'", ",", "'extremes_dict'", ",", "'extreme_hot_weeks'", ",", "'extreme_cold_weeks'", ",", "'typical_weeks'", ",", "'monthly_ground_temps'", ")", "for", "key", "in", "required_keys", ":", "assert", "key", "in", "data", ",", "'Required key \"{}\" is missing!'", ".", "format", "(", "key", ")", "assert", "len", "(", "data", "[", "'data_collections'", "]", ")", "==", "epw_obj", ".", "_num_of_fields", ",", "'The number of data_collections must be {}. Got {}.'", ".", "format", "(", "epw_obj", ".", "_num_of_fields", ",", "len", "(", "data", "[", "'data_collections'", "]", ")", ")", "for", "key", "in", "option_keys_dict", ":", "if", "key", "not", "in", "data", ":", "data", "[", "key", "]", "=", "{", "}", "# Set the required properties of the EPW object.", "epw_obj", ".", "_location", "=", "Location", ".", "from_json", "(", "data", "[", "'location'", "]", ")", "epw_obj", ".", "_data", "=", "[", "HourlyContinuousCollection", ".", "from_json", "(", "dc", ")", "for", "dc", "in", "data", "[", "'data_collections'", "]", "]", "if", "'is_leap_year'", "in", "data", ":", "epw_obj", ".", "_is_leap_year", "=", "data", "[", "'is_leap_year'", "]", "if", "'is_ip'", "in", "data", ":", "epw_obj", ".", "_is_ip", "=", "data", "[", "'is_ip'", "]", "# Check that the required properties all make sense.", "for", "dc", "in", "epw_obj", ".", "_data", ":", "assert", "isinstance", "(", "dc", ",", "HourlyContinuousCollection", ")", ",", "'data_collections must '", "'be of HourlyContinuousCollection schema. Got {}'", ".", "format", "(", "type", "(", "dc", ")", ")", "assert", "dc", ".", "header", ".", "analysis_period", ".", "is_annual", ",", "'data_collections '", "'analysis_period must be annual.'", "assert", "dc", ".", "header", ".", "analysis_period", ".", "is_leap_year", "==", "epw_obj", ".", "_is_leap_year", ",", "'data_collections is_leap_year is not aligned with that of the EPW.'", "# Set all of the header properties if they exist in the dictionary.", "epw_obj", ".", "_metadata", "=", "data", "[", "'metadata'", "]", "epw_obj", ".", "heating_design_condition_dictionary", "=", "data", "[", "'heating_dict'", "]", "epw_obj", ".", "cooling_design_condition_dictionary", "=", "data", "[", "'cooling_dict'", "]", "epw_obj", ".", "extreme_design_condition_dictionary", "=", "data", "[", "'extremes_dict'", "]", "def", "_dejson", "(", "parent_dict", ",", "obj", ")", ":", "new_dict", "=", "{", "}", "for", "key", ",", "val", "in", "parent_dict", ".", "items", "(", ")", ":", "new_dict", "[", "key", "]", "=", "obj", ".", "from_json", "(", "val", ")", "return", "new_dict", "epw_obj", ".", "extreme_hot_weeks", "=", "_dejson", "(", "data", "[", "'extreme_hot_weeks'", "]", ",", "AnalysisPeriod", ")", "epw_obj", ".", "extreme_cold_weeks", "=", "_dejson", "(", "data", "[", "'extreme_cold_weeks'", "]", ",", "AnalysisPeriod", ")", "epw_obj", ".", "typical_weeks", "=", "_dejson", "(", "data", "[", "'typical_weeks'", "]", ",", "AnalysisPeriod", ")", "epw_obj", ".", "monthly_ground_temperature", "=", "_dejson", "(", "data", "[", "'monthly_ground_temps'", "]", ",", "MonthlyCollection", ")", "if", "'daylight_savings_start'", "in", "data", ":", "epw_obj", ".", "daylight_savings_start", "=", "data", "[", "'daylight_savings_start'", "]", "if", "'daylight_savings_end'", "in", "data", ":", "epw_obj", ".", "daylight_savings_end", "=", "data", "[", "'daylight_savings_end'", "]", "if", "'comments_1'", "in", "data", ":", "epw_obj", ".", "comments_1", "=", "data", "[", "'comments_1'", "]", "if", "'comments_2'", "in", "data", ":", "epw_obj", ".", "comments_2", "=", "data", "[", "'comments_2'", "]", "return", "epw_obj" ]
Create EPW from json dictionary. Args: data: { "location": {} , // ladybug location schema "data_collections": [], // list of hourly annual hourly data collection schemas for each of the 35 fields within the EPW file. "metadata": {}, // dict of metadata assigned to all data collections "heating_dict": {}, // dict containing heating design conditions "cooling_dict": {}, // dict containing cooling design conditions "extremes_dict": {}, // dict containing extreme design conditions "extreme_hot_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying extreme hot weeks. "extreme_cold_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying extreme cold weeks. "typical_weeks": {}, // dict with values of week-long ladybug analysis period schemas signifying typical weeks. "monthly_ground_temps": {}, // dict with keys as floats signifying depths in meters below ground and values of monthly collection schema "is_ip": Boolean // denote whether the data is in IP units "is_leap_year": Boolean, // denote whether data is for a leap year "daylight_savings_start": 0, // signify when daylight savings starts or 0 for no daylight savings "daylight_savings_end" 0, // signify when daylight savings ends or 0 for no daylight savings "comments_1": String, // epw comments "comments_2": String // epw comments }
[ "Create", "EPW", "from", "json", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L181-L274
4,622
ladybug-tools/ladybug
ladybug/epw.py
EPW.annual_cooling_design_day_010
def annual_cooling_design_day_010(self): """A design day object representing the annual 1.0% cooling design day.""" self._load_header_check() if bool(self._cooling_dict) is True: avg_press = self.atmospheric_station_pressure.average avg_press = None if avg_press == 999999 else avg_press return DesignDay.from_ashrae_dict_cooling( self._cooling_dict, self.location, True, avg_press) else: return None
python
def annual_cooling_design_day_010(self): """A design day object representing the annual 1.0% cooling design day.""" self._load_header_check() if bool(self._cooling_dict) is True: avg_press = self.atmospheric_station_pressure.average avg_press = None if avg_press == 999999 else avg_press return DesignDay.from_ashrae_dict_cooling( self._cooling_dict, self.location, True, avg_press) else: return None
[ "def", "annual_cooling_design_day_010", "(", "self", ")", ":", "self", ".", "_load_header_check", "(", ")", "if", "bool", "(", "self", ".", "_cooling_dict", ")", "is", "True", ":", "avg_press", "=", "self", ".", "atmospheric_station_pressure", ".", "average", "avg_press", "=", "None", "if", "avg_press", "==", "999999", "else", "avg_press", "return", "DesignDay", ".", "from_ashrae_dict_cooling", "(", "self", ".", "_cooling_dict", ",", "self", ".", "location", ",", "True", ",", "avg_press", ")", "else", ":", "return", "None" ]
A design day object representing the annual 1.0% cooling design day.
[ "A", "design", "day", "object", "representing", "the", "annual", "1", ".", "0%", "cooling", "design", "day", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L364-L373
4,623
ladybug-tools/ladybug
ladybug/epw.py
EPW._des_dict_check
def _des_dict_check(self, des_dict, req_keys, cond_name): """Check if an input design condition dictionary is acceptable.""" assert isinstance(des_dict, dict), '{}' \ ' must be a dictionary. Got {}.'.format(cond_name, type(des_dict)) if bool(des_dict) is True: input_keys = list(des_dict.keys()) for key in req_keys: assert key in input_keys, 'Required key "{}" was not found in ' \ '{}'.format(key, cond_name)
python
def _des_dict_check(self, des_dict, req_keys, cond_name): """Check if an input design condition dictionary is acceptable.""" assert isinstance(des_dict, dict), '{}' \ ' must be a dictionary. Got {}.'.format(cond_name, type(des_dict)) if bool(des_dict) is True: input_keys = list(des_dict.keys()) for key in req_keys: assert key in input_keys, 'Required key "{}" was not found in ' \ '{}'.format(key, cond_name)
[ "def", "_des_dict_check", "(", "self", ",", "des_dict", ",", "req_keys", ",", "cond_name", ")", ":", "assert", "isinstance", "(", "des_dict", ",", "dict", ")", ",", "'{}'", "' must be a dictionary. Got {}.'", ".", "format", "(", "cond_name", ",", "type", "(", "des_dict", ")", ")", "if", "bool", "(", "des_dict", ")", "is", "True", ":", "input_keys", "=", "list", "(", "des_dict", ".", "keys", "(", ")", ")", "for", "key", "in", "req_keys", ":", "assert", "key", "in", "input_keys", ",", "'Required key \"{}\" was not found in '", "'{}'", ".", "format", "(", "key", ",", "cond_name", ")" ]
Check if an input design condition dictionary is acceptable.
[ "Check", "if", "an", "input", "design", "condition", "dictionary", "is", "acceptable", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L482-L490
4,624
ladybug-tools/ladybug
ladybug/epw.py
EPW._format_week
def _format_week(self, name, type, a_per): """Format an AnalysisPeriod into string for the EPW header.""" return '{},{},{}/{},{}/{}'.format(name, type, a_per.st_month, a_per.st_day, a_per.end_month, a_per.end_day)
python
def _format_week(self, name, type, a_per): """Format an AnalysisPeriod into string for the EPW header.""" return '{},{},{}/{},{}/{}'.format(name, type, a_per.st_month, a_per.st_day, a_per.end_month, a_per.end_day)
[ "def", "_format_week", "(", "self", ",", "name", ",", "type", ",", "a_per", ")", ":", "return", "'{},{},{}/{},{}/{}'", ".", "format", "(", "name", ",", "type", ",", "a_per", ".", "st_month", ",", "a_per", ".", "st_day", ",", "a_per", ".", "end_month", ",", "a_per", ".", "end_day", ")" ]
Format an AnalysisPeriod into string for the EPW header.
[ "Format", "an", "AnalysisPeriod", "into", "string", "for", "the", "EPW", "header", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L709-L712
4,625
ladybug-tools/ladybug
ladybug/epw.py
EPW._format_grndt
def _format_grndt(self, data_c): """Format monthly ground data collection into string for the EPW header.""" monthly_str = '{},{},{},{}'.format( data_c.header.metadata['soil conductivity'], data_c.header.metadata['soil density'], data_c.header.metadata['soil specific heat'], ','.join(['%.2f' % x for x in data_c.values])) return monthly_str
python
def _format_grndt(self, data_c): """Format monthly ground data collection into string for the EPW header.""" monthly_str = '{},{},{},{}'.format( data_c.header.metadata['soil conductivity'], data_c.header.metadata['soil density'], data_c.header.metadata['soil specific heat'], ','.join(['%.2f' % x for x in data_c.values])) return monthly_str
[ "def", "_format_grndt", "(", "self", ",", "data_c", ")", ":", "monthly_str", "=", "'{},{},{},{}'", ".", "format", "(", "data_c", ".", "header", ".", "metadata", "[", "'soil conductivity'", "]", ",", "data_c", ".", "header", ".", "metadata", "[", "'soil density'", "]", ",", "data_c", ".", "header", ".", "metadata", "[", "'soil specific heat'", "]", ",", "','", ".", "join", "(", "[", "'%.2f'", "%", "x", "for", "x", "in", "data_c", ".", "values", "]", ")", ")", "return", "monthly_str" ]
Format monthly ground data collection into string for the EPW header.
[ "Format", "monthly", "ground", "data", "collection", "into", "string", "for", "the", "EPW", "header", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L714-L721
4,626
ladybug-tools/ladybug
ladybug/epw.py
EPW.save
def save(self, file_path): """Save epw object as an epw file. args: file_path: A string representing the path to write the epw file to. """ # load data if it's not loaded convert to SI if it is in IP if not self.is_data_loaded: self._import_data() originally_ip = False if self.is_ip is True: self.convert_to_si() originally_ip = True # write the file lines = self.header try: # if the first value is at 1AM, move first item to end position for field in xrange(0, self._num_of_fields): point_in_time = self._data[field].header.data_type.point_in_time if point_in_time is True: first_hour = self._data[field]._values.pop(0) self._data[field]._values.append(first_hour) annual_a_per = AnalysisPeriod(is_leap_year=self.is_leap_year) for hour in xrange(0, len(annual_a_per.datetimes)): line = [] for field in xrange(0, self._num_of_fields): line.append(str(self._data[field]._values[hour])) lines.append(",".join(line) + "\n") except IndexError: # cleaning up length_error_msg = 'Data length is not for a full year and cannot be ' + \ 'saved as an EPW file.' raise ValueError(length_error_msg) else: file_data = ''.join(lines) write_to_file(file_path, file_data, True) finally: del(lines) # move last item to start position for fields on the hour for field in xrange(0, self._num_of_fields): point_in_time = self._data[field].header.data_type.point_in_time if point_in_time is True: last_hour = self._data[field]._values.pop() self._data[field]._values.insert(0, last_hour) if originally_ip is True: self.convert_to_ip() return file_path
python
def save(self, file_path): """Save epw object as an epw file. args: file_path: A string representing the path to write the epw file to. """ # load data if it's not loaded convert to SI if it is in IP if not self.is_data_loaded: self._import_data() originally_ip = False if self.is_ip is True: self.convert_to_si() originally_ip = True # write the file lines = self.header try: # if the first value is at 1AM, move first item to end position for field in xrange(0, self._num_of_fields): point_in_time = self._data[field].header.data_type.point_in_time if point_in_time is True: first_hour = self._data[field]._values.pop(0) self._data[field]._values.append(first_hour) annual_a_per = AnalysisPeriod(is_leap_year=self.is_leap_year) for hour in xrange(0, len(annual_a_per.datetimes)): line = [] for field in xrange(0, self._num_of_fields): line.append(str(self._data[field]._values[hour])) lines.append(",".join(line) + "\n") except IndexError: # cleaning up length_error_msg = 'Data length is not for a full year and cannot be ' + \ 'saved as an EPW file.' raise ValueError(length_error_msg) else: file_data = ''.join(lines) write_to_file(file_path, file_data, True) finally: del(lines) # move last item to start position for fields on the hour for field in xrange(0, self._num_of_fields): point_in_time = self._data[field].header.data_type.point_in_time if point_in_time is True: last_hour = self._data[field]._values.pop() self._data[field]._values.insert(0, last_hour) if originally_ip is True: self.convert_to_ip() return file_path
[ "def", "save", "(", "self", ",", "file_path", ")", ":", "# load data if it's not loaded convert to SI if it is in IP", "if", "not", "self", ".", "is_data_loaded", ":", "self", ".", "_import_data", "(", ")", "originally_ip", "=", "False", "if", "self", ".", "is_ip", "is", "True", ":", "self", ".", "convert_to_si", "(", ")", "originally_ip", "=", "True", "# write the file", "lines", "=", "self", ".", "header", "try", ":", "# if the first value is at 1AM, move first item to end position", "for", "field", "in", "xrange", "(", "0", ",", "self", ".", "_num_of_fields", ")", ":", "point_in_time", "=", "self", ".", "_data", "[", "field", "]", ".", "header", ".", "data_type", ".", "point_in_time", "if", "point_in_time", "is", "True", ":", "first_hour", "=", "self", ".", "_data", "[", "field", "]", ".", "_values", ".", "pop", "(", "0", ")", "self", ".", "_data", "[", "field", "]", ".", "_values", ".", "append", "(", "first_hour", ")", "annual_a_per", "=", "AnalysisPeriod", "(", "is_leap_year", "=", "self", ".", "is_leap_year", ")", "for", "hour", "in", "xrange", "(", "0", ",", "len", "(", "annual_a_per", ".", "datetimes", ")", ")", ":", "line", "=", "[", "]", "for", "field", "in", "xrange", "(", "0", ",", "self", ".", "_num_of_fields", ")", ":", "line", ".", "append", "(", "str", "(", "self", ".", "_data", "[", "field", "]", ".", "_values", "[", "hour", "]", ")", ")", "lines", ".", "append", "(", "\",\"", ".", "join", "(", "line", ")", "+", "\"\\n\"", ")", "except", "IndexError", ":", "# cleaning up", "length_error_msg", "=", "'Data length is not for a full year and cannot be '", "+", "'saved as an EPW file.'", "raise", "ValueError", "(", "length_error_msg", ")", "else", ":", "file_data", "=", "''", ".", "join", "(", "lines", ")", "write_to_file", "(", "file_path", ",", "file_data", ",", "True", ")", "finally", ":", "del", "(", "lines", ")", "# move last item to start position for fields on the hour", "for", "field", "in", "xrange", "(", "0", ",", "self", ".", "_num_of_fields", ")", ":", "point_in_time", "=", "self", ".", "_data", "[", "field", "]", ".", "header", ".", "data_type", ".", "point_in_time", "if", "point_in_time", "is", "True", ":", "last_hour", "=", "self", ".", "_data", "[", "field", "]", ".", "_values", ".", "pop", "(", ")", "self", ".", "_data", "[", "field", "]", ".", "_values", ".", "insert", "(", "0", ",", "last_hour", ")", "if", "originally_ip", "is", "True", ":", "self", ".", "convert_to_ip", "(", ")", "return", "file_path" ]
Save epw object as an epw file. args: file_path: A string representing the path to write the epw file to.
[ "Save", "epw", "object", "as", "an", "epw", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L723-L773
4,627
ladybug-tools/ladybug
ladybug/epw.py
EPW.convert_to_ip
def convert_to_ip(self): """Convert all Data Collections of this EPW object to IP units. This is useful when one knows that all graphics produced from this EPW should be in Imperial units.""" if not self.is_data_loaded: self._import_data() if self.is_ip is False: for coll in self._data: coll.convert_to_ip() self._is_ip = True
python
def convert_to_ip(self): """Convert all Data Collections of this EPW object to IP units. This is useful when one knows that all graphics produced from this EPW should be in Imperial units.""" if not self.is_data_loaded: self._import_data() if self.is_ip is False: for coll in self._data: coll.convert_to_ip() self._is_ip = True
[ "def", "convert_to_ip", "(", "self", ")", ":", "if", "not", "self", ".", "is_data_loaded", ":", "self", ".", "_import_data", "(", ")", "if", "self", ".", "is_ip", "is", "False", ":", "for", "coll", "in", "self", ".", "_data", ":", "coll", ".", "convert_to_ip", "(", ")", "self", ".", "_is_ip", "=", "True" ]
Convert all Data Collections of this EPW object to IP units. This is useful when one knows that all graphics produced from this EPW should be in Imperial units.
[ "Convert", "all", "Data", "Collections", "of", "this", "EPW", "object", "to", "IP", "units", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L775-L785
4,628
ladybug-tools/ladybug
ladybug/epw.py
EPW._get_data_by_field
def _get_data_by_field(self, field_number): """Return a data field by field number. This is a useful method to get the values for fields that Ladybug currently doesn't import by default. You can find list of fields by typing EPWFields.fields Args: field_number: a value between 0 to 34 for different available epw fields. Returns: An annual Ladybug list """ if not self.is_data_loaded: self._import_data() # check input data if not 0 <= field_number < self._num_of_fields: raise ValueError("Field number should be between 0-%d" % self._num_of_fields) return self._data[field_number]
python
def _get_data_by_field(self, field_number): """Return a data field by field number. This is a useful method to get the values for fields that Ladybug currently doesn't import by default. You can find list of fields by typing EPWFields.fields Args: field_number: a value between 0 to 34 for different available epw fields. Returns: An annual Ladybug list """ if not self.is_data_loaded: self._import_data() # check input data if not 0 <= field_number < self._num_of_fields: raise ValueError("Field number should be between 0-%d" % self._num_of_fields) return self._data[field_number]
[ "def", "_get_data_by_field", "(", "self", ",", "field_number", ")", ":", "if", "not", "self", ".", "is_data_loaded", ":", "self", ".", "_import_data", "(", ")", "# check input data", "if", "not", "0", "<=", "field_number", "<", "self", ".", "_num_of_fields", ":", "raise", "ValueError", "(", "\"Field number should be between 0-%d\"", "%", "self", ".", "_num_of_fields", ")", "return", "self", ".", "_data", "[", "field_number", "]" ]
Return a data field by field number. This is a useful method to get the values for fields that Ladybug currently doesn't import by default. You can find list of fields by typing EPWFields.fields Args: field_number: a value between 0 to 34 for different available epw fields. Returns: An annual Ladybug list
[ "Return", "a", "data", "field", "by", "field", "number", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L800-L820
4,629
ladybug-tools/ladybug
ladybug/epw.py
EPW.sky_temperature
def sky_temperature(self): """Return annual Sky Temperature as a Ladybug Data Collection. This value in degrees Celcius is derived from the Horizontal Infrared Radiation Intensity in Wh/m2. It represents the long wave radiant temperature of the sky Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference /climate-calculations.html#energyplus-sky-temperature-calculation """ # create sky temperature header sky_temp_header = Header(data_type=temperature.SkyTemperature(), unit='C', analysis_period=AnalysisPeriod(), metadata=self._metadata) # calculate sy temperature for each hour horiz_ir = self._get_data_by_field(12).values sky_temp_data = [calc_sky_temperature(hir) for hir in horiz_ir] return HourlyContinuousCollection(sky_temp_header, sky_temp_data)
python
def sky_temperature(self): """Return annual Sky Temperature as a Ladybug Data Collection. This value in degrees Celcius is derived from the Horizontal Infrared Radiation Intensity in Wh/m2. It represents the long wave radiant temperature of the sky Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference /climate-calculations.html#energyplus-sky-temperature-calculation """ # create sky temperature header sky_temp_header = Header(data_type=temperature.SkyTemperature(), unit='C', analysis_period=AnalysisPeriod(), metadata=self._metadata) # calculate sy temperature for each hour horiz_ir = self._get_data_by_field(12).values sky_temp_data = [calc_sky_temperature(hir) for hir in horiz_ir] return HourlyContinuousCollection(sky_temp_header, sky_temp_data)
[ "def", "sky_temperature", "(", "self", ")", ":", "# create sky temperature header", "sky_temp_header", "=", "Header", "(", "data_type", "=", "temperature", ".", "SkyTemperature", "(", ")", ",", "unit", "=", "'C'", ",", "analysis_period", "=", "AnalysisPeriod", "(", ")", ",", "metadata", "=", "self", ".", "_metadata", ")", "# calculate sy temperature for each hour", "horiz_ir", "=", "self", ".", "_get_data_by_field", "(", "12", ")", ".", "values", "sky_temp_data", "=", "[", "calc_sky_temperature", "(", "hir", ")", "for", "hir", "in", "horiz_ir", "]", "return", "HourlyContinuousCollection", "(", "sky_temp_header", ",", "sky_temp_data", ")" ]
Return annual Sky Temperature as a Ladybug Data Collection. This value in degrees Celcius is derived from the Horizontal Infrared Radiation Intensity in Wh/m2. It represents the long wave radiant temperature of the sky Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference /climate-calculations.html#energyplus-sky-temperature-calculation
[ "Return", "annual", "Sky", "Temperature", "as", "a", "Ladybug", "Data", "Collection", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L1275-L1292
4,630
ladybug-tools/ladybug
ladybug/epw.py
EPW.to_wea
def to_wea(self, file_path, hoys=None): """Write an wea file from the epw file. WEA carries radiation values from epw. Gendaymtx uses these values to generate the sky. For an annual analysis it is identical to using epw2wea. args: file_path: Full file path for output file. hoys: List of hours of the year. Default is 0-8759. """ hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes)) if not file_path.lower().endswith('.wea'): file_path += '.wea' originally_ip = False if self.is_ip is True: self.convert_to_si() originally_ip = True # write header lines = [self._get_wea_header()] # write values datetimes = self.direct_normal_radiation.datetimes for hoy in hoys: dir_rad = self.direct_normal_radiation[hoy] dif_rad = self.diffuse_horizontal_radiation[hoy] line = "%d %d %.3f %d %d\n" \ % (datetimes[hoy].month, datetimes[hoy].day, datetimes[hoy].hour + 0.5, dir_rad, dif_rad) lines.append(line) file_data = ''.join(lines) write_to_file(file_path, file_data, True) if originally_ip is True: self.convert_to_ip() return file_path
python
def to_wea(self, file_path, hoys=None): """Write an wea file from the epw file. WEA carries radiation values from epw. Gendaymtx uses these values to generate the sky. For an annual analysis it is identical to using epw2wea. args: file_path: Full file path for output file. hoys: List of hours of the year. Default is 0-8759. """ hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes)) if not file_path.lower().endswith('.wea'): file_path += '.wea' originally_ip = False if self.is_ip is True: self.convert_to_si() originally_ip = True # write header lines = [self._get_wea_header()] # write values datetimes = self.direct_normal_radiation.datetimes for hoy in hoys: dir_rad = self.direct_normal_radiation[hoy] dif_rad = self.diffuse_horizontal_radiation[hoy] line = "%d %d %.3f %d %d\n" \ % (datetimes[hoy].month, datetimes[hoy].day, datetimes[hoy].hour + 0.5, dir_rad, dif_rad) lines.append(line) file_data = ''.join(lines) write_to_file(file_path, file_data, True) if originally_ip is True: self.convert_to_ip() return file_path
[ "def", "to_wea", "(", "self", ",", "file_path", ",", "hoys", "=", "None", ")", ":", "hoys", "=", "hoys", "or", "xrange", "(", "len", "(", "self", ".", "direct_normal_radiation", ".", "datetimes", ")", ")", "if", "not", "file_path", ".", "lower", "(", ")", ".", "endswith", "(", "'.wea'", ")", ":", "file_path", "+=", "'.wea'", "originally_ip", "=", "False", "if", "self", ".", "is_ip", "is", "True", ":", "self", ".", "convert_to_si", "(", ")", "originally_ip", "=", "True", "# write header", "lines", "=", "[", "self", ".", "_get_wea_header", "(", ")", "]", "# write values", "datetimes", "=", "self", ".", "direct_normal_radiation", ".", "datetimes", "for", "hoy", "in", "hoys", ":", "dir_rad", "=", "self", ".", "direct_normal_radiation", "[", "hoy", "]", "dif_rad", "=", "self", ".", "diffuse_horizontal_radiation", "[", "hoy", "]", "line", "=", "\"%d %d %.3f %d %d\\n\"", "%", "(", "datetimes", "[", "hoy", "]", ".", "month", ",", "datetimes", "[", "hoy", "]", ".", "day", ",", "datetimes", "[", "hoy", "]", ".", "hour", "+", "0.5", ",", "dir_rad", ",", "dif_rad", ")", "lines", ".", "append", "(", "line", ")", "file_data", "=", "''", ".", "join", "(", "lines", ")", "write_to_file", "(", "file_path", ",", "file_data", ",", "True", ")", "if", "originally_ip", "is", "True", ":", "self", ".", "convert_to_ip", "(", ")", "return", "file_path" ]
Write an wea file from the epw file. WEA carries radiation values from epw. Gendaymtx uses these values to generate the sky. For an annual analysis it is identical to using epw2wea. args: file_path: Full file path for output file. hoys: List of hours of the year. Default is 0-8759.
[ "Write", "an", "wea", "file", "from", "the", "epw", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L1302-L1341
4,631
ladybug-tools/ladybug
ladybug/epw.py
EPW.to_json
def to_json(self): """Convert the EPW to a dictionary.""" # load data if it's not loaded if not self.is_data_loaded: self._import_data() def jsonify_dict(base_dict): new_dict = {} for key, val in base_dict.items(): new_dict[key] = val.to_json() return new_dict hot_wks = jsonify_dict(self.extreme_hot_weeks) cold_wks = jsonify_dict(self.extreme_cold_weeks) typ_wks = jsonify_dict(self.typical_weeks) grnd_temps = jsonify_dict(self.monthly_ground_temperature) return { 'location': self.location.to_json(), 'data_collections': [dc.to_json() for dc in self._data], 'metadata': self.metadata, 'heating_dict': self.heating_design_condition_dictionary, 'cooling_dict': self.cooling_design_condition_dictionary, 'extremes_dict': self.extreme_design_condition_dictionary, 'extreme_hot_weeks': hot_wks, 'extreme_cold_weeks': cold_wks, 'typical_weeks': typ_wks, "monthly_ground_temps": grnd_temps, "is_ip": self._is_ip, "is_leap_year": self.is_leap_year, "daylight_savings_start": self.daylight_savings_start, "daylight_savings_end": self.daylight_savings_end, "comments_1": self.comments_1, "comments_2": self.comments_2 }
python
def to_json(self): """Convert the EPW to a dictionary.""" # load data if it's not loaded if not self.is_data_loaded: self._import_data() def jsonify_dict(base_dict): new_dict = {} for key, val in base_dict.items(): new_dict[key] = val.to_json() return new_dict hot_wks = jsonify_dict(self.extreme_hot_weeks) cold_wks = jsonify_dict(self.extreme_cold_weeks) typ_wks = jsonify_dict(self.typical_weeks) grnd_temps = jsonify_dict(self.monthly_ground_temperature) return { 'location': self.location.to_json(), 'data_collections': [dc.to_json() for dc in self._data], 'metadata': self.metadata, 'heating_dict': self.heating_design_condition_dictionary, 'cooling_dict': self.cooling_design_condition_dictionary, 'extremes_dict': self.extreme_design_condition_dictionary, 'extreme_hot_weeks': hot_wks, 'extreme_cold_weeks': cold_wks, 'typical_weeks': typ_wks, "monthly_ground_temps": grnd_temps, "is_ip": self._is_ip, "is_leap_year": self.is_leap_year, "daylight_savings_start": self.daylight_savings_start, "daylight_savings_end": self.daylight_savings_end, "comments_1": self.comments_1, "comments_2": self.comments_2 }
[ "def", "to_json", "(", "self", ")", ":", "# load data if it's not loaded", "if", "not", "self", ".", "is_data_loaded", ":", "self", ".", "_import_data", "(", ")", "def", "jsonify_dict", "(", "base_dict", ")", ":", "new_dict", "=", "{", "}", "for", "key", ",", "val", "in", "base_dict", ".", "items", "(", ")", ":", "new_dict", "[", "key", "]", "=", "val", ".", "to_json", "(", ")", "return", "new_dict", "hot_wks", "=", "jsonify_dict", "(", "self", ".", "extreme_hot_weeks", ")", "cold_wks", "=", "jsonify_dict", "(", "self", ".", "extreme_cold_weeks", ")", "typ_wks", "=", "jsonify_dict", "(", "self", ".", "typical_weeks", ")", "grnd_temps", "=", "jsonify_dict", "(", "self", ".", "monthly_ground_temperature", ")", "return", "{", "'location'", ":", "self", ".", "location", ".", "to_json", "(", ")", ",", "'data_collections'", ":", "[", "dc", ".", "to_json", "(", ")", "for", "dc", "in", "self", ".", "_data", "]", ",", "'metadata'", ":", "self", ".", "metadata", ",", "'heating_dict'", ":", "self", ".", "heating_design_condition_dictionary", ",", "'cooling_dict'", ":", "self", ".", "cooling_design_condition_dictionary", ",", "'extremes_dict'", ":", "self", ".", "extreme_design_condition_dictionary", ",", "'extreme_hot_weeks'", ":", "hot_wks", ",", "'extreme_cold_weeks'", ":", "cold_wks", ",", "'typical_weeks'", ":", "typ_wks", ",", "\"monthly_ground_temps\"", ":", "grnd_temps", ",", "\"is_ip\"", ":", "self", ".", "_is_ip", ",", "\"is_leap_year\"", ":", "self", ".", "is_leap_year", ",", "\"daylight_savings_start\"", ":", "self", ".", "daylight_savings_start", ",", "\"daylight_savings_end\"", ":", "self", ".", "daylight_savings_end", ",", "\"comments_1\"", ":", "self", ".", "comments_1", ",", "\"comments_2\"", ":", "self", ".", "comments_2", "}" ]
Convert the EPW to a dictionary.
[ "Convert", "the", "EPW", "to", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L1343-L1375
4,632
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.from_analysis_period
def from_analysis_period(cls, analysis_period=None): """Create and AnalysisPeriod from an analysis period. This method is useful to be called from inside Grasshopper or Dynamo """ if not analysis_period: return cls() elif hasattr(analysis_period, 'isAnalysisPeriod'): return analysis_period elif isinstance(analysis_period, str): try: return cls.from_string(analysis_period) except Exception as e: raise ValueError( "{} is not convertable to an AnalysisPeriod: {}".format( analysis_period, e) )
python
def from_analysis_period(cls, analysis_period=None): """Create and AnalysisPeriod from an analysis period. This method is useful to be called from inside Grasshopper or Dynamo """ if not analysis_period: return cls() elif hasattr(analysis_period, 'isAnalysisPeriod'): return analysis_period elif isinstance(analysis_period, str): try: return cls.from_string(analysis_period) except Exception as e: raise ValueError( "{} is not convertable to an AnalysisPeriod: {}".format( analysis_period, e) )
[ "def", "from_analysis_period", "(", "cls", ",", "analysis_period", "=", "None", ")", ":", "if", "not", "analysis_period", ":", "return", "cls", "(", ")", "elif", "hasattr", "(", "analysis_period", ",", "'isAnalysisPeriod'", ")", ":", "return", "analysis_period", "elif", "isinstance", "(", "analysis_period", ",", "str", ")", ":", "try", ":", "return", "cls", ".", "from_string", "(", "analysis_period", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "\"{} is not convertable to an AnalysisPeriod: {}\"", ".", "format", "(", "analysis_period", ",", "e", ")", ")" ]
Create and AnalysisPeriod from an analysis period. This method is useful to be called from inside Grasshopper or Dynamo
[ "Create", "and", "AnalysisPeriod", "from", "an", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L161-L177
4,633
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.from_string
def from_string(cls, analysis_period_string): """Create an Analysis Period object from an analysis period string. %s/%s to %s/%s between %s and %s @%s """ # %s/%s to %s/%s between %s to %s @%s* is_leap_year = True if analysis_period_string.strip()[-1] == '*' else False ap = analysis_period_string.lower().replace(' ', '') \ .replace('to', ' ') \ .replace('and', ' ') \ .replace('/', ' ') \ .replace('between', ' ') \ .replace('@', ' ') \ .replace('*', '') try: st_month, st_day, end_month, end_day, \ st_hour, end_hour, timestep = ap.split(' ') return cls(st_month, st_day, st_hour, end_month, end_day, end_hour, int(timestep), is_leap_year) except Exception as e: raise ValueError(str(e))
python
def from_string(cls, analysis_period_string): """Create an Analysis Period object from an analysis period string. %s/%s to %s/%s between %s and %s @%s """ # %s/%s to %s/%s between %s to %s @%s* is_leap_year = True if analysis_period_string.strip()[-1] == '*' else False ap = analysis_period_string.lower().replace(' ', '') \ .replace('to', ' ') \ .replace('and', ' ') \ .replace('/', ' ') \ .replace('between', ' ') \ .replace('@', ' ') \ .replace('*', '') try: st_month, st_day, end_month, end_day, \ st_hour, end_hour, timestep = ap.split(' ') return cls(st_month, st_day, st_hour, end_month, end_day, end_hour, int(timestep), is_leap_year) except Exception as e: raise ValueError(str(e))
[ "def", "from_string", "(", "cls", ",", "analysis_period_string", ")", ":", "# %s/%s to %s/%s between %s to %s @%s*", "is_leap_year", "=", "True", "if", "analysis_period_string", ".", "strip", "(", ")", "[", "-", "1", "]", "==", "'*'", "else", "False", "ap", "=", "analysis_period_string", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "'to'", ",", "' '", ")", ".", "replace", "(", "'and'", ",", "' '", ")", ".", "replace", "(", "'/'", ",", "' '", ")", ".", "replace", "(", "'between'", ",", "' '", ")", ".", "replace", "(", "'@'", ",", "' '", ")", ".", "replace", "(", "'*'", ",", "''", ")", "try", ":", "st_month", ",", "st_day", ",", "end_month", ",", "end_day", ",", "st_hour", ",", "end_hour", ",", "timestep", "=", "ap", ".", "split", "(", "' '", ")", "return", "cls", "(", "st_month", ",", "st_day", ",", "st_hour", ",", "end_month", ",", "end_day", ",", "end_hour", ",", "int", "(", "timestep", ")", ",", "is_leap_year", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "str", "(", "e", ")", ")" ]
Create an Analysis Period object from an analysis period string. %s/%s to %s/%s between %s and %s @%s
[ "Create", "an", "Analysis", "Period", "object", "from", "an", "analysis", "period", "string", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L180-L200
4,634
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.datetimes
def datetimes(self): """A sorted list of datetimes in this analysis period.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(DateTime.from_moy(moy, self.is_leap_year) for moy in self._timestamps_data)
python
def datetimes(self): """A sorted list of datetimes in this analysis period.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(DateTime.from_moy(moy, self.is_leap_year) for moy in self._timestamps_data)
[ "def", "datetimes", "(", "self", ")", ":", "if", "self", ".", "_timestamps_data", "is", "None", ":", "self", ".", "_calculate_timestamps", "(", ")", "return", "tuple", "(", "DateTime", ".", "from_moy", "(", "moy", ",", "self", ".", "is_leap_year", ")", "for", "moy", "in", "self", ".", "_timestamps_data", ")" ]
A sorted list of datetimes in this analysis period.
[ "A", "sorted", "list", "of", "datetimes", "in", "this", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L258-L263
4,635
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.hoys
def hoys(self): """A sorted list of hours of year in this analysis period.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(moy / 60.0 for moy in self._timestamps_data)
python
def hoys(self): """A sorted list of hours of year in this analysis period.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(moy / 60.0 for moy in self._timestamps_data)
[ "def", "hoys", "(", "self", ")", ":", "if", "self", ".", "_timestamps_data", "is", "None", ":", "self", ".", "_calculate_timestamps", "(", ")", "return", "tuple", "(", "moy", "/", "60.0", "for", "moy", "in", "self", ".", "_timestamps_data", ")" ]
A sorted list of hours of year in this analysis period.
[ "A", "sorted", "list", "of", "hours", "of", "year", "in", "this", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L273-L277
4,636
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.hoys_int
def hoys_int(self): """A sorted list of hours of year in this analysis period as integers.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(int(moy / 60.0) for moy in self._timestamps_data)
python
def hoys_int(self): """A sorted list of hours of year in this analysis period as integers.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(int(moy / 60.0) for moy in self._timestamps_data)
[ "def", "hoys_int", "(", "self", ")", ":", "if", "self", ".", "_timestamps_data", "is", "None", ":", "self", ".", "_calculate_timestamps", "(", ")", "return", "tuple", "(", "int", "(", "moy", "/", "60.0", ")", "for", "moy", "in", "self", ".", "_timestamps_data", ")" ]
A sorted list of hours of year in this analysis period as integers.
[ "A", "sorted", "list", "of", "hours", "of", "year", "in", "this", "analysis", "period", "as", "integers", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L280-L284
4,637
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.doys_int
def doys_int(self): """A sorted list of days of the year in this analysis period as integers.""" if not self._is_reversed: return self._calc_daystamps(self.st_time, self.end_time) else: doys_st = self._calc_daystamps(self.st_time, DateTime.from_hoy(8759)) doys_end = self._calc_daystamps(DateTime.from_hoy(0), self.end_time) return doys_st + doys_end
python
def doys_int(self): """A sorted list of days of the year in this analysis period as integers.""" if not self._is_reversed: return self._calc_daystamps(self.st_time, self.end_time) else: doys_st = self._calc_daystamps(self.st_time, DateTime.from_hoy(8759)) doys_end = self._calc_daystamps(DateTime.from_hoy(0), self.end_time) return doys_st + doys_end
[ "def", "doys_int", "(", "self", ")", ":", "if", "not", "self", ".", "_is_reversed", ":", "return", "self", ".", "_calc_daystamps", "(", "self", ".", "st_time", ",", "self", ".", "end_time", ")", "else", ":", "doys_st", "=", "self", ".", "_calc_daystamps", "(", "self", ".", "st_time", ",", "DateTime", ".", "from_hoy", "(", "8759", ")", ")", "doys_end", "=", "self", ".", "_calc_daystamps", "(", "DateTime", ".", "from_hoy", "(", "0", ")", ",", "self", ".", "end_time", ")", "return", "doys_st", "+", "doys_end" ]
A sorted list of days of the year in this analysis period as integers.
[ "A", "sorted", "list", "of", "days", "of", "the", "year", "in", "this", "analysis", "period", "as", "integers", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L287-L294
4,638
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.months_int
def months_int(self): """A sorted list of months of the year in this analysis period as integers.""" if not self._is_reversed: return list(xrange(self.st_time.month, self.end_time.month + 1)) else: months_st = list(xrange(self.st_time.month, 13)) months_end = list(xrange(1, self.end_time.month + 1)) return months_st + months_end
python
def months_int(self): """A sorted list of months of the year in this analysis period as integers.""" if not self._is_reversed: return list(xrange(self.st_time.month, self.end_time.month + 1)) else: months_st = list(xrange(self.st_time.month, 13)) months_end = list(xrange(1, self.end_time.month + 1)) return months_st + months_end
[ "def", "months_int", "(", "self", ")", ":", "if", "not", "self", ".", "_is_reversed", ":", "return", "list", "(", "xrange", "(", "self", ".", "st_time", ".", "month", ",", "self", ".", "end_time", ".", "month", "+", "1", ")", ")", "else", ":", "months_st", "=", "list", "(", "xrange", "(", "self", ".", "st_time", ".", "month", ",", "13", ")", ")", "months_end", "=", "list", "(", "xrange", "(", "1", ",", "self", ".", "end_time", ".", "month", "+", "1", ")", ")", "return", "months_st", "+", "months_end" ]
A sorted list of months of the year in this analysis period as integers.
[ "A", "sorted", "list", "of", "months", "of", "the", "year", "in", "this", "analysis", "period", "as", "integers", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L297-L304
4,639
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.months_per_hour
def months_per_hour(self): """A list of tuples representing months per hour in this analysis period.""" month_hour = [] hour_range = xrange(self.st_hour, self.end_hour + 1) for month in self.months_int: month_hour.extend([(month, hr) for hr in hour_range]) return month_hour
python
def months_per_hour(self): """A list of tuples representing months per hour in this analysis period.""" month_hour = [] hour_range = xrange(self.st_hour, self.end_hour + 1) for month in self.months_int: month_hour.extend([(month, hr) for hr in hour_range]) return month_hour
[ "def", "months_per_hour", "(", "self", ")", ":", "month_hour", "=", "[", "]", "hour_range", "=", "xrange", "(", "self", ".", "st_hour", ",", "self", ".", "end_hour", "+", "1", ")", "for", "month", "in", "self", ".", "months_int", ":", "month_hour", ".", "extend", "(", "[", "(", "month", ",", "hr", ")", "for", "hr", "in", "hour_range", "]", ")", "return", "month_hour" ]
A list of tuples representing months per hour in this analysis period.
[ "A", "list", "of", "tuples", "representing", "months", "per", "hour", "in", "this", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L307-L313
4,640
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.is_annual
def is_annual(self): """Check if an analysis period is annual.""" if (self.st_month, self.st_day, self.st_hour, self.end_month, self.end_day, self.end_hour) == (1, 1, 0, 12, 31, 23): return True else: return False
python
def is_annual(self): """Check if an analysis period is annual.""" if (self.st_month, self.st_day, self.st_hour, self.end_month, self.end_day, self.end_hour) == (1, 1, 0, 12, 31, 23): return True else: return False
[ "def", "is_annual", "(", "self", ")", ":", "if", "(", "self", ".", "st_month", ",", "self", ".", "st_day", ",", "self", ".", "st_hour", ",", "self", ".", "end_month", ",", "self", ".", "end_day", ",", "self", ".", "end_hour", ")", "==", "(", "1", ",", "1", ",", "0", ",", "12", ",", "31", ",", "23", ")", ":", "return", "True", "else", ":", "return", "False" ]
Check if an analysis period is annual.
[ "Check", "if", "an", "analysis", "period", "is", "annual", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L321-L327
4,641
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.is_possible_hour
def is_possible_hour(self, hour): """Check if a float hour is a possible hour for this analysis period.""" if hour > 23 and self.is_possible_hour(0): hour = int(hour) if not self._is_overnight: return self.st_time.hour <= hour <= self.end_time.hour else: return self.st_time.hour <= hour <= 23 or \ 0 <= hour <= self.end_time.hour
python
def is_possible_hour(self, hour): """Check if a float hour is a possible hour for this analysis period.""" if hour > 23 and self.is_possible_hour(0): hour = int(hour) if not self._is_overnight: return self.st_time.hour <= hour <= self.end_time.hour else: return self.st_time.hour <= hour <= 23 or \ 0 <= hour <= self.end_time.hour
[ "def", "is_possible_hour", "(", "self", ",", "hour", ")", ":", "if", "hour", ">", "23", "and", "self", ".", "is_possible_hour", "(", "0", ")", ":", "hour", "=", "int", "(", "hour", ")", "if", "not", "self", ".", "_is_overnight", ":", "return", "self", ".", "st_time", ".", "hour", "<=", "hour", "<=", "self", ".", "end_time", ".", "hour", "else", ":", "return", "self", ".", "st_time", ".", "hour", "<=", "hour", "<=", "23", "or", "0", "<=", "hour", "<=", "self", ".", "end_time", ".", "hour" ]
Check if a float hour is a possible hour for this analysis period.
[ "Check", "if", "a", "float", "hour", "is", "a", "possible", "hour", "for", "this", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L347-L355
4,642
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.is_time_included
def is_time_included(self, time): """Check if time is included in analysis period. Return True if time is inside this analysis period, otherwise return False Args: time: A DateTime to be tested Returns: A boolean. True if time is included in analysis period """ if self._timestamps_data is None: self._calculate_timestamps() # time filtering in Ladybug Tools is slightly different than "normal" # filtering since start hour and end hour will be applied for every day. # For instance 2/20 9am to 2/22 5pm means hour between 9-17 # during 20, 21 and 22 of Feb. return time.moy in self._timestamps_data
python
def is_time_included(self, time): """Check if time is included in analysis period. Return True if time is inside this analysis period, otherwise return False Args: time: A DateTime to be tested Returns: A boolean. True if time is included in analysis period """ if self._timestamps_data is None: self._calculate_timestamps() # time filtering in Ladybug Tools is slightly different than "normal" # filtering since start hour and end hour will be applied for every day. # For instance 2/20 9am to 2/22 5pm means hour between 9-17 # during 20, 21 and 22 of Feb. return time.moy in self._timestamps_data
[ "def", "is_time_included", "(", "self", ",", "time", ")", ":", "if", "self", ".", "_timestamps_data", "is", "None", ":", "self", ".", "_calculate_timestamps", "(", ")", "# time filtering in Ladybug Tools is slightly different than \"normal\"", "# filtering since start hour and end hour will be applied for every day.", "# For instance 2/20 9am to 2/22 5pm means hour between 9-17", "# during 20, 21 and 22 of Feb.", "return", "time", ".", "moy", "in", "self", ".", "_timestamps_data" ]
Check if time is included in analysis period. Return True if time is inside this analysis period, otherwise return False Args: time: A DateTime to be tested Returns: A boolean. True if time is included in analysis period
[ "Check", "if", "time", "is", "included", "in", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L357-L375
4,643
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.duplicate
def duplicate(self): """Return a copy of the analysis period.""" return AnalysisPeriod(self.st_month, self.st_day, self.st_hour, self.end_month, self.end_day, self.end_hour, self.timestep, self.is_leap_year)
python
def duplicate(self): """Return a copy of the analysis period.""" return AnalysisPeriod(self.st_month, self.st_day, self.st_hour, self.end_month, self.end_day, self.end_hour, self.timestep, self.is_leap_year)
[ "def", "duplicate", "(", "self", ")", ":", "return", "AnalysisPeriod", "(", "self", ".", "st_month", ",", "self", ".", "st_day", ",", "self", ".", "st_hour", ",", "self", ".", "end_month", ",", "self", ".", "end_day", ",", "self", ".", "end_hour", ",", "self", ".", "timestep", ",", "self", ".", "is_leap_year", ")" ]
Return a copy of the analysis period.
[ "Return", "a", "copy", "of", "the", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L377-L381
4,644
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod.to_json
def to_json(self): """Convert the analysis period to a dictionary.""" return { 'st_month': self.st_month, 'st_day': self.st_day, 'st_hour': self.st_hour, 'end_month': self.end_month, 'end_day': self.end_day, 'end_hour': self.end_hour, 'timestep': self.timestep, 'is_leap_year': self.is_leap_year }
python
def to_json(self): """Convert the analysis period to a dictionary.""" return { 'st_month': self.st_month, 'st_day': self.st_day, 'st_hour': self.st_hour, 'end_month': self.end_month, 'end_day': self.end_day, 'end_hour': self.end_hour, 'timestep': self.timestep, 'is_leap_year': self.is_leap_year }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'st_month'", ":", "self", ".", "st_month", ",", "'st_day'", ":", "self", ".", "st_day", ",", "'st_hour'", ":", "self", ".", "st_hour", ",", "'end_month'", ":", "self", ".", "end_month", ",", "'end_day'", ":", "self", ".", "end_day", ",", "'end_hour'", ":", "self", ".", "end_hour", ",", "'timestep'", ":", "self", ".", "timestep", ",", "'is_leap_year'", ":", "self", ".", "is_leap_year", "}" ]
Convert the analysis period to a dictionary.
[ "Convert", "the", "analysis", "period", "to", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L383-L394
4,645
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod._calc_timestamps
def _calc_timestamps(self, st_time, end_time): """Calculate timesteps between start time and end time. Use this method only when start time month is before end time month. """ # calculate based on minutes # I have to convert the object to DateTime because of how Dynamo # works: https://github.com/DynamoDS/Dynamo/issues/6683 # Do not modify this line to datetime curr = datetime(st_time.year, st_time.month, st_time.day, st_time.hour, st_time.minute, self.is_leap_year) end_time = datetime(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.minute, self.is_leap_year) while curr <= end_time: if self.is_possible_hour(curr.hour + (curr.minute / 60.0)): time = DateTime(curr.month, curr.day, curr.hour, curr.minute, self.is_leap_year) self._timestamps_data.append(time.moy) curr += self.minute_intervals if self.timestep != 1 and curr.hour == 23 and self.is_possible_hour(0): # This is for cases that timestep is more than one # and last hour of the day is part of the calculation curr = end_time for i in list(xrange(self.timestep))[1:]: curr += self.minute_intervals time = DateTime(curr.month, curr.day, curr.hour, curr.minute, self.is_leap_year) self._timestamps_data.append(time.moy)
python
def _calc_timestamps(self, st_time, end_time): """Calculate timesteps between start time and end time. Use this method only when start time month is before end time month. """ # calculate based on minutes # I have to convert the object to DateTime because of how Dynamo # works: https://github.com/DynamoDS/Dynamo/issues/6683 # Do not modify this line to datetime curr = datetime(st_time.year, st_time.month, st_time.day, st_time.hour, st_time.minute, self.is_leap_year) end_time = datetime(end_time.year, end_time.month, end_time.day, end_time.hour, end_time.minute, self.is_leap_year) while curr <= end_time: if self.is_possible_hour(curr.hour + (curr.minute / 60.0)): time = DateTime(curr.month, curr.day, curr.hour, curr.minute, self.is_leap_year) self._timestamps_data.append(time.moy) curr += self.minute_intervals if self.timestep != 1 and curr.hour == 23 and self.is_possible_hour(0): # This is for cases that timestep is more than one # and last hour of the day is part of the calculation curr = end_time for i in list(xrange(self.timestep))[1:]: curr += self.minute_intervals time = DateTime(curr.month, curr.day, curr.hour, curr.minute, self.is_leap_year) self._timestamps_data.append(time.moy)
[ "def", "_calc_timestamps", "(", "self", ",", "st_time", ",", "end_time", ")", ":", "# calculate based on minutes", "# I have to convert the object to DateTime because of how Dynamo", "# works: https://github.com/DynamoDS/Dynamo/issues/6683", "# Do not modify this line to datetime", "curr", "=", "datetime", "(", "st_time", ".", "year", ",", "st_time", ".", "month", ",", "st_time", ".", "day", ",", "st_time", ".", "hour", ",", "st_time", ".", "minute", ",", "self", ".", "is_leap_year", ")", "end_time", "=", "datetime", "(", "end_time", ".", "year", ",", "end_time", ".", "month", ",", "end_time", ".", "day", ",", "end_time", ".", "hour", ",", "end_time", ".", "minute", ",", "self", ".", "is_leap_year", ")", "while", "curr", "<=", "end_time", ":", "if", "self", ".", "is_possible_hour", "(", "curr", ".", "hour", "+", "(", "curr", ".", "minute", "/", "60.0", ")", ")", ":", "time", "=", "DateTime", "(", "curr", ".", "month", ",", "curr", ".", "day", ",", "curr", ".", "hour", ",", "curr", ".", "minute", ",", "self", ".", "is_leap_year", ")", "self", ".", "_timestamps_data", ".", "append", "(", "time", ".", "moy", ")", "curr", "+=", "self", ".", "minute_intervals", "if", "self", ".", "timestep", "!=", "1", "and", "curr", ".", "hour", "==", "23", "and", "self", ".", "is_possible_hour", "(", "0", ")", ":", "# This is for cases that timestep is more than one", "# and last hour of the day is part of the calculation", "curr", "=", "end_time", "for", "i", "in", "list", "(", "xrange", "(", "self", ".", "timestep", ")", ")", "[", "1", ":", "]", ":", "curr", "+=", "self", ".", "minute_intervals", "time", "=", "DateTime", "(", "curr", ".", "month", ",", "curr", ".", "day", ",", "curr", ".", "hour", ",", "curr", ".", "minute", ",", "self", ".", "is_leap_year", ")", "self", ".", "_timestamps_data", ".", "append", "(", "time", ".", "moy", ")" ]
Calculate timesteps between start time and end time. Use this method only when start time month is before end time month.
[ "Calculate", "timesteps", "between", "start", "time", "and", "end", "time", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L396-L425
4,646
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod._calculate_timestamps
def _calculate_timestamps(self): """Return a list of Ladybug DateTime in this analysis period.""" self._timestamps_data = [] if not self._is_reversed: self._calc_timestamps(self.st_time, self.end_time) else: self._calc_timestamps(self.st_time, DateTime.from_hoy(8759)) self._calc_timestamps(DateTime.from_hoy(0), self.end_time)
python
def _calculate_timestamps(self): """Return a list of Ladybug DateTime in this analysis period.""" self._timestamps_data = [] if not self._is_reversed: self._calc_timestamps(self.st_time, self.end_time) else: self._calc_timestamps(self.st_time, DateTime.from_hoy(8759)) self._calc_timestamps(DateTime.from_hoy(0), self.end_time)
[ "def", "_calculate_timestamps", "(", "self", ")", ":", "self", ".", "_timestamps_data", "=", "[", "]", "if", "not", "self", ".", "_is_reversed", ":", "self", ".", "_calc_timestamps", "(", "self", ".", "st_time", ",", "self", ".", "end_time", ")", "else", ":", "self", ".", "_calc_timestamps", "(", "self", ".", "st_time", ",", "DateTime", ".", "from_hoy", "(", "8759", ")", ")", "self", ".", "_calc_timestamps", "(", "DateTime", ".", "from_hoy", "(", "0", ")", ",", "self", ".", "end_time", ")" ]
Return a list of Ladybug DateTime in this analysis period.
[ "Return", "a", "list", "of", "Ladybug", "DateTime", "in", "this", "analysis", "period", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L427-L434
4,647
ladybug-tools/ladybug
ladybug/analysisperiod.py
AnalysisPeriod._calc_daystamps
def _calc_daystamps(self, st_time, end_time): """Calculate days of the year between start time and end time. Use this method only when start time month is before end time month. """ start_doy = sum(self._num_of_days_each_month[:st_time.month-1]) + st_time.day end_doy = sum(self._num_of_days_each_month[:end_time.month-1]) + end_time.day + 1 return list(range(start_doy, end_doy))
python
def _calc_daystamps(self, st_time, end_time): """Calculate days of the year between start time and end time. Use this method only when start time month is before end time month. """ start_doy = sum(self._num_of_days_each_month[:st_time.month-1]) + st_time.day end_doy = sum(self._num_of_days_each_month[:end_time.month-1]) + end_time.day + 1 return list(range(start_doy, end_doy))
[ "def", "_calc_daystamps", "(", "self", ",", "st_time", ",", "end_time", ")", ":", "start_doy", "=", "sum", "(", "self", ".", "_num_of_days_each_month", "[", ":", "st_time", ".", "month", "-", "1", "]", ")", "+", "st_time", ".", "day", "end_doy", "=", "sum", "(", "self", ".", "_num_of_days_each_month", "[", ":", "end_time", ".", "month", "-", "1", "]", ")", "+", "end_time", ".", "day", "+", "1", "return", "list", "(", "range", "(", "start_doy", ",", "end_doy", ")", ")" ]
Calculate days of the year between start time and end time. Use this method only when start time month is before end time month.
[ "Calculate", "days", "of", "the", "year", "between", "start", "time", "and", "end", "time", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L436-L443
4,648
ladybug-tools/ladybug
ladybug/wea.py
Wea.from_values
def from_values(cls, location, direct_normal_irradiance, diffuse_horizontal_irradiance, timestep=1, is_leap_year=False): """Create wea from a list of irradiance values. This method converts input lists to data collection. """ err_message = 'For timestep %d, %d number of data for %s is expected. ' \ '%d is provided.' if len(direct_normal_irradiance) % cls.hour_count(is_leap_year) == 0: # add extra information to err_message err_message = err_message + ' Did you forget to set the timestep to %d?' \ % (len(direct_normal_irradiance) / cls.hour_count(is_leap_year)) assert len(direct_normal_irradiance) / \ timestep == cls.hour_count(is_leap_year), \ err_message % (timestep, timestep * cls.hour_count(is_leap_year), 'direct normal irradiance', len( direct_normal_irradiance)) assert len(diffuse_horizontal_irradiance) / timestep == \ cls.hour_count(is_leap_year), \ err_message % (timestep, timestep * cls.hour_count(is_leap_year), 'diffuse_horizontal_irradiance', len( direct_normal_irradiance)) metadata = {'source': location.source, 'country': location.country, 'city': location.city} dnr, dhr = cls._get_data_collections( direct_normal_irradiance, diffuse_horizontal_irradiance, metadata, timestep, is_leap_year) return cls(location, dnr, dhr, timestep, is_leap_year)
python
def from_values(cls, location, direct_normal_irradiance, diffuse_horizontal_irradiance, timestep=1, is_leap_year=False): """Create wea from a list of irradiance values. This method converts input lists to data collection. """ err_message = 'For timestep %d, %d number of data for %s is expected. ' \ '%d is provided.' if len(direct_normal_irradiance) % cls.hour_count(is_leap_year) == 0: # add extra information to err_message err_message = err_message + ' Did you forget to set the timestep to %d?' \ % (len(direct_normal_irradiance) / cls.hour_count(is_leap_year)) assert len(direct_normal_irradiance) / \ timestep == cls.hour_count(is_leap_year), \ err_message % (timestep, timestep * cls.hour_count(is_leap_year), 'direct normal irradiance', len( direct_normal_irradiance)) assert len(diffuse_horizontal_irradiance) / timestep == \ cls.hour_count(is_leap_year), \ err_message % (timestep, timestep * cls.hour_count(is_leap_year), 'diffuse_horizontal_irradiance', len( direct_normal_irradiance)) metadata = {'source': location.source, 'country': location.country, 'city': location.city} dnr, dhr = cls._get_data_collections( direct_normal_irradiance, diffuse_horizontal_irradiance, metadata, timestep, is_leap_year) return cls(location, dnr, dhr, timestep, is_leap_year)
[ "def", "from_values", "(", "cls", ",", "location", ",", "direct_normal_irradiance", ",", "diffuse_horizontal_irradiance", ",", "timestep", "=", "1", ",", "is_leap_year", "=", "False", ")", ":", "err_message", "=", "'For timestep %d, %d number of data for %s is expected. '", "'%d is provided.'", "if", "len", "(", "direct_normal_irradiance", ")", "%", "cls", ".", "hour_count", "(", "is_leap_year", ")", "==", "0", ":", "# add extra information to err_message", "err_message", "=", "err_message", "+", "' Did you forget to set the timestep to %d?'", "%", "(", "len", "(", "direct_normal_irradiance", ")", "/", "cls", ".", "hour_count", "(", "is_leap_year", ")", ")", "assert", "len", "(", "direct_normal_irradiance", ")", "/", "timestep", "==", "cls", ".", "hour_count", "(", "is_leap_year", ")", ",", "err_message", "%", "(", "timestep", ",", "timestep", "*", "cls", ".", "hour_count", "(", "is_leap_year", ")", ",", "'direct normal irradiance'", ",", "len", "(", "direct_normal_irradiance", ")", ")", "assert", "len", "(", "diffuse_horizontal_irradiance", ")", "/", "timestep", "==", "cls", ".", "hour_count", "(", "is_leap_year", ")", ",", "err_message", "%", "(", "timestep", ",", "timestep", "*", "cls", ".", "hour_count", "(", "is_leap_year", ")", ",", "'diffuse_horizontal_irradiance'", ",", "len", "(", "direct_normal_irradiance", ")", ")", "metadata", "=", "{", "'source'", ":", "location", ".", "source", ",", "'country'", ":", "location", ".", "country", ",", "'city'", ":", "location", ".", "city", "}", "dnr", ",", "dhr", "=", "cls", ".", "_get_data_collections", "(", "direct_normal_irradiance", ",", "diffuse_horizontal_irradiance", ",", "metadata", ",", "timestep", ",", "is_leap_year", ")", "return", "cls", "(", "location", ",", "dnr", ",", "dhr", ",", "timestep", ",", "is_leap_year", ")" ]
Create wea from a list of irradiance values. This method converts input lists to data collection.
[ "Create", "wea", "from", "a", "list", "of", "irradiance", "values", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L69-L99
4,649
ladybug-tools/ladybug
ladybug/wea.py
Wea.from_file
def from_file(cls, weafile, timestep=1, is_leap_year=False): """Create wea object from a wea file. Args: weafile:Full path to wea file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. If the wea file has a time step smaller than an hour adjust this input accordingly. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. """ assert os.path.isfile(weafile), 'Failed to find {}'.format(weafile) location = Location() with open(weafile, readmode) as weaf: first_line = weaf.readline() assert first_line.startswith('place'), \ 'Failed to find place in header. ' \ '{} is not a valid wea file.'.format(weafile) location.city = ' '.join(first_line.split()[1:]) # parse header location.latitude = float(weaf.readline().split()[-1]) location.longitude = -float(weaf.readline().split()[-1]) location.time_zone = -int(weaf.readline().split()[-1]) / 15 location.elevation = float(weaf.readline().split()[-1]) weaf.readline() # pass line for weather data units # parse irradiance values direct_normal_irradiance = [] diffuse_horizontal_irradiance = [] for line in weaf: dirn, difh = [int(v) for v in line.split()[-2:]] direct_normal_irradiance.append(dirn) diffuse_horizontal_irradiance.append(difh) return cls.from_values(location, direct_normal_irradiance, diffuse_horizontal_irradiance, timestep, is_leap_year)
python
def from_file(cls, weafile, timestep=1, is_leap_year=False): """Create wea object from a wea file. Args: weafile:Full path to wea file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. If the wea file has a time step smaller than an hour adjust this input accordingly. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. """ assert os.path.isfile(weafile), 'Failed to find {}'.format(weafile) location = Location() with open(weafile, readmode) as weaf: first_line = weaf.readline() assert first_line.startswith('place'), \ 'Failed to find place in header. ' \ '{} is not a valid wea file.'.format(weafile) location.city = ' '.join(first_line.split()[1:]) # parse header location.latitude = float(weaf.readline().split()[-1]) location.longitude = -float(weaf.readline().split()[-1]) location.time_zone = -int(weaf.readline().split()[-1]) / 15 location.elevation = float(weaf.readline().split()[-1]) weaf.readline() # pass line for weather data units # parse irradiance values direct_normal_irradiance = [] diffuse_horizontal_irradiance = [] for line in weaf: dirn, difh = [int(v) for v in line.split()[-2:]] direct_normal_irradiance.append(dirn) diffuse_horizontal_irradiance.append(difh) return cls.from_values(location, direct_normal_irradiance, diffuse_horizontal_irradiance, timestep, is_leap_year)
[ "def", "from_file", "(", "cls", ",", "weafile", ",", "timestep", "=", "1", ",", "is_leap_year", "=", "False", ")", ":", "assert", "os", ".", "path", ".", "isfile", "(", "weafile", ")", ",", "'Failed to find {}'", ".", "format", "(", "weafile", ")", "location", "=", "Location", "(", ")", "with", "open", "(", "weafile", ",", "readmode", ")", "as", "weaf", ":", "first_line", "=", "weaf", ".", "readline", "(", ")", "assert", "first_line", ".", "startswith", "(", "'place'", ")", ",", "'Failed to find place in header. '", "'{} is not a valid wea file.'", ".", "format", "(", "weafile", ")", "location", ".", "city", "=", "' '", ".", "join", "(", "first_line", ".", "split", "(", ")", "[", "1", ":", "]", ")", "# parse header", "location", ".", "latitude", "=", "float", "(", "weaf", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "-", "1", "]", ")", "location", ".", "longitude", "=", "-", "float", "(", "weaf", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "-", "1", "]", ")", "location", ".", "time_zone", "=", "-", "int", "(", "weaf", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "-", "1", "]", ")", "/", "15", "location", ".", "elevation", "=", "float", "(", "weaf", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "-", "1", "]", ")", "weaf", ".", "readline", "(", ")", "# pass line for weather data units", "# parse irradiance values", "direct_normal_irradiance", "=", "[", "]", "diffuse_horizontal_irradiance", "=", "[", "]", "for", "line", "in", "weaf", ":", "dirn", ",", "difh", "=", "[", "int", "(", "v", ")", "for", "v", "in", "line", ".", "split", "(", ")", "[", "-", "2", ":", "]", "]", "direct_normal_irradiance", ".", "append", "(", "dirn", ")", "diffuse_horizontal_irradiance", ".", "append", "(", "difh", ")", "return", "cls", ".", "from_values", "(", "location", ",", "direct_normal_irradiance", ",", "diffuse_horizontal_irradiance", ",", "timestep", ",", "is_leap_year", ")" ]
Create wea object from a wea file. Args: weafile:Full path to wea file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. If the wea file has a time step smaller than an hour adjust this input accordingly. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False.
[ "Create", "wea", "object", "from", "a", "wea", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L139-L174
4,650
ladybug-tools/ladybug
ladybug/wea.py
Wea.from_epw_file
def from_epw_file(cls, epwfile, timestep=1): """Create a wea object using the solar irradiance values in an epw file. Args: epwfile: Full path to epw weather file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. Note that this input will only do a linear interpolation over the data in the EPW file. While such linear interpolations are suitable for most thermal simulations, where thermal lag "smooths over" the effect of momentary increases in solar energy, it is not recommended for daylight simulations, where momentary increases in solar energy can mean the difference between glare and visual comfort. """ is_leap_year = False # epw file is always for 8760 hours epw = EPW(epwfile) direct_normal, diffuse_horizontal = \ cls._get_data_collections(epw.direct_normal_radiation.values, epw.diffuse_horizontal_radiation.values, epw.metadata, 1, is_leap_year) if timestep != 1: print ("Note: timesteps greater than 1 on epw-generated Wea's \n" + "are suitable for thermal models but are not recommended \n" + "for daylight models.") # interpolate the data direct_normal = direct_normal.interpolate_to_timestep(timestep) diffuse_horizontal = diffuse_horizontal.interpolate_to_timestep(timestep) # create sunpath to check if the sun is up at a given timestep sp = Sunpath.from_location(epw.location) # add correct values to the emply data collection for i, dt in enumerate(cls._get_datetimes(timestep, is_leap_year)): # set irradiance values to 0 when the sun is not up sun = sp.calculate_sun_from_date_time(dt) if sun.altitude < 0: direct_normal[i] = 0 diffuse_horizontal[i] = 0 return cls(epw.location, direct_normal, diffuse_horizontal, timestep, is_leap_year)
python
def from_epw_file(cls, epwfile, timestep=1): """Create a wea object using the solar irradiance values in an epw file. Args: epwfile: Full path to epw weather file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. Note that this input will only do a linear interpolation over the data in the EPW file. While such linear interpolations are suitable for most thermal simulations, where thermal lag "smooths over" the effect of momentary increases in solar energy, it is not recommended for daylight simulations, where momentary increases in solar energy can mean the difference between glare and visual comfort. """ is_leap_year = False # epw file is always for 8760 hours epw = EPW(epwfile) direct_normal, diffuse_horizontal = \ cls._get_data_collections(epw.direct_normal_radiation.values, epw.diffuse_horizontal_radiation.values, epw.metadata, 1, is_leap_year) if timestep != 1: print ("Note: timesteps greater than 1 on epw-generated Wea's \n" + "are suitable for thermal models but are not recommended \n" + "for daylight models.") # interpolate the data direct_normal = direct_normal.interpolate_to_timestep(timestep) diffuse_horizontal = diffuse_horizontal.interpolate_to_timestep(timestep) # create sunpath to check if the sun is up at a given timestep sp = Sunpath.from_location(epw.location) # add correct values to the emply data collection for i, dt in enumerate(cls._get_datetimes(timestep, is_leap_year)): # set irradiance values to 0 when the sun is not up sun = sp.calculate_sun_from_date_time(dt) if sun.altitude < 0: direct_normal[i] = 0 diffuse_horizontal[i] = 0 return cls(epw.location, direct_normal, diffuse_horizontal, timestep, is_leap_year)
[ "def", "from_epw_file", "(", "cls", ",", "epwfile", ",", "timestep", "=", "1", ")", ":", "is_leap_year", "=", "False", "# epw file is always for 8760 hours", "epw", "=", "EPW", "(", "epwfile", ")", "direct_normal", ",", "diffuse_horizontal", "=", "cls", ".", "_get_data_collections", "(", "epw", ".", "direct_normal_radiation", ".", "values", ",", "epw", ".", "diffuse_horizontal_radiation", ".", "values", ",", "epw", ".", "metadata", ",", "1", ",", "is_leap_year", ")", "if", "timestep", "!=", "1", ":", "print", "(", "\"Note: timesteps greater than 1 on epw-generated Wea's \\n\"", "+", "\"are suitable for thermal models but are not recommended \\n\"", "+", "\"for daylight models.\"", ")", "# interpolate the data", "direct_normal", "=", "direct_normal", ".", "interpolate_to_timestep", "(", "timestep", ")", "diffuse_horizontal", "=", "diffuse_horizontal", ".", "interpolate_to_timestep", "(", "timestep", ")", "# create sunpath to check if the sun is up at a given timestep", "sp", "=", "Sunpath", ".", "from_location", "(", "epw", ".", "location", ")", "# add correct values to the emply data collection", "for", "i", ",", "dt", "in", "enumerate", "(", "cls", ".", "_get_datetimes", "(", "timestep", ",", "is_leap_year", ")", ")", ":", "# set irradiance values to 0 when the sun is not up", "sun", "=", "sp", ".", "calculate_sun_from_date_time", "(", "dt", ")", "if", "sun", ".", "altitude", "<", "0", ":", "direct_normal", "[", "i", "]", "=", "0", "diffuse_horizontal", "[", "i", "]", "=", "0", "return", "cls", "(", "epw", ".", "location", ",", "direct_normal", ",", "diffuse_horizontal", ",", "timestep", ",", "is_leap_year", ")" ]
Create a wea object using the solar irradiance values in an epw file. Args: epwfile: Full path to epw weather file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. Note that this input will only do a linear interpolation over the data in the EPW file. While such linear interpolations are suitable for most thermal simulations, where thermal lag "smooths over" the effect of momentary increases in solar energy, it is not recommended for daylight simulations, where momentary increases in solar energy can mean the difference between glare and visual comfort.
[ "Create", "a", "wea", "object", "using", "the", "solar", "irradiance", "values", "in", "an", "epw", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L177-L216
4,651
ladybug-tools/ladybug
ladybug/wea.py
Wea.from_stat_file
def from_stat_file(cls, statfile, timestep=1, is_leap_year=False): """Create an ASHRAE Revised Clear Sky wea object from the monthly sky optical depths in a .stat file. Args: statfile: Full path to the .stat file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. """ stat = STAT(statfile) # check to be sure the stat file does not have missing tau values def check_missing(opt_data, data_name): if opt_data == []: raise ValueError('Stat file contains no optical data.') for i, x in enumerate(opt_data): if x is None: raise ValueError( 'Missing optical depth data for {} at month {}'.format( data_name, i) ) check_missing(stat.monthly_tau_beam, 'monthly_tau_beam') check_missing(stat.monthly_tau_diffuse, 'monthly_tau_diffuse') return cls.from_ashrae_revised_clear_sky(stat.location, stat.monthly_tau_beam, stat.monthly_tau_diffuse, timestep, is_leap_year)
python
def from_stat_file(cls, statfile, timestep=1, is_leap_year=False): """Create an ASHRAE Revised Clear Sky wea object from the monthly sky optical depths in a .stat file. Args: statfile: Full path to the .stat file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. """ stat = STAT(statfile) # check to be sure the stat file does not have missing tau values def check_missing(opt_data, data_name): if opt_data == []: raise ValueError('Stat file contains no optical data.') for i, x in enumerate(opt_data): if x is None: raise ValueError( 'Missing optical depth data for {} at month {}'.format( data_name, i) ) check_missing(stat.monthly_tau_beam, 'monthly_tau_beam') check_missing(stat.monthly_tau_diffuse, 'monthly_tau_diffuse') return cls.from_ashrae_revised_clear_sky(stat.location, stat.monthly_tau_beam, stat.monthly_tau_diffuse, timestep, is_leap_year)
[ "def", "from_stat_file", "(", "cls", ",", "statfile", ",", "timestep", "=", "1", ",", "is_leap_year", "=", "False", ")", ":", "stat", "=", "STAT", "(", "statfile", ")", "# check to be sure the stat file does not have missing tau values", "def", "check_missing", "(", "opt_data", ",", "data_name", ")", ":", "if", "opt_data", "==", "[", "]", ":", "raise", "ValueError", "(", "'Stat file contains no optical data.'", ")", "for", "i", ",", "x", "in", "enumerate", "(", "opt_data", ")", ":", "if", "x", "is", "None", ":", "raise", "ValueError", "(", "'Missing optical depth data for {} at month {}'", ".", "format", "(", "data_name", ",", "i", ")", ")", "check_missing", "(", "stat", ".", "monthly_tau_beam", ",", "'monthly_tau_beam'", ")", "check_missing", "(", "stat", ".", "monthly_tau_diffuse", ",", "'monthly_tau_diffuse'", ")", "return", "cls", ".", "from_ashrae_revised_clear_sky", "(", "stat", ".", "location", ",", "stat", ".", "monthly_tau_beam", ",", "stat", ".", "monthly_tau_diffuse", ",", "timestep", ",", "is_leap_year", ")" ]
Create an ASHRAE Revised Clear Sky wea object from the monthly sky optical depths in a .stat file. Args: statfile: Full path to the .stat file. timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False.
[ "Create", "an", "ASHRAE", "Revised", "Clear", "Sky", "wea", "object", "from", "the", "monthly", "sky", "optical", "depths", "in", "a", ".", "stat", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L219-L247
4,652
ladybug-tools/ladybug
ladybug/wea.py
Wea.from_zhang_huang_solar
def from_zhang_huang_solar(cls, location, cloud_cover, relative_humidity, dry_bulb_temperature, wind_speed, atmospheric_pressure=None, timestep=1, is_leap_year=False, use_disc=False): """Create a wea object from climate data using the Zhang-Huang model. The Zhang-Huang solar model was developed to estimate solar irradiance for weather stations that lack such values, which are typically colleted with a pyranometer. Using total cloud cover, dry-bulb temperature, relative humidity, and wind speed as inputs the Zhang-Huang estimates global horizontal irradiance by means of a regression model across these variables. For more information on the Zhang-Huang model, see the EnergyPlus Engineering Reference: https://bigladdersoftware.com/epx/docs/8-7/engineering-reference/climate-calculations.html#zhang-huang-solar-model Args: location: Ladybug location object. cloud_cover: A list of annual float values between 0 and 1 that represent the fraction of the sky dome covered in clouds (0 = clear; 1 = completely overcast) relative_humidity: A list of annual float values between 0 and 100 that represent the relative humidity in percent. dry_bulb_temperature: A list of annual float values that represent the dry bulb temperature in degrees Celcius. wind_speed: A list of annual float values that represent the wind speed in meters per second. atmospheric_pressure: An optional list of float values that represent the atmospheric pressure in Pa. If None or left blank, pressure at sea level will be used (101325 Pa). timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. use_disc: Set to True to use the original DISC model as opposed to the newer and more accurate DIRINT model. Default is False. """ # check input data assert len(cloud_cover) == len(relative_humidity) == \ len(dry_bulb_temperature) == len(wind_speed), \ 'lengths of input climate data must match.' assert len(cloud_cover) / timestep == cls.hour_count(is_leap_year), \ 'input climate data must be annual.' assert isinstance(timestep, int), 'timestep must be an' \ ' integer. Got {}'.format(type(timestep)) if atmospheric_pressure is not None: assert len(atmospheric_pressure) == len(cloud_cover), \ 'length pf atmospheric_pressure must match the other input lists.' else: atmospheric_pressure = [101325] * cls.hour_count(is_leap_year) * timestep # initiate sunpath based on location sp = Sunpath.from_location(location) sp.is_leap_year = is_leap_year # calculate parameters needed for zhang-huang irradiance date_times = [] altitudes = [] doys = [] dry_bulb_t3_hrs = [] for count, t_date in enumerate(cls._get_datetimes(timestep, is_leap_year)): date_times.append(t_date) sun = sp.calculate_sun_from_date_time(t_date) altitudes.append(sun.altitude) doys.append(sun.datetime.doy) dry_bulb_t3_hrs.append(dry_bulb_temperature[count - (3 * timestep)]) # calculate zhang-huang irradiance dir_ir, diff_ir = zhang_huang_solar_split(altitudes, doys, cloud_cover, relative_humidity, dry_bulb_temperature, dry_bulb_t3_hrs, wind_speed, atmospheric_pressure, use_disc) # assemble the results into DataCollections metadata = {'source': location.source, 'country': location.country, 'city': location.city} direct_norm_rad, diffuse_horiz_rad = \ cls._get_data_collections(dir_ir, diff_ir, metadata, timestep, is_leap_year) return cls(location, direct_norm_rad, diffuse_horiz_rad, timestep, is_leap_year)
python
def from_zhang_huang_solar(cls, location, cloud_cover, relative_humidity, dry_bulb_temperature, wind_speed, atmospheric_pressure=None, timestep=1, is_leap_year=False, use_disc=False): """Create a wea object from climate data using the Zhang-Huang model. The Zhang-Huang solar model was developed to estimate solar irradiance for weather stations that lack such values, which are typically colleted with a pyranometer. Using total cloud cover, dry-bulb temperature, relative humidity, and wind speed as inputs the Zhang-Huang estimates global horizontal irradiance by means of a regression model across these variables. For more information on the Zhang-Huang model, see the EnergyPlus Engineering Reference: https://bigladdersoftware.com/epx/docs/8-7/engineering-reference/climate-calculations.html#zhang-huang-solar-model Args: location: Ladybug location object. cloud_cover: A list of annual float values between 0 and 1 that represent the fraction of the sky dome covered in clouds (0 = clear; 1 = completely overcast) relative_humidity: A list of annual float values between 0 and 100 that represent the relative humidity in percent. dry_bulb_temperature: A list of annual float values that represent the dry bulb temperature in degrees Celcius. wind_speed: A list of annual float values that represent the wind speed in meters per second. atmospheric_pressure: An optional list of float values that represent the atmospheric pressure in Pa. If None or left blank, pressure at sea level will be used (101325 Pa). timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. use_disc: Set to True to use the original DISC model as opposed to the newer and more accurate DIRINT model. Default is False. """ # check input data assert len(cloud_cover) == len(relative_humidity) == \ len(dry_bulb_temperature) == len(wind_speed), \ 'lengths of input climate data must match.' assert len(cloud_cover) / timestep == cls.hour_count(is_leap_year), \ 'input climate data must be annual.' assert isinstance(timestep, int), 'timestep must be an' \ ' integer. Got {}'.format(type(timestep)) if atmospheric_pressure is not None: assert len(atmospheric_pressure) == len(cloud_cover), \ 'length pf atmospheric_pressure must match the other input lists.' else: atmospheric_pressure = [101325] * cls.hour_count(is_leap_year) * timestep # initiate sunpath based on location sp = Sunpath.from_location(location) sp.is_leap_year = is_leap_year # calculate parameters needed for zhang-huang irradiance date_times = [] altitudes = [] doys = [] dry_bulb_t3_hrs = [] for count, t_date in enumerate(cls._get_datetimes(timestep, is_leap_year)): date_times.append(t_date) sun = sp.calculate_sun_from_date_time(t_date) altitudes.append(sun.altitude) doys.append(sun.datetime.doy) dry_bulb_t3_hrs.append(dry_bulb_temperature[count - (3 * timestep)]) # calculate zhang-huang irradiance dir_ir, diff_ir = zhang_huang_solar_split(altitudes, doys, cloud_cover, relative_humidity, dry_bulb_temperature, dry_bulb_t3_hrs, wind_speed, atmospheric_pressure, use_disc) # assemble the results into DataCollections metadata = {'source': location.source, 'country': location.country, 'city': location.city} direct_norm_rad, diffuse_horiz_rad = \ cls._get_data_collections(dir_ir, diff_ir, metadata, timestep, is_leap_year) return cls(location, direct_norm_rad, diffuse_horiz_rad, timestep, is_leap_year)
[ "def", "from_zhang_huang_solar", "(", "cls", ",", "location", ",", "cloud_cover", ",", "relative_humidity", ",", "dry_bulb_temperature", ",", "wind_speed", ",", "atmospheric_pressure", "=", "None", ",", "timestep", "=", "1", ",", "is_leap_year", "=", "False", ",", "use_disc", "=", "False", ")", ":", "# check input data", "assert", "len", "(", "cloud_cover", ")", "==", "len", "(", "relative_humidity", ")", "==", "len", "(", "dry_bulb_temperature", ")", "==", "len", "(", "wind_speed", ")", ",", "'lengths of input climate data must match.'", "assert", "len", "(", "cloud_cover", ")", "/", "timestep", "==", "cls", ".", "hour_count", "(", "is_leap_year", ")", ",", "'input climate data must be annual.'", "assert", "isinstance", "(", "timestep", ",", "int", ")", ",", "'timestep must be an'", "' integer. Got {}'", ".", "format", "(", "type", "(", "timestep", ")", ")", "if", "atmospheric_pressure", "is", "not", "None", ":", "assert", "len", "(", "atmospheric_pressure", ")", "==", "len", "(", "cloud_cover", ")", ",", "'length pf atmospheric_pressure must match the other input lists.'", "else", ":", "atmospheric_pressure", "=", "[", "101325", "]", "*", "cls", ".", "hour_count", "(", "is_leap_year", ")", "*", "timestep", "# initiate sunpath based on location", "sp", "=", "Sunpath", ".", "from_location", "(", "location", ")", "sp", ".", "is_leap_year", "=", "is_leap_year", "# calculate parameters needed for zhang-huang irradiance", "date_times", "=", "[", "]", "altitudes", "=", "[", "]", "doys", "=", "[", "]", "dry_bulb_t3_hrs", "=", "[", "]", "for", "count", ",", "t_date", "in", "enumerate", "(", "cls", ".", "_get_datetimes", "(", "timestep", ",", "is_leap_year", ")", ")", ":", "date_times", ".", "append", "(", "t_date", ")", "sun", "=", "sp", ".", "calculate_sun_from_date_time", "(", "t_date", ")", "altitudes", ".", "append", "(", "sun", ".", "altitude", ")", "doys", ".", "append", "(", "sun", ".", "datetime", ".", "doy", ")", "dry_bulb_t3_hrs", ".", "append", "(", "dry_bulb_temperature", "[", "count", "-", "(", "3", "*", "timestep", ")", "]", ")", "# calculate zhang-huang irradiance", "dir_ir", ",", "diff_ir", "=", "zhang_huang_solar_split", "(", "altitudes", ",", "doys", ",", "cloud_cover", ",", "relative_humidity", ",", "dry_bulb_temperature", ",", "dry_bulb_t3_hrs", ",", "wind_speed", ",", "atmospheric_pressure", ",", "use_disc", ")", "# assemble the results into DataCollections", "metadata", "=", "{", "'source'", ":", "location", ".", "source", ",", "'country'", ":", "location", ".", "country", ",", "'city'", ":", "location", ".", "city", "}", "direct_norm_rad", ",", "diffuse_horiz_rad", "=", "cls", ".", "_get_data_collections", "(", "dir_ir", ",", "diff_ir", ",", "metadata", ",", "timestep", ",", "is_leap_year", ")", "return", "cls", "(", "location", ",", "direct_norm_rad", ",", "diffuse_horiz_rad", ",", "timestep", ",", "is_leap_year", ")" ]
Create a wea object from climate data using the Zhang-Huang model. The Zhang-Huang solar model was developed to estimate solar irradiance for weather stations that lack such values, which are typically colleted with a pyranometer. Using total cloud cover, dry-bulb temperature, relative humidity, and wind speed as inputs the Zhang-Huang estimates global horizontal irradiance by means of a regression model across these variables. For more information on the Zhang-Huang model, see the EnergyPlus Engineering Reference: https://bigladdersoftware.com/epx/docs/8-7/engineering-reference/climate-calculations.html#zhang-huang-solar-model Args: location: Ladybug location object. cloud_cover: A list of annual float values between 0 and 1 that represent the fraction of the sky dome covered in clouds (0 = clear; 1 = completely overcast) relative_humidity: A list of annual float values between 0 and 100 that represent the relative humidity in percent. dry_bulb_temperature: A list of annual float values that represent the dry bulb temperature in degrees Celcius. wind_speed: A list of annual float values that represent the wind speed in meters per second. atmospheric_pressure: An optional list of float values that represent the atmospheric pressure in Pa. If None or left blank, pressure at sea level will be used (101325 Pa). timestep: An optional integer to set the number of time steps per hour. Default is 1 for one value per hour. is_leap_year: A boolean to indicate if values are representing a leap year. Default is False. use_disc: Set to True to use the original DISC model as opposed to the newer and more accurate DIRINT model. Default is False.
[ "Create", "a", "wea", "object", "from", "climate", "data", "using", "the", "Zhang", "-", "Huang", "model", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L357-L437
4,653
ladybug-tools/ladybug
ladybug/wea.py
Wea.datetimes
def datetimes(self): """Datetimes in wea file.""" if self.timestep == 1: return tuple(dt.add_minute(30) for dt in self.direct_normal_irradiance.datetimes) else: return self.direct_normal_irradiance.datetimes
python
def datetimes(self): """Datetimes in wea file.""" if self.timestep == 1: return tuple(dt.add_minute(30) for dt in self.direct_normal_irradiance.datetimes) else: return self.direct_normal_irradiance.datetimes
[ "def", "datetimes", "(", "self", ")", ":", "if", "self", ".", "timestep", "==", "1", ":", "return", "tuple", "(", "dt", ".", "add_minute", "(", "30", ")", "for", "dt", "in", "self", ".", "direct_normal_irradiance", ".", "datetimes", ")", "else", ":", "return", "self", ".", "direct_normal_irradiance", ".", "datetimes" ]
Datetimes in wea file.
[ "Datetimes", "in", "wea", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L450-L456
4,654
ladybug-tools/ladybug
ladybug/wea.py
Wea.global_horizontal_irradiance
def global_horizontal_irradiance(self): """Returns the global horizontal irradiance at each timestep.""" analysis_period = AnalysisPeriod(timestep=self.timestep, is_leap_year=self.is_leap_year) header_ghr = Header(data_type=GlobalHorizontalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=self.metadata) glob_horiz = [] sp = Sunpath.from_location(self.location) sp.is_leap_year = self.is_leap_year for dt, dnr, dhr in zip(self.datetimes, self.direct_normal_irradiance, self.diffuse_horizontal_irradiance): sun = sp.calculate_sun_from_date_time(dt) glob_horiz.append(dhr + dnr * math.sin(math.radians(sun.altitude))) return HourlyContinuousCollection(header_ghr, glob_horiz)
python
def global_horizontal_irradiance(self): """Returns the global horizontal irradiance at each timestep.""" analysis_period = AnalysisPeriod(timestep=self.timestep, is_leap_year=self.is_leap_year) header_ghr = Header(data_type=GlobalHorizontalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=self.metadata) glob_horiz = [] sp = Sunpath.from_location(self.location) sp.is_leap_year = self.is_leap_year for dt, dnr, dhr in zip(self.datetimes, self.direct_normal_irradiance, self.diffuse_horizontal_irradiance): sun = sp.calculate_sun_from_date_time(dt) glob_horiz.append(dhr + dnr * math.sin(math.radians(sun.altitude))) return HourlyContinuousCollection(header_ghr, glob_horiz)
[ "def", "global_horizontal_irradiance", "(", "self", ")", ":", "analysis_period", "=", "AnalysisPeriod", "(", "timestep", "=", "self", ".", "timestep", ",", "is_leap_year", "=", "self", ".", "is_leap_year", ")", "header_ghr", "=", "Header", "(", "data_type", "=", "GlobalHorizontalIrradiance", "(", ")", ",", "unit", "=", "'W/m2'", ",", "analysis_period", "=", "analysis_period", ",", "metadata", "=", "self", ".", "metadata", ")", "glob_horiz", "=", "[", "]", "sp", "=", "Sunpath", ".", "from_location", "(", "self", ".", "location", ")", "sp", ".", "is_leap_year", "=", "self", ".", "is_leap_year", "for", "dt", ",", "dnr", ",", "dhr", "in", "zip", "(", "self", ".", "datetimes", ",", "self", ".", "direct_normal_irradiance", ",", "self", ".", "diffuse_horizontal_irradiance", ")", ":", "sun", "=", "sp", ".", "calculate_sun_from_date_time", "(", "dt", ")", "glob_horiz", ".", "append", "(", "dhr", "+", "dnr", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "sun", ".", "altitude", ")", ")", ")", "return", "HourlyContinuousCollection", "(", "header_ghr", ",", "glob_horiz", ")" ]
Returns the global horizontal irradiance at each timestep.
[ "Returns", "the", "global", "horizontal", "irradiance", "at", "each", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L498-L513
4,655
ladybug-tools/ladybug
ladybug/wea.py
Wea.direct_horizontal_irradiance
def direct_horizontal_irradiance(self): """Returns the direct irradiance on a horizontal surface at each timestep. Note that this is different from the direct_normal_irradiance needed to construct a Wea, which is NORMAL and not HORIZONTAL.""" analysis_period = AnalysisPeriod(timestep=self.timestep, is_leap_year=self.is_leap_year) header_dhr = Header(data_type=DirectHorizontalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=self.metadata) direct_horiz = [] sp = Sunpath.from_location(self.location) sp.is_leap_year = self.is_leap_year for dt, dnr in zip(self.datetimes, self.direct_normal_irradiance): sun = sp.calculate_sun_from_date_time(dt) direct_horiz.append(dnr * math.sin(math.radians(sun.altitude))) return HourlyContinuousCollection(header_dhr, direct_horiz)
python
def direct_horizontal_irradiance(self): """Returns the direct irradiance on a horizontal surface at each timestep. Note that this is different from the direct_normal_irradiance needed to construct a Wea, which is NORMAL and not HORIZONTAL.""" analysis_period = AnalysisPeriod(timestep=self.timestep, is_leap_year=self.is_leap_year) header_dhr = Header(data_type=DirectHorizontalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=self.metadata) direct_horiz = [] sp = Sunpath.from_location(self.location) sp.is_leap_year = self.is_leap_year for dt, dnr in zip(self.datetimes, self.direct_normal_irradiance): sun = sp.calculate_sun_from_date_time(dt) direct_horiz.append(dnr * math.sin(math.radians(sun.altitude))) return HourlyContinuousCollection(header_dhr, direct_horiz)
[ "def", "direct_horizontal_irradiance", "(", "self", ")", ":", "analysis_period", "=", "AnalysisPeriod", "(", "timestep", "=", "self", ".", "timestep", ",", "is_leap_year", "=", "self", ".", "is_leap_year", ")", "header_dhr", "=", "Header", "(", "data_type", "=", "DirectHorizontalIrradiance", "(", ")", ",", "unit", "=", "'W/m2'", ",", "analysis_period", "=", "analysis_period", ",", "metadata", "=", "self", ".", "metadata", ")", "direct_horiz", "=", "[", "]", "sp", "=", "Sunpath", ".", "from_location", "(", "self", ".", "location", ")", "sp", ".", "is_leap_year", "=", "self", ".", "is_leap_year", "for", "dt", ",", "dnr", "in", "zip", "(", "self", ".", "datetimes", ",", "self", ".", "direct_normal_irradiance", ")", ":", "sun", "=", "sp", ".", "calculate_sun_from_date_time", "(", "dt", ")", "direct_horiz", ".", "append", "(", "dnr", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "sun", ".", "altitude", ")", ")", ")", "return", "HourlyContinuousCollection", "(", "header_dhr", ",", "direct_horiz", ")" ]
Returns the direct irradiance on a horizontal surface at each timestep. Note that this is different from the direct_normal_irradiance needed to construct a Wea, which is NORMAL and not HORIZONTAL.
[ "Returns", "the", "direct", "irradiance", "on", "a", "horizontal", "surface", "at", "each", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L516-L533
4,656
ladybug-tools/ladybug
ladybug/wea.py
Wea._get_datetimes
def _get_datetimes(timestep, is_leap_year): """List of datetimes based on timestep. This method should only be used for classmethods. For datetimes use datetiems or hoys methods. """ hour_count = 8760 + 24 if is_leap_year else 8760 adjust_time = 30 if timestep == 1 else 0 return tuple( DateTime.from_moy(60.0 * count / timestep + adjust_time, is_leap_year) for count in xrange(hour_count * timestep) )
python
def _get_datetimes(timestep, is_leap_year): """List of datetimes based on timestep. This method should only be used for classmethods. For datetimes use datetiems or hoys methods. """ hour_count = 8760 + 24 if is_leap_year else 8760 adjust_time = 30 if timestep == 1 else 0 return tuple( DateTime.from_moy(60.0 * count / timestep + adjust_time, is_leap_year) for count in xrange(hour_count * timestep) )
[ "def", "_get_datetimes", "(", "timestep", ",", "is_leap_year", ")", ":", "hour_count", "=", "8760", "+", "24", "if", "is_leap_year", "else", "8760", "adjust_time", "=", "30", "if", "timestep", "==", "1", "else", "0", "return", "tuple", "(", "DateTime", ".", "from_moy", "(", "60.0", "*", "count", "/", "timestep", "+", "adjust_time", ",", "is_leap_year", ")", "for", "count", "in", "xrange", "(", "hour_count", "*", "timestep", ")", ")" ]
List of datetimes based on timestep. This method should only be used for classmethods. For datetimes use datetiems or hoys methods.
[ "List", "of", "datetimes", "based", "on", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L550-L561
4,657
ladybug-tools/ladybug
ladybug/wea.py
Wea._get_data_collections
def _get_data_collections(dnr_values, dhr_values, metadata, timestep, is_leap_year): """Return two data collections for Direct Normal , Diffuse Horizontal """ analysis_period = AnalysisPeriod(timestep=timestep, is_leap_year=is_leap_year) dnr_header = Header(data_type=DirectNormalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=metadata) direct_norm_rad = HourlyContinuousCollection(dnr_header, dnr_values) dhr_header = Header(data_type=DiffuseHorizontalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=metadata) diffuse_horiz_rad = HourlyContinuousCollection(dhr_header, dhr_values) return direct_norm_rad, diffuse_horiz_rad
python
def _get_data_collections(dnr_values, dhr_values, metadata, timestep, is_leap_year): """Return two data collections for Direct Normal , Diffuse Horizontal """ analysis_period = AnalysisPeriod(timestep=timestep, is_leap_year=is_leap_year) dnr_header = Header(data_type=DirectNormalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=metadata) direct_norm_rad = HourlyContinuousCollection(dnr_header, dnr_values) dhr_header = Header(data_type=DiffuseHorizontalIrradiance(), unit='W/m2', analysis_period=analysis_period, metadata=metadata) diffuse_horiz_rad = HourlyContinuousCollection(dhr_header, dhr_values) return direct_norm_rad, diffuse_horiz_rad
[ "def", "_get_data_collections", "(", "dnr_values", ",", "dhr_values", ",", "metadata", ",", "timestep", ",", "is_leap_year", ")", ":", "analysis_period", "=", "AnalysisPeriod", "(", "timestep", "=", "timestep", ",", "is_leap_year", "=", "is_leap_year", ")", "dnr_header", "=", "Header", "(", "data_type", "=", "DirectNormalIrradiance", "(", ")", ",", "unit", "=", "'W/m2'", ",", "analysis_period", "=", "analysis_period", ",", "metadata", "=", "metadata", ")", "direct_norm_rad", "=", "HourlyContinuousCollection", "(", "dnr_header", ",", "dnr_values", ")", "dhr_header", "=", "Header", "(", "data_type", "=", "DiffuseHorizontalIrradiance", "(", ")", ",", "unit", "=", "'W/m2'", ",", "analysis_period", "=", "analysis_period", ",", "metadata", "=", "metadata", ")", "diffuse_horiz_rad", "=", "HourlyContinuousCollection", "(", "dhr_header", ",", "dhr_values", ")", "return", "direct_norm_rad", ",", "diffuse_horiz_rad" ]
Return two data collections for Direct Normal , Diffuse Horizontal
[ "Return", "two", "data", "collections", "for", "Direct", "Normal", "Diffuse", "Horizontal" ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L564-L579
4,658
ladybug-tools/ladybug
ladybug/wea.py
Wea.get_irradiance_value
def get_irradiance_value(self, month, day, hour): """Get direct and diffuse irradiance values for a point in time.""" dt = DateTime(month, day, hour, leap_year=self.is_leap_year) count = int(dt.hoy * self.timestep) return self.direct_normal_irradiance[count], \ self.diffuse_horizontal_irradiance[count]
python
def get_irradiance_value(self, month, day, hour): """Get direct and diffuse irradiance values for a point in time.""" dt = DateTime(month, day, hour, leap_year=self.is_leap_year) count = int(dt.hoy * self.timestep) return self.direct_normal_irradiance[count], \ self.diffuse_horizontal_irradiance[count]
[ "def", "get_irradiance_value", "(", "self", ",", "month", ",", "day", ",", "hour", ")", ":", "dt", "=", "DateTime", "(", "month", ",", "day", ",", "hour", ",", "leap_year", "=", "self", ".", "is_leap_year", ")", "count", "=", "int", "(", "dt", ".", "hoy", "*", "self", ".", "timestep", ")", "return", "self", ".", "direct_normal_irradiance", "[", "count", "]", ",", "self", ".", "diffuse_horizontal_irradiance", "[", "count", "]" ]
Get direct and diffuse irradiance values for a point in time.
[ "Get", "direct", "and", "diffuse", "irradiance", "values", "for", "a", "point", "in", "time", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L581-L586
4,659
ladybug-tools/ladybug
ladybug/wea.py
Wea.get_irradiance_value_for_hoy
def get_irradiance_value_for_hoy(self, hoy): """Get direct and diffuse irradiance values for an hoy.""" count = int(hoy * self.timestep) return self.direct_normal_irradiance[count], \ self.diffuse_horizontal_irradiance[count]
python
def get_irradiance_value_for_hoy(self, hoy): """Get direct and diffuse irradiance values for an hoy.""" count = int(hoy * self.timestep) return self.direct_normal_irradiance[count], \ self.diffuse_horizontal_irradiance[count]
[ "def", "get_irradiance_value_for_hoy", "(", "self", ",", "hoy", ")", ":", "count", "=", "int", "(", "hoy", "*", "self", ".", "timestep", ")", "return", "self", ".", "direct_normal_irradiance", "[", "count", "]", ",", "self", ".", "diffuse_horizontal_irradiance", "[", "count", "]" ]
Get direct and diffuse irradiance values for an hoy.
[ "Get", "direct", "and", "diffuse", "irradiance", "values", "for", "an", "hoy", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L588-L592
4,660
ladybug-tools/ladybug
ladybug/wea.py
Wea.directional_irradiance
def directional_irradiance(self, altitude=90, azimuth=180, ground_reflectance=0.2, isotrophic=True): """Returns the irradiance components facing a given altitude and azimuth. This method computes unobstructed solar flux facing a given altitude and azimuth. The default is set to return the golbal horizontal irradiance, assuming an altitude facing straight up (90 degrees). Args: altitude: A number between -90 and 90 that represents the altitude at which irradiance is being evaluated in degrees. azimuth: A number between 0 and 360 that represents the azimuth at wich irradiance is being evaluated in degrees. ground_reflectance: A number between 0 and 1 that represents the reflectance of the ground. Default is set to 0.2. Some common ground reflectances are: urban: 0.18 grass: 0.20 fresh grass: 0.26 soil: 0.17 sand: 0.40 snow: 0.65 fresh_snow: 0.75 asphalt: 0.12 concrete: 0.30 sea: 0.06 isotrophic: A boolean value that sets whether an istotrophic sky is used (as opposed to an anisotrophic sky). An isotrophic sky assummes an even distribution of diffuse irradiance across the sky while an anisotrophic sky places more diffuse irradiance near the solar disc. Default is set to True for isotrophic Returns: total_irradiance: A data collection of total solar irradiance. direct_irradiance: A data collection of direct solar irradiance. diffuse_irradiance: A data collection of diffuse sky solar irradiance. reflected_irradiance: A data collection of ground reflected solar irradiance. """ # function to convert polar coordinates to xyz. def pol2cart(phi, theta): mult = math.cos(theta) x = math.sin(phi) * mult y = math.cos(phi) * mult z = math.sin(theta) return Vector3(x, y, z) # convert the altitude and azimuth to a normal vector normal = pol2cart(math.radians(azimuth), math.radians(altitude)) # create sunpath and get altitude at every timestep of the year direct_irr, diffuse_irr, reflected_irr, total_irr = [], [], [], [] sp = Sunpath.from_location(self.location) sp.is_leap_year = self.is_leap_year for dt, dnr, dhr in zip(self.datetimes, self.direct_normal_irradiance, self.diffuse_horizontal_irradiance): sun = sp.calculate_sun_from_date_time(dt) sun_vec = pol2cart(math.radians(sun.azimuth), math.radians(sun.altitude)) vec_angle = sun_vec.angle(normal) # direct irradiance on surface srf_dir = 0 if sun.altitude > 0 and vec_angle < math.pi / 2: srf_dir = dnr * math.cos(vec_angle) # diffuse irradiance on surface if isotrophic is True: srf_dif = dhr * ((math.sin(math.radians(altitude)) / 2) + 0.5) else: y = max(0.45, 0.55 + (0.437 * math.cos(vec_angle)) + 0.313 * math.cos(vec_angle) * 0.313 * math.cos(vec_angle)) srf_dif = self.dhr * (y * ( math.sin(math.radians(abs(90 - altitude)))) + math.cos(math.radians(abs(90 - altitude)))) # reflected irradiance on surface. e_glob = dhr + dnr * math.cos(math.radians(90 - sun.altitude)) srf_ref = e_glob * ground_reflectance * (0.5 - (math.sin( math.radians(altitude)) / 2)) # add it all together direct_irr.append(srf_dir) diffuse_irr.append(srf_dif) reflected_irr.append(srf_ref) total_irr.append(srf_dir + srf_dif + srf_ref) # create the headers a_per = AnalysisPeriod(timestep=self.timestep, is_leap_year=self.is_leap_year) direct_hea = diffuse_hea = reflected_hea = total_hea = \ Header(Irradiance(), 'W/m2', a_per, self.metadata) # create the data collections direct_irradiance = HourlyContinuousCollection(direct_hea, direct_irr) diffuse_irradiance = HourlyContinuousCollection(diffuse_hea, diffuse_irr) reflected_irradiance = HourlyContinuousCollection(reflected_hea, reflected_irr) total_irradiance = HourlyContinuousCollection(total_hea, total_irr) return total_irradiance, direct_irradiance, \ diffuse_irradiance, reflected_irradiance
python
def directional_irradiance(self, altitude=90, azimuth=180, ground_reflectance=0.2, isotrophic=True): """Returns the irradiance components facing a given altitude and azimuth. This method computes unobstructed solar flux facing a given altitude and azimuth. The default is set to return the golbal horizontal irradiance, assuming an altitude facing straight up (90 degrees). Args: altitude: A number between -90 and 90 that represents the altitude at which irradiance is being evaluated in degrees. azimuth: A number between 0 and 360 that represents the azimuth at wich irradiance is being evaluated in degrees. ground_reflectance: A number between 0 and 1 that represents the reflectance of the ground. Default is set to 0.2. Some common ground reflectances are: urban: 0.18 grass: 0.20 fresh grass: 0.26 soil: 0.17 sand: 0.40 snow: 0.65 fresh_snow: 0.75 asphalt: 0.12 concrete: 0.30 sea: 0.06 isotrophic: A boolean value that sets whether an istotrophic sky is used (as opposed to an anisotrophic sky). An isotrophic sky assummes an even distribution of diffuse irradiance across the sky while an anisotrophic sky places more diffuse irradiance near the solar disc. Default is set to True for isotrophic Returns: total_irradiance: A data collection of total solar irradiance. direct_irradiance: A data collection of direct solar irradiance. diffuse_irradiance: A data collection of diffuse sky solar irradiance. reflected_irradiance: A data collection of ground reflected solar irradiance. """ # function to convert polar coordinates to xyz. def pol2cart(phi, theta): mult = math.cos(theta) x = math.sin(phi) * mult y = math.cos(phi) * mult z = math.sin(theta) return Vector3(x, y, z) # convert the altitude and azimuth to a normal vector normal = pol2cart(math.radians(azimuth), math.radians(altitude)) # create sunpath and get altitude at every timestep of the year direct_irr, diffuse_irr, reflected_irr, total_irr = [], [], [], [] sp = Sunpath.from_location(self.location) sp.is_leap_year = self.is_leap_year for dt, dnr, dhr in zip(self.datetimes, self.direct_normal_irradiance, self.diffuse_horizontal_irradiance): sun = sp.calculate_sun_from_date_time(dt) sun_vec = pol2cart(math.radians(sun.azimuth), math.radians(sun.altitude)) vec_angle = sun_vec.angle(normal) # direct irradiance on surface srf_dir = 0 if sun.altitude > 0 and vec_angle < math.pi / 2: srf_dir = dnr * math.cos(vec_angle) # diffuse irradiance on surface if isotrophic is True: srf_dif = dhr * ((math.sin(math.radians(altitude)) / 2) + 0.5) else: y = max(0.45, 0.55 + (0.437 * math.cos(vec_angle)) + 0.313 * math.cos(vec_angle) * 0.313 * math.cos(vec_angle)) srf_dif = self.dhr * (y * ( math.sin(math.radians(abs(90 - altitude)))) + math.cos(math.radians(abs(90 - altitude)))) # reflected irradiance on surface. e_glob = dhr + dnr * math.cos(math.radians(90 - sun.altitude)) srf_ref = e_glob * ground_reflectance * (0.5 - (math.sin( math.radians(altitude)) / 2)) # add it all together direct_irr.append(srf_dir) diffuse_irr.append(srf_dif) reflected_irr.append(srf_ref) total_irr.append(srf_dir + srf_dif + srf_ref) # create the headers a_per = AnalysisPeriod(timestep=self.timestep, is_leap_year=self.is_leap_year) direct_hea = diffuse_hea = reflected_hea = total_hea = \ Header(Irradiance(), 'W/m2', a_per, self.metadata) # create the data collections direct_irradiance = HourlyContinuousCollection(direct_hea, direct_irr) diffuse_irradiance = HourlyContinuousCollection(diffuse_hea, diffuse_irr) reflected_irradiance = HourlyContinuousCollection(reflected_hea, reflected_irr) total_irradiance = HourlyContinuousCollection(total_hea, total_irr) return total_irradiance, direct_irradiance, \ diffuse_irradiance, reflected_irradiance
[ "def", "directional_irradiance", "(", "self", ",", "altitude", "=", "90", ",", "azimuth", "=", "180", ",", "ground_reflectance", "=", "0.2", ",", "isotrophic", "=", "True", ")", ":", "# function to convert polar coordinates to xyz.", "def", "pol2cart", "(", "phi", ",", "theta", ")", ":", "mult", "=", "math", ".", "cos", "(", "theta", ")", "x", "=", "math", ".", "sin", "(", "phi", ")", "*", "mult", "y", "=", "math", ".", "cos", "(", "phi", ")", "*", "mult", "z", "=", "math", ".", "sin", "(", "theta", ")", "return", "Vector3", "(", "x", ",", "y", ",", "z", ")", "# convert the altitude and azimuth to a normal vector", "normal", "=", "pol2cart", "(", "math", ".", "radians", "(", "azimuth", ")", ",", "math", ".", "radians", "(", "altitude", ")", ")", "# create sunpath and get altitude at every timestep of the year", "direct_irr", ",", "diffuse_irr", ",", "reflected_irr", ",", "total_irr", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "sp", "=", "Sunpath", ".", "from_location", "(", "self", ".", "location", ")", "sp", ".", "is_leap_year", "=", "self", ".", "is_leap_year", "for", "dt", ",", "dnr", ",", "dhr", "in", "zip", "(", "self", ".", "datetimes", ",", "self", ".", "direct_normal_irradiance", ",", "self", ".", "diffuse_horizontal_irradiance", ")", ":", "sun", "=", "sp", ".", "calculate_sun_from_date_time", "(", "dt", ")", "sun_vec", "=", "pol2cart", "(", "math", ".", "radians", "(", "sun", ".", "azimuth", ")", ",", "math", ".", "radians", "(", "sun", ".", "altitude", ")", ")", "vec_angle", "=", "sun_vec", ".", "angle", "(", "normal", ")", "# direct irradiance on surface", "srf_dir", "=", "0", "if", "sun", ".", "altitude", ">", "0", "and", "vec_angle", "<", "math", ".", "pi", "/", "2", ":", "srf_dir", "=", "dnr", "*", "math", ".", "cos", "(", "vec_angle", ")", "# diffuse irradiance on surface", "if", "isotrophic", "is", "True", ":", "srf_dif", "=", "dhr", "*", "(", "(", "math", ".", "sin", "(", "math", ".", "radians", "(", "altitude", ")", ")", "/", "2", ")", "+", "0.5", ")", "else", ":", "y", "=", "max", "(", "0.45", ",", "0.55", "+", "(", "0.437", "*", "math", ".", "cos", "(", "vec_angle", ")", ")", "+", "0.313", "*", "math", ".", "cos", "(", "vec_angle", ")", "*", "0.313", "*", "math", ".", "cos", "(", "vec_angle", ")", ")", "srf_dif", "=", "self", ".", "dhr", "*", "(", "y", "*", "(", "math", ".", "sin", "(", "math", ".", "radians", "(", "abs", "(", "90", "-", "altitude", ")", ")", ")", ")", "+", "math", ".", "cos", "(", "math", ".", "radians", "(", "abs", "(", "90", "-", "altitude", ")", ")", ")", ")", "# reflected irradiance on surface.", "e_glob", "=", "dhr", "+", "dnr", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "90", "-", "sun", ".", "altitude", ")", ")", "srf_ref", "=", "e_glob", "*", "ground_reflectance", "*", "(", "0.5", "-", "(", "math", ".", "sin", "(", "math", ".", "radians", "(", "altitude", ")", ")", "/", "2", ")", ")", "# add it all together", "direct_irr", ".", "append", "(", "srf_dir", ")", "diffuse_irr", ".", "append", "(", "srf_dif", ")", "reflected_irr", ".", "append", "(", "srf_ref", ")", "total_irr", ".", "append", "(", "srf_dir", "+", "srf_dif", "+", "srf_ref", ")", "# create the headers", "a_per", "=", "AnalysisPeriod", "(", "timestep", "=", "self", ".", "timestep", ",", "is_leap_year", "=", "self", ".", "is_leap_year", ")", "direct_hea", "=", "diffuse_hea", "=", "reflected_hea", "=", "total_hea", "=", "Header", "(", "Irradiance", "(", ")", ",", "'W/m2'", ",", "a_per", ",", "self", ".", "metadata", ")", "# create the data collections", "direct_irradiance", "=", "HourlyContinuousCollection", "(", "direct_hea", ",", "direct_irr", ")", "diffuse_irradiance", "=", "HourlyContinuousCollection", "(", "diffuse_hea", ",", "diffuse_irr", ")", "reflected_irradiance", "=", "HourlyContinuousCollection", "(", "reflected_hea", ",", "reflected_irr", ")", "total_irradiance", "=", "HourlyContinuousCollection", "(", "total_hea", ",", "total_irr", ")", "return", "total_irradiance", ",", "direct_irradiance", ",", "diffuse_irradiance", ",", "reflected_irradiance" ]
Returns the irradiance components facing a given altitude and azimuth. This method computes unobstructed solar flux facing a given altitude and azimuth. The default is set to return the golbal horizontal irradiance, assuming an altitude facing straight up (90 degrees). Args: altitude: A number between -90 and 90 that represents the altitude at which irradiance is being evaluated in degrees. azimuth: A number between 0 and 360 that represents the azimuth at wich irradiance is being evaluated in degrees. ground_reflectance: A number between 0 and 1 that represents the reflectance of the ground. Default is set to 0.2. Some common ground reflectances are: urban: 0.18 grass: 0.20 fresh grass: 0.26 soil: 0.17 sand: 0.40 snow: 0.65 fresh_snow: 0.75 asphalt: 0.12 concrete: 0.30 sea: 0.06 isotrophic: A boolean value that sets whether an istotrophic sky is used (as opposed to an anisotrophic sky). An isotrophic sky assummes an even distribution of diffuse irradiance across the sky while an anisotrophic sky places more diffuse irradiance near the solar disc. Default is set to True for isotrophic Returns: total_irradiance: A data collection of total solar irradiance. direct_irradiance: A data collection of direct solar irradiance. diffuse_irradiance: A data collection of diffuse sky solar irradiance. reflected_irradiance: A data collection of ground reflected solar irradiance.
[ "Returns", "the", "irradiance", "components", "facing", "a", "given", "altitude", "and", "azimuth", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L594-L692
4,661
ladybug-tools/ladybug
ladybug/wea.py
Wea.header
def header(self): """Wea header.""" return "place %s\n" % self.location.city + \ "latitude %.2f\n" % self.location.latitude + \ "longitude %.2f\n" % -self.location.longitude + \ "time_zone %d\n" % (-self.location.time_zone * 15) + \ "site_elevation %.1f\n" % self.location.elevation + \ "weather_data_file_units 1\n"
python
def header(self): """Wea header.""" return "place %s\n" % self.location.city + \ "latitude %.2f\n" % self.location.latitude + \ "longitude %.2f\n" % -self.location.longitude + \ "time_zone %d\n" % (-self.location.time_zone * 15) + \ "site_elevation %.1f\n" % self.location.elevation + \ "weather_data_file_units 1\n"
[ "def", "header", "(", "self", ")", ":", "return", "\"place %s\\n\"", "%", "self", ".", "location", ".", "city", "+", "\"latitude %.2f\\n\"", "%", "self", ".", "location", ".", "latitude", "+", "\"longitude %.2f\\n\"", "%", "-", "self", ".", "location", ".", "longitude", "+", "\"time_zone %d\\n\"", "%", "(", "-", "self", ".", "location", ".", "time_zone", "*", "15", ")", "+", "\"site_elevation %.1f\\n\"", "%", "self", ".", "location", ".", "elevation", "+", "\"weather_data_file_units 1\\n\"" ]
Wea header.
[ "Wea", "header", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L695-L702
4,662
ladybug-tools/ladybug
ladybug/wea.py
Wea.write
def write(self, file_path, hoys=None, write_hours=False): """Write the wea file. WEA carries irradiance values from epw and is what gendaymtx uses to generate the sky. """ if not file_path.lower().endswith('.wea'): file_path += '.wea' # generate hoys in wea file based on timestep full_wea = False if not hoys: hoys = self.hoys full_wea = True # write header lines = [self.header] if full_wea: # there is no user input for hoys, write it for all the hours for dir_rad, dif_rad, dt in zip(self.direct_normal_irradiance, self.diffuse_horizontal_irradiance, self.datetimes): line = "%d %d %.3f %d %d\n" \ % (dt.month, dt.day, dt.float_hour, dir_rad, dif_rad) lines.append(line) else: # output wea based on user request for hoy in hoys: try: dir_rad, dif_rad = self.get_irradiance_value_for_hoy(hoy) except IndexError: print('Warn: Wea data for {} is not available!'.format(dt)) continue dt = DateTime.from_hoy(hoy) dt = dt.add_minute(30) if self.timestep == 1 else dt line = "%d %d %.3f %d %d\n" \ % (dt.month, dt.day, dt.float_hour, dir_rad, dif_rad) lines.append(line) file_data = ''.join(lines) write_to_file(file_path, file_data, True) if write_hours: hrs_file_path = file_path[:-4] + '.hrs' hrs_data = ','.join(str(h) for h in hoys) + '\n' write_to_file(hrs_file_path, hrs_data, True) return file_path
python
def write(self, file_path, hoys=None, write_hours=False): """Write the wea file. WEA carries irradiance values from epw and is what gendaymtx uses to generate the sky. """ if not file_path.lower().endswith('.wea'): file_path += '.wea' # generate hoys in wea file based on timestep full_wea = False if not hoys: hoys = self.hoys full_wea = True # write header lines = [self.header] if full_wea: # there is no user input for hoys, write it for all the hours for dir_rad, dif_rad, dt in zip(self.direct_normal_irradiance, self.diffuse_horizontal_irradiance, self.datetimes): line = "%d %d %.3f %d %d\n" \ % (dt.month, dt.day, dt.float_hour, dir_rad, dif_rad) lines.append(line) else: # output wea based on user request for hoy in hoys: try: dir_rad, dif_rad = self.get_irradiance_value_for_hoy(hoy) except IndexError: print('Warn: Wea data for {} is not available!'.format(dt)) continue dt = DateTime.from_hoy(hoy) dt = dt.add_minute(30) if self.timestep == 1 else dt line = "%d %d %.3f %d %d\n" \ % (dt.month, dt.day, dt.float_hour, dir_rad, dif_rad) lines.append(line) file_data = ''.join(lines) write_to_file(file_path, file_data, True) if write_hours: hrs_file_path = file_path[:-4] + '.hrs' hrs_data = ','.join(str(h) for h in hoys) + '\n' write_to_file(hrs_file_path, hrs_data, True) return file_path
[ "def", "write", "(", "self", ",", "file_path", ",", "hoys", "=", "None", ",", "write_hours", "=", "False", ")", ":", "if", "not", "file_path", ".", "lower", "(", ")", ".", "endswith", "(", "'.wea'", ")", ":", "file_path", "+=", "'.wea'", "# generate hoys in wea file based on timestep", "full_wea", "=", "False", "if", "not", "hoys", ":", "hoys", "=", "self", ".", "hoys", "full_wea", "=", "True", "# write header", "lines", "=", "[", "self", ".", "header", "]", "if", "full_wea", ":", "# there is no user input for hoys, write it for all the hours", "for", "dir_rad", ",", "dif_rad", ",", "dt", "in", "zip", "(", "self", ".", "direct_normal_irradiance", ",", "self", ".", "diffuse_horizontal_irradiance", ",", "self", ".", "datetimes", ")", ":", "line", "=", "\"%d %d %.3f %d %d\\n\"", "%", "(", "dt", ".", "month", ",", "dt", ".", "day", ",", "dt", ".", "float_hour", ",", "dir_rad", ",", "dif_rad", ")", "lines", ".", "append", "(", "line", ")", "else", ":", "# output wea based on user request", "for", "hoy", "in", "hoys", ":", "try", ":", "dir_rad", ",", "dif_rad", "=", "self", ".", "get_irradiance_value_for_hoy", "(", "hoy", ")", "except", "IndexError", ":", "print", "(", "'Warn: Wea data for {} is not available!'", ".", "format", "(", "dt", ")", ")", "continue", "dt", "=", "DateTime", ".", "from_hoy", "(", "hoy", ")", "dt", "=", "dt", ".", "add_minute", "(", "30", ")", "if", "self", ".", "timestep", "==", "1", "else", "dt", "line", "=", "\"%d %d %.3f %d %d\\n\"", "%", "(", "dt", ".", "month", ",", "dt", ".", "day", ",", "dt", ".", "float_hour", ",", "dir_rad", ",", "dif_rad", ")", "lines", ".", "append", "(", "line", ")", "file_data", "=", "''", ".", "join", "(", "lines", ")", "write_to_file", "(", "file_path", ",", "file_data", ",", "True", ")", "if", "write_hours", ":", "hrs_file_path", "=", "file_path", "[", ":", "-", "4", "]", "+", "'.hrs'", "hrs_data", "=", "','", ".", "join", "(", "str", "(", "h", ")", "for", "h", "in", "hoys", ")", "+", "'\\n'", "write_to_file", "(", "hrs_file_path", ",", "hrs_data", ",", "True", ")", "return", "file_path" ]
Write the wea file. WEA carries irradiance values from epw and is what gendaymtx uses to generate the sky.
[ "Write", "the", "wea", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L725-L773
4,663
ladybug-tools/ladybug
ladybug/listoperations.py
flatten
def flatten(input_list): """Return a flattened genertor from an input list. Usage: input_list = [['a'], ['b', 'c', 'd'], [['e']], ['f']] list(flatten(input_list)) >> ['a', 'b', 'c', 'd', 'e', 'f'] """ for el in input_list: if isinstance(el, collections.Iterable) \ and not isinstance(el, basestring): for sub in flatten(el): yield sub else: yield el
python
def flatten(input_list): """Return a flattened genertor from an input list. Usage: input_list = [['a'], ['b', 'c', 'd'], [['e']], ['f']] list(flatten(input_list)) >> ['a', 'b', 'c', 'd', 'e', 'f'] """ for el in input_list: if isinstance(el, collections.Iterable) \ and not isinstance(el, basestring): for sub in flatten(el): yield sub else: yield el
[ "def", "flatten", "(", "input_list", ")", ":", "for", "el", "in", "input_list", ":", "if", "isinstance", "(", "el", ",", "collections", ".", "Iterable", ")", "and", "not", "isinstance", "(", "el", ",", "basestring", ")", ":", "for", "sub", "in", "flatten", "(", "el", ")", ":", "yield", "sub", "else", ":", "yield", "el" ]
Return a flattened genertor from an input list. Usage: input_list = [['a'], ['b', 'c', 'd'], [['e']], ['f']] list(flatten(input_list)) >> ['a', 'b', 'c', 'd', 'e', 'f']
[ "Return", "a", "flattened", "genertor", "from", "an", "input", "list", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/listoperations.py#L8-L23
4,664
ladybug-tools/ladybug
ladybug/listoperations.py
unflatten
def unflatten(guide, falttened_input): """Unflatten a falttened generator. Args: guide: A guide list to follow the structure falttened_input: A flattened iterator object Usage: guide = [["a"], ["b","c","d"], [["e"]], ["f"]] input_list = [0, 1, 2, 3, 4, 5, 6, 7] unflatten(guide, iter(input_list)) >> [[0], [1, 2, 3], [[4]], [5]] """ return [unflatten(sub_list, falttened_input) if isinstance(sub_list, list) else next(falttened_input) for sub_list in guide]
python
def unflatten(guide, falttened_input): """Unflatten a falttened generator. Args: guide: A guide list to follow the structure falttened_input: A flattened iterator object Usage: guide = [["a"], ["b","c","d"], [["e"]], ["f"]] input_list = [0, 1, 2, 3, 4, 5, 6, 7] unflatten(guide, iter(input_list)) >> [[0], [1, 2, 3], [[4]], [5]] """ return [unflatten(sub_list, falttened_input) if isinstance(sub_list, list) else next(falttened_input) for sub_list in guide]
[ "def", "unflatten", "(", "guide", ",", "falttened_input", ")", ":", "return", "[", "unflatten", "(", "sub_list", ",", "falttened_input", ")", "if", "isinstance", "(", "sub_list", ",", "list", ")", "else", "next", "(", "falttened_input", ")", "for", "sub_list", "in", "guide", "]" ]
Unflatten a falttened generator. Args: guide: A guide list to follow the structure falttened_input: A flattened iterator object Usage: guide = [["a"], ["b","c","d"], [["e"]], ["f"]] input_list = [0, 1, 2, 3, 4, 5, 6, 7] unflatten(guide, iter(input_list)) >> [[0], [1, 2, 3], [[4]], [5]]
[ "Unflatten", "a", "falttened", "generator", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/listoperations.py#L26-L41
4,665
ladybug-tools/ladybug
ladybug/color.py
ColorRange.color
def color(self, value): """Return color for an input value.""" assert self._is_domain_set, \ "Domain is not set. Use self.domain to set the domain." if self._ctype == 2: # if ordinal map the value and color try: return self._colors[self._domain.index(value)] except ValueError: raise ValueError( "%s is not a valid input for ordinal type.\n" % str(value) + "List of valid values are %s" % ";".join(map(str, self._domain)) ) if value < self._domain[0]: return self._colors[0] if value > self._domain[-1]: return self._colors[-1] # find the index of the value in domain for count, d in enumerate(self._domain): if d <= value <= self._domain[count + 1]: if self._ctype == 0: return self._cal_color(value, count) if self._ctype == 1: return self._colors[count + 1]
python
def color(self, value): """Return color for an input value.""" assert self._is_domain_set, \ "Domain is not set. Use self.domain to set the domain." if self._ctype == 2: # if ordinal map the value and color try: return self._colors[self._domain.index(value)] except ValueError: raise ValueError( "%s is not a valid input for ordinal type.\n" % str(value) + "List of valid values are %s" % ";".join(map(str, self._domain)) ) if value < self._domain[0]: return self._colors[0] if value > self._domain[-1]: return self._colors[-1] # find the index of the value in domain for count, d in enumerate(self._domain): if d <= value <= self._domain[count + 1]: if self._ctype == 0: return self._cal_color(value, count) if self._ctype == 1: return self._colors[count + 1]
[ "def", "color", "(", "self", ",", "value", ")", ":", "assert", "self", ".", "_is_domain_set", ",", "\"Domain is not set. Use self.domain to set the domain.\"", "if", "self", ".", "_ctype", "==", "2", ":", "# if ordinal map the value and color", "try", ":", "return", "self", ".", "_colors", "[", "self", ".", "_domain", ".", "index", "(", "value", ")", "]", "except", "ValueError", ":", "raise", "ValueError", "(", "\"%s is not a valid input for ordinal type.\\n\"", "%", "str", "(", "value", ")", "+", "\"List of valid values are %s\"", "%", "\";\"", ".", "join", "(", "map", "(", "str", ",", "self", ".", "_domain", ")", ")", ")", "if", "value", "<", "self", ".", "_domain", "[", "0", "]", ":", "return", "self", ".", "_colors", "[", "0", "]", "if", "value", ">", "self", ".", "_domain", "[", "-", "1", "]", ":", "return", "self", ".", "_colors", "[", "-", "1", "]", "# find the index of the value in domain", "for", "count", ",", "d", "in", "enumerate", "(", "self", ".", "_domain", ")", ":", "if", "d", "<=", "value", "<=", "self", ".", "_domain", "[", "count", "+", "1", "]", ":", "if", "self", ".", "_ctype", "==", "0", ":", "return", "self", ".", "_cal_color", "(", "value", ",", "count", ")", "if", "self", ".", "_ctype", "==", "1", ":", "return", "self", ".", "_colors", "[", "count", "+", "1", "]" ]
Return color for an input value.
[ "Return", "color", "for", "an", "input", "value", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/color.py#L436-L462
4,666
ladybug-tools/ladybug
ladybug/color.py
ColorRange._cal_color
def _cal_color(self, value, color_index): """Blend between two colors based on input value.""" range_min_p = self._domain[color_index] range_p = self._domain[color_index + 1] - range_min_p try: factor = (value - range_min_p) / range_p except ZeroDivisionError: factor = 0 min_color = self.colors[color_index] max_color = self.colors[color_index + 1] red = round(factor * (max_color.r - min_color.r) + min_color.r) green = round(factor * (max_color.g - min_color.g) + min_color.g) blue = round(factor * (max_color.b - min_color.b) + min_color.b) return Color(red, green, blue)
python
def _cal_color(self, value, color_index): """Blend between two colors based on input value.""" range_min_p = self._domain[color_index] range_p = self._domain[color_index + 1] - range_min_p try: factor = (value - range_min_p) / range_p except ZeroDivisionError: factor = 0 min_color = self.colors[color_index] max_color = self.colors[color_index + 1] red = round(factor * (max_color.r - min_color.r) + min_color.r) green = round(factor * (max_color.g - min_color.g) + min_color.g) blue = round(factor * (max_color.b - min_color.b) + min_color.b) return Color(red, green, blue)
[ "def", "_cal_color", "(", "self", ",", "value", ",", "color_index", ")", ":", "range_min_p", "=", "self", ".", "_domain", "[", "color_index", "]", "range_p", "=", "self", ".", "_domain", "[", "color_index", "+", "1", "]", "-", "range_min_p", "try", ":", "factor", "=", "(", "value", "-", "range_min_p", ")", "/", "range_p", "except", "ZeroDivisionError", ":", "factor", "=", "0", "min_color", "=", "self", ".", "colors", "[", "color_index", "]", "max_color", "=", "self", ".", "colors", "[", "color_index", "+", "1", "]", "red", "=", "round", "(", "factor", "*", "(", "max_color", ".", "r", "-", "min_color", ".", "r", ")", "+", "min_color", ".", "r", ")", "green", "=", "round", "(", "factor", "*", "(", "max_color", ".", "g", "-", "min_color", ".", "g", ")", "+", "min_color", ".", "g", ")", "blue", "=", "round", "(", "factor", "*", "(", "max_color", ".", "b", "-", "min_color", ".", "b", ")", "+", "min_color", ".", "b", ")", "return", "Color", "(", "red", ",", "green", ",", "blue", ")" ]
Blend between two colors based on input value.
[ "Blend", "between", "two", "colors", "based", "on", "input", "value", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/color.py#L464-L479
4,667
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.from_location
def from_location(cls, location, north_angle=0, daylight_saving_period=None): """Create a sun path from a LBlocation.""" location = Location.from_location(location) return cls(location.latitude, location.longitude, location.time_zone, north_angle, daylight_saving_period)
python
def from_location(cls, location, north_angle=0, daylight_saving_period=None): """Create a sun path from a LBlocation.""" location = Location.from_location(location) return cls(location.latitude, location.longitude, location.time_zone, north_angle, daylight_saving_period)
[ "def", "from_location", "(", "cls", ",", "location", ",", "north_angle", "=", "0", ",", "daylight_saving_period", "=", "None", ")", ":", "location", "=", "Location", ".", "from_location", "(", "location", ")", "return", "cls", "(", "location", ".", "latitude", ",", "location", ".", "longitude", ",", "location", ".", "time_zone", ",", "north_angle", ",", "daylight_saving_period", ")" ]
Create a sun path from a LBlocation.
[ "Create", "a", "sun", "path", "from", "a", "LBlocation", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L84-L88
4,668
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.latitude
def latitude(self, value): """Set latitude value.""" self._latitude = math.radians(float(value)) assert -self.PI / 2 <= self._latitude <= self.PI / 2, \ "latitude value should be between -90..90."
python
def latitude(self, value): """Set latitude value.""" self._latitude = math.radians(float(value)) assert -self.PI / 2 <= self._latitude <= self.PI / 2, \ "latitude value should be between -90..90."
[ "def", "latitude", "(", "self", ",", "value", ")", ":", "self", ".", "_latitude", "=", "math", ".", "radians", "(", "float", "(", "value", ")", ")", "assert", "-", "self", ".", "PI", "/", "2", "<=", "self", ".", "_latitude", "<=", "self", ".", "PI", "/", "2", ",", "\"latitude value should be between -90..90.\"" ]
Set latitude value.
[ "Set", "latitude", "value", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L96-L100
4,669
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.longitude
def longitude(self, value): """Set longitude value in degrees.""" self._longitude = math.radians(float(value)) # update time_zone if abs((value / 15.0) - self.time_zone) > 1: # if time_zone doesn't match the longitude update the time_zone self.time_zone = value / 15.0
python
def longitude(self, value): """Set longitude value in degrees.""" self._longitude = math.radians(float(value)) # update time_zone if abs((value / 15.0) - self.time_zone) > 1: # if time_zone doesn't match the longitude update the time_zone self.time_zone = value / 15.0
[ "def", "longitude", "(", "self", ",", "value", ")", ":", "self", ".", "_longitude", "=", "math", ".", "radians", "(", "float", "(", "value", ")", ")", "# update time_zone", "if", "abs", "(", "(", "value", "/", "15.0", ")", "-", "self", ".", "time_zone", ")", ">", "1", ":", "# if time_zone doesn't match the longitude update the time_zone", "self", ".", "time_zone", "=", "value", "/", "15.0" ]
Set longitude value in degrees.
[ "Set", "longitude", "value", "in", "degrees", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L108-L115
4,670
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.is_daylight_saving_hour
def is_daylight_saving_hour(self, datetime): """Check if a datetime is a daylight saving time.""" if not self.daylight_saving_period: return False return self.daylight_saving_period.isTimeIncluded(datetime.hoy)
python
def is_daylight_saving_hour(self, datetime): """Check if a datetime is a daylight saving time.""" if not self.daylight_saving_period: return False return self.daylight_saving_period.isTimeIncluded(datetime.hoy)
[ "def", "is_daylight_saving_hour", "(", "self", ",", "datetime", ")", ":", "if", "not", "self", ".", "daylight_saving_period", ":", "return", "False", "return", "self", ".", "daylight_saving_period", ".", "isTimeIncluded", "(", "datetime", ".", "hoy", ")" ]
Check if a datetime is a daylight saving time.
[ "Check", "if", "a", "datetime", "is", "a", "daylight", "saving", "time", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L127-L131
4,671
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.calculate_sun_from_date_time
def calculate_sun_from_date_time(self, datetime, is_solar_time=False): """Get Sun for an hour of the year. This code is originally written by Trygve Wastvedt \ ([email protected]) based on (NOAA) and modified by Chris Mackey and Mostapha Roudsari Args: datetime: Ladybug datetime is_solar_time: A boolean to indicate if the input hour is solar time. (Default: False) Returns: A sun object for this particular time """ # TODO(mostapha): This should be more generic and based on a method if datetime.year != 2016 and self.is_leap_year: datetime = DateTime(datetime.month, datetime.day, datetime.hour, datetime.minute, True) sol_dec, eq_of_time = self._calculate_solar_geometry(datetime) hour = datetime.float_hour is_daylight_saving = self.is_daylight_saving_hour(datetime.hoy) hour = hour + 1 if self.is_daylight_saving_hour(datetime.hoy) else hour # minutes sol_time = self._calculate_solar_time(hour, eq_of_time, is_solar_time) * 60 # degrees if sol_time / 4 < 0: hour_angle = sol_time / 4 + 180 else: hour_angle = sol_time / 4 - 180 # Degrees zenith = math.degrees(math.acos (math.sin(self._latitude) * math.sin(math.radians(sol_dec)) + math.cos(self._latitude) * math.cos(math.radians(sol_dec)) * math.cos(math.radians(hour_angle)))) altitude = 90 - zenith # Approx Atmospheric Refraction if altitude > 85: atmos_refraction = 0 else: if altitude > 5: atmos_refraction = 58.1 / math.tan(math.radians(altitude)) - 0.07 / (math.tan(math.radians(altitude)))**3 + 0.000086 / (math.tan(math.radians(altitude)))**5 else: if altitude > -0.575: atmos_refraction = 1735 + altitude * (-518.2 + altitude * (103.4 + altitude * (-12.79 + altitude * 0.711))) else: atmos_refraction = -20.772 / math.tan( math.radians(altitude)) atmos_refraction /= 3600 altitude += atmos_refraction # Degrees if hour_angle > 0: azimuth = (math.degrees( math.acos( ( (math.sin(self._latitude) * math.cos(math.radians(zenith))) - math.sin(math.radians(sol_dec))) / (math.cos(self._latitude) * math.sin(math.radians(zenith))) ) ) + 180) % 360 else: azimuth = (540 - math.degrees(math.acos(( (math.sin(self._latitude) * math.cos(math.radians(zenith))) - math.sin(math.radians(sol_dec))) / (math.cos(self._latitude) * math.sin(math.radians(zenith)))) )) % 360 altitude = math.radians(altitude) azimuth = math.radians(azimuth) # create the sun for this hour return Sun(datetime, altitude, azimuth, is_solar_time, is_daylight_saving, self.north_angle)
python
def calculate_sun_from_date_time(self, datetime, is_solar_time=False): """Get Sun for an hour of the year. This code is originally written by Trygve Wastvedt \ ([email protected]) based on (NOAA) and modified by Chris Mackey and Mostapha Roudsari Args: datetime: Ladybug datetime is_solar_time: A boolean to indicate if the input hour is solar time. (Default: False) Returns: A sun object for this particular time """ # TODO(mostapha): This should be more generic and based on a method if datetime.year != 2016 and self.is_leap_year: datetime = DateTime(datetime.month, datetime.day, datetime.hour, datetime.minute, True) sol_dec, eq_of_time = self._calculate_solar_geometry(datetime) hour = datetime.float_hour is_daylight_saving = self.is_daylight_saving_hour(datetime.hoy) hour = hour + 1 if self.is_daylight_saving_hour(datetime.hoy) else hour # minutes sol_time = self._calculate_solar_time(hour, eq_of_time, is_solar_time) * 60 # degrees if sol_time / 4 < 0: hour_angle = sol_time / 4 + 180 else: hour_angle = sol_time / 4 - 180 # Degrees zenith = math.degrees(math.acos (math.sin(self._latitude) * math.sin(math.radians(sol_dec)) + math.cos(self._latitude) * math.cos(math.radians(sol_dec)) * math.cos(math.radians(hour_angle)))) altitude = 90 - zenith # Approx Atmospheric Refraction if altitude > 85: atmos_refraction = 0 else: if altitude > 5: atmos_refraction = 58.1 / math.tan(math.radians(altitude)) - 0.07 / (math.tan(math.radians(altitude)))**3 + 0.000086 / (math.tan(math.radians(altitude)))**5 else: if altitude > -0.575: atmos_refraction = 1735 + altitude * (-518.2 + altitude * (103.4 + altitude * (-12.79 + altitude * 0.711))) else: atmos_refraction = -20.772 / math.tan( math.radians(altitude)) atmos_refraction /= 3600 altitude += atmos_refraction # Degrees if hour_angle > 0: azimuth = (math.degrees( math.acos( ( (math.sin(self._latitude) * math.cos(math.radians(zenith))) - math.sin(math.radians(sol_dec))) / (math.cos(self._latitude) * math.sin(math.radians(zenith))) ) ) + 180) % 360 else: azimuth = (540 - math.degrees(math.acos(( (math.sin(self._latitude) * math.cos(math.radians(zenith))) - math.sin(math.radians(sol_dec))) / (math.cos(self._latitude) * math.sin(math.radians(zenith)))) )) % 360 altitude = math.radians(altitude) azimuth = math.radians(azimuth) # create the sun for this hour return Sun(datetime, altitude, azimuth, is_solar_time, is_daylight_saving, self.north_angle)
[ "def", "calculate_sun_from_date_time", "(", "self", ",", "datetime", ",", "is_solar_time", "=", "False", ")", ":", "# TODO(mostapha): This should be more generic and based on a method", "if", "datetime", ".", "year", "!=", "2016", "and", "self", ".", "is_leap_year", ":", "datetime", "=", "DateTime", "(", "datetime", ".", "month", ",", "datetime", ".", "day", ",", "datetime", ".", "hour", ",", "datetime", ".", "minute", ",", "True", ")", "sol_dec", ",", "eq_of_time", "=", "self", ".", "_calculate_solar_geometry", "(", "datetime", ")", "hour", "=", "datetime", ".", "float_hour", "is_daylight_saving", "=", "self", ".", "is_daylight_saving_hour", "(", "datetime", ".", "hoy", ")", "hour", "=", "hour", "+", "1", "if", "self", ".", "is_daylight_saving_hour", "(", "datetime", ".", "hoy", ")", "else", "hour", "# minutes", "sol_time", "=", "self", ".", "_calculate_solar_time", "(", "hour", ",", "eq_of_time", ",", "is_solar_time", ")", "*", "60", "# degrees", "if", "sol_time", "/", "4", "<", "0", ":", "hour_angle", "=", "sol_time", "/", "4", "+", "180", "else", ":", "hour_angle", "=", "sol_time", "/", "4", "-", "180", "# Degrees", "zenith", "=", "math", ".", "degrees", "(", "math", ".", "acos", "(", "math", ".", "sin", "(", "self", ".", "_latitude", ")", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "sol_dec", ")", ")", "+", "math", ".", "cos", "(", "self", ".", "_latitude", ")", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "sol_dec", ")", ")", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "hour_angle", ")", ")", ")", ")", "altitude", "=", "90", "-", "zenith", "# Approx Atmospheric Refraction", "if", "altitude", ">", "85", ":", "atmos_refraction", "=", "0", "else", ":", "if", "altitude", ">", "5", ":", "atmos_refraction", "=", "58.1", "/", "math", ".", "tan", "(", "math", ".", "radians", "(", "altitude", ")", ")", "-", "0.07", "/", "(", "math", ".", "tan", "(", "math", ".", "radians", "(", "altitude", ")", ")", ")", "**", "3", "+", "0.000086", "/", "(", "math", ".", "tan", "(", "math", ".", "radians", "(", "altitude", ")", ")", ")", "**", "5", "else", ":", "if", "altitude", ">", "-", "0.575", ":", "atmos_refraction", "=", "1735", "+", "altitude", "*", "(", "-", "518.2", "+", "altitude", "*", "(", "103.4", "+", "altitude", "*", "(", "-", "12.79", "+", "altitude", "*", "0.711", ")", ")", ")", "else", ":", "atmos_refraction", "=", "-", "20.772", "/", "math", ".", "tan", "(", "math", ".", "radians", "(", "altitude", ")", ")", "atmos_refraction", "/=", "3600", "altitude", "+=", "atmos_refraction", "# Degrees", "if", "hour_angle", ">", "0", ":", "azimuth", "=", "(", "math", ".", "degrees", "(", "math", ".", "acos", "(", "(", "(", "math", ".", "sin", "(", "self", ".", "_latitude", ")", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "zenith", ")", ")", ")", "-", "math", ".", "sin", "(", "math", ".", "radians", "(", "sol_dec", ")", ")", ")", "/", "(", "math", ".", "cos", "(", "self", ".", "_latitude", ")", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "zenith", ")", ")", ")", ")", ")", "+", "180", ")", "%", "360", "else", ":", "azimuth", "=", "(", "540", "-", "math", ".", "degrees", "(", "math", ".", "acos", "(", "(", "(", "math", ".", "sin", "(", "self", ".", "_latitude", ")", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "zenith", ")", ")", ")", "-", "math", ".", "sin", "(", "math", ".", "radians", "(", "sol_dec", ")", ")", ")", "/", "(", "math", ".", "cos", "(", "self", ".", "_latitude", ")", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "zenith", ")", ")", ")", ")", ")", ")", "%", "360", "altitude", "=", "math", ".", "radians", "(", "altitude", ")", "azimuth", "=", "math", ".", "radians", "(", "azimuth", ")", "# create the sun for this hour", "return", "Sun", "(", "datetime", ",", "altitude", ",", "azimuth", ",", "is_solar_time", ",", "is_daylight_saving", ",", "self", ".", "north_angle", ")" ]
Get Sun for an hour of the year. This code is originally written by Trygve Wastvedt \ ([email protected]) based on (NOAA) and modified by Chris Mackey and Mostapha Roudsari Args: datetime: Ladybug datetime is_solar_time: A boolean to indicate if the input hour is solar time. (Default: False) Returns: A sun object for this particular time
[ "Get", "Sun", "for", "an", "hour", "of", "the", "year", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L164-L261
4,672
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.calculate_sunrise_sunset
def calculate_sunrise_sunset(self, month, day, depression=0.833, is_solar_time=False): """Calculate sunrise, noon and sunset. Return: A dictionary. Keys are ("sunrise", "noon", "sunset") """ datetime = DateTime(month, day, hour=12, leap_year=self.is_leap_year) return self.calculate_sunrise_sunset_from_datetime(datetime, depression, is_solar_time)
python
def calculate_sunrise_sunset(self, month, day, depression=0.833, is_solar_time=False): """Calculate sunrise, noon and sunset. Return: A dictionary. Keys are ("sunrise", "noon", "sunset") """ datetime = DateTime(month, day, hour=12, leap_year=self.is_leap_year) return self.calculate_sunrise_sunset_from_datetime(datetime, depression, is_solar_time)
[ "def", "calculate_sunrise_sunset", "(", "self", ",", "month", ",", "day", ",", "depression", "=", "0.833", ",", "is_solar_time", "=", "False", ")", ":", "datetime", "=", "DateTime", "(", "month", ",", "day", ",", "hour", "=", "12", ",", "leap_year", "=", "self", ".", "is_leap_year", ")", "return", "self", ".", "calculate_sunrise_sunset_from_datetime", "(", "datetime", ",", "depression", ",", "is_solar_time", ")" ]
Calculate sunrise, noon and sunset. Return: A dictionary. Keys are ("sunrise", "noon", "sunset")
[ "Calculate", "sunrise", "noon", "and", "sunset", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L263-L274
4,673
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.calculate_sunrise_sunset_from_datetime
def calculate_sunrise_sunset_from_datetime(self, datetime, depression=0.833, is_solar_time=False): """Calculate sunrise, sunset and noon for a day of year.""" # TODO(mostapha): This should be more generic and based on a method if datetime.year != 2016 and self.is_leap_year: datetime = DateTime(datetime.month, datetime.day, datetime.hour, datetime.minute, True) sol_dec, eq_of_time = self._calculate_solar_geometry(datetime) # calculate sunrise and sunset hour if is_solar_time: noon = .5 else: noon = (720 - 4 * math.degrees(self._longitude) - eq_of_time + self.time_zone * 60 ) / 1440.0 try: sunrise_hour_angle = self._calculate_sunrise_hour_angle( sol_dec, depression) except ValueError: # no sun rise and sunset at this hour noon = 24 * noon return { "sunrise": None, "noon": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(noon), leap_year=self.is_leap_year), "sunset": None } else: sunrise = noon - sunrise_hour_angle * 4 / 1440.0 sunset = noon + sunrise_hour_angle * 4 / 1440.0 noon = 24 * noon sunrise = 24 * sunrise sunset = 24 * sunset return { "sunrise": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(sunrise), leap_year=self.is_leap_year), "noon": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(noon), leap_year=self.is_leap_year), "sunset": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(sunset), leap_year=self.is_leap_year) }
python
def calculate_sunrise_sunset_from_datetime(self, datetime, depression=0.833, is_solar_time=False): """Calculate sunrise, sunset and noon for a day of year.""" # TODO(mostapha): This should be more generic and based on a method if datetime.year != 2016 and self.is_leap_year: datetime = DateTime(datetime.month, datetime.day, datetime.hour, datetime.minute, True) sol_dec, eq_of_time = self._calculate_solar_geometry(datetime) # calculate sunrise and sunset hour if is_solar_time: noon = .5 else: noon = (720 - 4 * math.degrees(self._longitude) - eq_of_time + self.time_zone * 60 ) / 1440.0 try: sunrise_hour_angle = self._calculate_sunrise_hour_angle( sol_dec, depression) except ValueError: # no sun rise and sunset at this hour noon = 24 * noon return { "sunrise": None, "noon": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(noon), leap_year=self.is_leap_year), "sunset": None } else: sunrise = noon - sunrise_hour_angle * 4 / 1440.0 sunset = noon + sunrise_hour_angle * 4 / 1440.0 noon = 24 * noon sunrise = 24 * sunrise sunset = 24 * sunset return { "sunrise": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(sunrise), leap_year=self.is_leap_year), "noon": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(noon), leap_year=self.is_leap_year), "sunset": DateTime(datetime.month, datetime.day, *self._calculate_hour_and_minute(sunset), leap_year=self.is_leap_year) }
[ "def", "calculate_sunrise_sunset_from_datetime", "(", "self", ",", "datetime", ",", "depression", "=", "0.833", ",", "is_solar_time", "=", "False", ")", ":", "# TODO(mostapha): This should be more generic and based on a method", "if", "datetime", ".", "year", "!=", "2016", "and", "self", ".", "is_leap_year", ":", "datetime", "=", "DateTime", "(", "datetime", ".", "month", ",", "datetime", ".", "day", ",", "datetime", ".", "hour", ",", "datetime", ".", "minute", ",", "True", ")", "sol_dec", ",", "eq_of_time", "=", "self", ".", "_calculate_solar_geometry", "(", "datetime", ")", "# calculate sunrise and sunset hour", "if", "is_solar_time", ":", "noon", "=", ".5", "else", ":", "noon", "=", "(", "720", "-", "4", "*", "math", ".", "degrees", "(", "self", ".", "_longitude", ")", "-", "eq_of_time", "+", "self", ".", "time_zone", "*", "60", ")", "/", "1440.0", "try", ":", "sunrise_hour_angle", "=", "self", ".", "_calculate_sunrise_hour_angle", "(", "sol_dec", ",", "depression", ")", "except", "ValueError", ":", "# no sun rise and sunset at this hour", "noon", "=", "24", "*", "noon", "return", "{", "\"sunrise\"", ":", "None", ",", "\"noon\"", ":", "DateTime", "(", "datetime", ".", "month", ",", "datetime", ".", "day", ",", "*", "self", ".", "_calculate_hour_and_minute", "(", "noon", ")", ",", "leap_year", "=", "self", ".", "is_leap_year", ")", ",", "\"sunset\"", ":", "None", "}", "else", ":", "sunrise", "=", "noon", "-", "sunrise_hour_angle", "*", "4", "/", "1440.0", "sunset", "=", "noon", "+", "sunrise_hour_angle", "*", "4", "/", "1440.0", "noon", "=", "24", "*", "noon", "sunrise", "=", "24", "*", "sunrise", "sunset", "=", "24", "*", "sunset", "return", "{", "\"sunrise\"", ":", "DateTime", "(", "datetime", ".", "month", ",", "datetime", ".", "day", ",", "*", "self", ".", "_calculate_hour_and_minute", "(", "sunrise", ")", ",", "leap_year", "=", "self", ".", "is_leap_year", ")", ",", "\"noon\"", ":", "DateTime", "(", "datetime", ".", "month", ",", "datetime", ".", "day", ",", "*", "self", ".", "_calculate_hour_and_minute", "(", "noon", ")", ",", "leap_year", "=", "self", ".", "is_leap_year", ")", ",", "\"sunset\"", ":", "DateTime", "(", "datetime", ".", "month", ",", "datetime", ".", "day", ",", "*", "self", ".", "_calculate_hour_and_minute", "(", "sunset", ")", ",", "leap_year", "=", "self", ".", "is_leap_year", ")", "}" ]
Calculate sunrise, sunset and noon for a day of year.
[ "Calculate", "sunrise", "sunset", "and", "noon", "for", "a", "day", "of", "year", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L277-L325
4,674
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath._calculate_sunrise_hour_angle
def _calculate_sunrise_hour_angle(self, solar_dec, depression=0.833): """Calculate hour angle for sunrise time in degrees.""" hour_angle_arg = math.degrees(math.acos( math.cos(math.radians(90 + depression)) / (math.cos(math.radians(self.latitude)) * math.cos( math.radians(solar_dec))) - math.tan(math.radians(self.latitude)) * math.tan(math.radians(solar_dec)) )) return hour_angle_arg
python
def _calculate_sunrise_hour_angle(self, solar_dec, depression=0.833): """Calculate hour angle for sunrise time in degrees.""" hour_angle_arg = math.degrees(math.acos( math.cos(math.radians(90 + depression)) / (math.cos(math.radians(self.latitude)) * math.cos( math.radians(solar_dec))) - math.tan(math.radians(self.latitude)) * math.tan(math.radians(solar_dec)) )) return hour_angle_arg
[ "def", "_calculate_sunrise_hour_angle", "(", "self", ",", "solar_dec", ",", "depression", "=", "0.833", ")", ":", "hour_angle_arg", "=", "math", ".", "degrees", "(", "math", ".", "acos", "(", "math", ".", "cos", "(", "math", ".", "radians", "(", "90", "+", "depression", ")", ")", "/", "(", "math", ".", "cos", "(", "math", ".", "radians", "(", "self", ".", "latitude", ")", ")", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "solar_dec", ")", ")", ")", "-", "math", ".", "tan", "(", "math", ".", "radians", "(", "self", ".", "latitude", ")", ")", "*", "math", ".", "tan", "(", "math", ".", "radians", "(", "solar_dec", ")", ")", ")", ")", "return", "hour_angle_arg" ]
Calculate hour angle for sunrise time in degrees.
[ "Calculate", "hour", "angle", "for", "sunrise", "time", "in", "degrees", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L468-L479
4,675
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath._calculate_solar_time
def _calculate_solar_time(self, hour, eq_of_time, is_solar_time): """Calculate Solar time for an hour.""" if is_solar_time: return hour return ( (hour * 60 + eq_of_time + 4 * math.degrees(self._longitude) - 60 * self.time_zone) % 1440) / 60
python
def _calculate_solar_time(self, hour, eq_of_time, is_solar_time): """Calculate Solar time for an hour.""" if is_solar_time: return hour return ( (hour * 60 + eq_of_time + 4 * math.degrees(self._longitude) - 60 * self.time_zone) % 1440) / 60
[ "def", "_calculate_solar_time", "(", "self", ",", "hour", ",", "eq_of_time", ",", "is_solar_time", ")", ":", "if", "is_solar_time", ":", "return", "hour", "return", "(", "(", "hour", "*", "60", "+", "eq_of_time", "+", "4", "*", "math", ".", "degrees", "(", "self", ".", "_longitude", ")", "-", "60", "*", "self", ".", "time_zone", ")", "%", "1440", ")", "/", "60" ]
Calculate Solar time for an hour.
[ "Calculate", "Solar", "time", "for", "an", "hour", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L481-L488
4,676
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath._calculate_solar_time_by_doy
def _calculate_solar_time_by_doy(self, hour, doy): """This is how radiance calculates solar time. This is a place holder and \ need to be validated against calculateSolarTime. """ raise NotImplementedError() return (0.170 * math.sin((4 * math.pi / 373) * (doy - 80)) - 0.129 * math.sin((2 * math.pi / 355) * (doy - 8)) + 12 * (-(15 * self.time_zone) - self.longitude) / math.pi)
python
def _calculate_solar_time_by_doy(self, hour, doy): """This is how radiance calculates solar time. This is a place holder and \ need to be validated against calculateSolarTime. """ raise NotImplementedError() return (0.170 * math.sin((4 * math.pi / 373) * (doy - 80)) - 0.129 * math.sin((2 * math.pi / 355) * (doy - 8)) + 12 * (-(15 * self.time_zone) - self.longitude) / math.pi)
[ "def", "_calculate_solar_time_by_doy", "(", "self", ",", "hour", ",", "doy", ")", ":", "raise", "NotImplementedError", "(", ")", "return", "(", "0.170", "*", "math", ".", "sin", "(", "(", "4", "*", "math", ".", "pi", "/", "373", ")", "*", "(", "doy", "-", "80", ")", ")", "-", "0.129", "*", "math", ".", "sin", "(", "(", "2", "*", "math", ".", "pi", "/", "355", ")", "*", "(", "doy", "-", "8", ")", ")", "+", "12", "*", "(", "-", "(", "15", "*", "self", ".", "time_zone", ")", "-", "self", ".", "longitude", ")", "/", "math", ".", "pi", ")" ]
This is how radiance calculates solar time. This is a place holder and \ need to be validated against calculateSolarTime.
[ "This", "is", "how", "radiance", "calculates", "solar", "time", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L490-L499
4,677
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath.draw_sunpath
def draw_sunpath(self, hoys=None, origin=None, scale=1, sun_scale=1, annual=True, rem_night=True): """Create sunpath geometry. \ This method should only be used from the + libraries. Args: hoys: An optional list of hours of the year(default: None). origin: Sunpath origin(default: (0, 0, 0)). scale: Sunpath scale(default: 1). sun_scale: Scale for the sun spheres(default: 1). annual: Set to True to draw an annual sunpath. Otherwise a daily sunpath is drawn. rem_night: Remove suns which are under the horizon(night!). Returns: base_curves: A collection of curves for base plot. analemma_curves: A collection of analemma_curves. daily_curves: A collection of daily_curves. suns: A list of suns. """ # check and make sure the call is coming from inside a plus library assert ladybug.isplus, \ '"draw_sunpath" method can only be used in the [+] libraries.' hoys = hoys or () origin = origin or (0, 0, 0) try: origin = tuple(origin) except TypeError as e: # dynamo try: origin = origin.X, origin.Y, origin.Z except AttributeError: raise TypeError(str(e)) scale = scale or 1 sun_scale = sun_scale or 1 assert annual or hoys, 'For daily sunpath you need to provide at least one hour.' radius = 200 * scale # draw base circles and lines base_curves = plus.base_curves(origin, radius, self.north_angle) # draw analemma # calculate date times for analemma curves if annual: asuns = self._analemma_suns() analemma_curves = plus.analemma_curves(asuns, origin, radius) else: analemma_curves = () # add sun spheres if hoys: suns = tuple(self.calculate_sun_from_hoy(hour) for hour in hoys) else: suns = () if rem_night: suns = tuple(sun for sun in suns if sun.is_during_day) sun_geos = plus.sun_geometry(suns, origin, radius) # draw daily sunpath if annual: dts = (DateTime(m, 21) for m in xrange(1, 13)) else: dts = (sun.datetime for sun in suns) dsuns = self._daily_suns(dts) daily_curves = plus.daily_curves(dsuns, origin, radius) SPGeo = namedtuple( 'SunpathGeo', ('compass_curves', 'analemma_curves', 'daily_curves', 'suns', 'sun_geos')) # return outputs return SPGeo(base_curves, analemma_curves, daily_curves, suns, sun_geos)
python
def draw_sunpath(self, hoys=None, origin=None, scale=1, sun_scale=1, annual=True, rem_night=True): """Create sunpath geometry. \ This method should only be used from the + libraries. Args: hoys: An optional list of hours of the year(default: None). origin: Sunpath origin(default: (0, 0, 0)). scale: Sunpath scale(default: 1). sun_scale: Scale for the sun spheres(default: 1). annual: Set to True to draw an annual sunpath. Otherwise a daily sunpath is drawn. rem_night: Remove suns which are under the horizon(night!). Returns: base_curves: A collection of curves for base plot. analemma_curves: A collection of analemma_curves. daily_curves: A collection of daily_curves. suns: A list of suns. """ # check and make sure the call is coming from inside a plus library assert ladybug.isplus, \ '"draw_sunpath" method can only be used in the [+] libraries.' hoys = hoys or () origin = origin or (0, 0, 0) try: origin = tuple(origin) except TypeError as e: # dynamo try: origin = origin.X, origin.Y, origin.Z except AttributeError: raise TypeError(str(e)) scale = scale or 1 sun_scale = sun_scale or 1 assert annual or hoys, 'For daily sunpath you need to provide at least one hour.' radius = 200 * scale # draw base circles and lines base_curves = plus.base_curves(origin, radius, self.north_angle) # draw analemma # calculate date times for analemma curves if annual: asuns = self._analemma_suns() analemma_curves = plus.analemma_curves(asuns, origin, radius) else: analemma_curves = () # add sun spheres if hoys: suns = tuple(self.calculate_sun_from_hoy(hour) for hour in hoys) else: suns = () if rem_night: suns = tuple(sun for sun in suns if sun.is_during_day) sun_geos = plus.sun_geometry(suns, origin, radius) # draw daily sunpath if annual: dts = (DateTime(m, 21) for m in xrange(1, 13)) else: dts = (sun.datetime for sun in suns) dsuns = self._daily_suns(dts) daily_curves = plus.daily_curves(dsuns, origin, radius) SPGeo = namedtuple( 'SunpathGeo', ('compass_curves', 'analemma_curves', 'daily_curves', 'suns', 'sun_geos')) # return outputs return SPGeo(base_curves, analemma_curves, daily_curves, suns, sun_geos)
[ "def", "draw_sunpath", "(", "self", ",", "hoys", "=", "None", ",", "origin", "=", "None", ",", "scale", "=", "1", ",", "sun_scale", "=", "1", ",", "annual", "=", "True", ",", "rem_night", "=", "True", ")", ":", "# check and make sure the call is coming from inside a plus library", "assert", "ladybug", ".", "isplus", ",", "'\"draw_sunpath\" method can only be used in the [+] libraries.'", "hoys", "=", "hoys", "or", "(", ")", "origin", "=", "origin", "or", "(", "0", ",", "0", ",", "0", ")", "try", ":", "origin", "=", "tuple", "(", "origin", ")", "except", "TypeError", "as", "e", ":", "# dynamo", "try", ":", "origin", "=", "origin", ".", "X", ",", "origin", ".", "Y", ",", "origin", ".", "Z", "except", "AttributeError", ":", "raise", "TypeError", "(", "str", "(", "e", ")", ")", "scale", "=", "scale", "or", "1", "sun_scale", "=", "sun_scale", "or", "1", "assert", "annual", "or", "hoys", ",", "'For daily sunpath you need to provide at least one hour.'", "radius", "=", "200", "*", "scale", "# draw base circles and lines", "base_curves", "=", "plus", ".", "base_curves", "(", "origin", ",", "radius", ",", "self", ".", "north_angle", ")", "# draw analemma", "# calculate date times for analemma curves", "if", "annual", ":", "asuns", "=", "self", ".", "_analemma_suns", "(", ")", "analemma_curves", "=", "plus", ".", "analemma_curves", "(", "asuns", ",", "origin", ",", "radius", ")", "else", ":", "analemma_curves", "=", "(", ")", "# add sun spheres", "if", "hoys", ":", "suns", "=", "tuple", "(", "self", ".", "calculate_sun_from_hoy", "(", "hour", ")", "for", "hour", "in", "hoys", ")", "else", ":", "suns", "=", "(", ")", "if", "rem_night", ":", "suns", "=", "tuple", "(", "sun", "for", "sun", "in", "suns", "if", "sun", ".", "is_during_day", ")", "sun_geos", "=", "plus", ".", "sun_geometry", "(", "suns", ",", "origin", ",", "radius", ")", "# draw daily sunpath", "if", "annual", ":", "dts", "=", "(", "DateTime", "(", "m", ",", "21", ")", "for", "m", "in", "xrange", "(", "1", ",", "13", ")", ")", "else", ":", "dts", "=", "(", "sun", ".", "datetime", "for", "sun", "in", "suns", ")", "dsuns", "=", "self", ".", "_daily_suns", "(", "dts", ")", "daily_curves", "=", "plus", ".", "daily_curves", "(", "dsuns", ",", "origin", ",", "radius", ")", "SPGeo", "=", "namedtuple", "(", "'SunpathGeo'", ",", "(", "'compass_curves'", ",", "'analemma_curves'", ",", "'daily_curves'", ",", "'suns'", ",", "'sun_geos'", ")", ")", "# return outputs", "return", "SPGeo", "(", "base_curves", ",", "analemma_curves", ",", "daily_curves", ",", "suns", ",", "sun_geos", ")" ]
Create sunpath geometry. \ This method should only be used from the + libraries. Args: hoys: An optional list of hours of the year(default: None). origin: Sunpath origin(default: (0, 0, 0)). scale: Sunpath scale(default: 1). sun_scale: Scale for the sun spheres(default: 1). annual: Set to True to draw an annual sunpath. Otherwise a daily sunpath is drawn. rem_night: Remove suns which are under the horizon(night!). Returns: base_curves: A collection of curves for base plot. analemma_curves: A collection of analemma_curves. daily_curves: A collection of daily_curves. suns: A list of suns.
[ "Create", "sunpath", "geometry", ".", "\\", "This", "method", "should", "only", "be", "used", "from", "the", "+", "libraries", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L512-L592
4,678
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath._analemma_position
def _analemma_position(self, hour): """Check what the analemma position is for an hour. This is useful for calculating hours of analemma curves. Returns: -1 if always night, 0 if both day and night, 1 if always day. """ # check for 21 dec and 21 jun low = self.calculate_sun(12, 21, hour).is_during_day high = self.calculate_sun(6, 21, hour).is_during_day if low and high: return 1 elif low or high: return 0 else: return -1
python
def _analemma_position(self, hour): """Check what the analemma position is for an hour. This is useful for calculating hours of analemma curves. Returns: -1 if always night, 0 if both day and night, 1 if always day. """ # check for 21 dec and 21 jun low = self.calculate_sun(12, 21, hour).is_during_day high = self.calculate_sun(6, 21, hour).is_during_day if low and high: return 1 elif low or high: return 0 else: return -1
[ "def", "_analemma_position", "(", "self", ",", "hour", ")", ":", "# check for 21 dec and 21 jun", "low", "=", "self", ".", "calculate_sun", "(", "12", ",", "21", ",", "hour", ")", ".", "is_during_day", "high", "=", "self", ".", "calculate_sun", "(", "6", ",", "21", ",", "hour", ")", ".", "is_during_day", "if", "low", "and", "high", ":", "return", "1", "elif", "low", "or", "high", ":", "return", "0", "else", ":", "return", "-", "1" ]
Check what the analemma position is for an hour. This is useful for calculating hours of analemma curves. Returns: -1 if always night, 0 if both day and night, 1 if always day.
[ "Check", "what", "the", "analemma", "position", "is", "for", "an", "hour", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L594-L613
4,679
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath._analemma_suns
def _analemma_suns(self): """Calculate times that should be used for drawing analemma_curves. Returns: A list of list of analemma suns. """ for h in xrange(0, 24): if self._analemma_position(h) < 0: continue elif self._analemma_position(h) == 0: chours = [] # this is an hour that not all the hours are day or night prevhour = self.latitude <= 0 num_of_days = 8760 if not self.is_leap_year else 8760 + 24 for hoy in xrange(h, num_of_days, 24): thishour = self.calculate_sun_from_hoy(hoy).is_during_day if thishour != prevhour: if not thishour: hoy -= 24 dt = DateTime.from_hoy(hoy, self.is_leap_year) chours.append((dt.month, dt.day, dt.hour)) prevhour = thishour tt = [] for hcount in range(int(len(chours) / 2)): st = chours[2 * hcount] en = chours[2 * hcount + 1] if self.latitude >= 0: tt = [self.calculate_sun(*st)] + \ [self.calculate_sun(st[0], d, h) for d in xrange(st[1] + 1, 29, 7)] + \ [self.calculate_sun(m, d, h) for m in xrange(st[0] + 1, en[0]) for d in xrange(3, 29, 7)] + \ [self.calculate_sun(en[0], d, h) for d in xrange(3, en[1], 7)] + \ [self.calculate_sun(*en)] else: tt = [self.calculate_sun(*en)] + \ [self.calculate_sun(en[0], d, h) for d in xrange(en[1] + 1, 29, 7)] + \ [self.calculate_sun(m, d, h) for m in xrange(en[0] + 1, 13) for d in xrange(3, 29, 7)] + \ [self.calculate_sun(m, d, h) for m in xrange(1, st[0]) for d in xrange(3, 29, 7)] + \ [self.calculate_sun(st[0], d, h) for d in xrange(3, st[1], 7)] + \ [self.calculate_sun(*st)] yield tt else: yield tuple(self.calculate_sun((m % 12) + 1, d, h) for m in xrange(0, 13) for d in (7, 14, 21))[:-2]
python
def _analemma_suns(self): """Calculate times that should be used for drawing analemma_curves. Returns: A list of list of analemma suns. """ for h in xrange(0, 24): if self._analemma_position(h) < 0: continue elif self._analemma_position(h) == 0: chours = [] # this is an hour that not all the hours are day or night prevhour = self.latitude <= 0 num_of_days = 8760 if not self.is_leap_year else 8760 + 24 for hoy in xrange(h, num_of_days, 24): thishour = self.calculate_sun_from_hoy(hoy).is_during_day if thishour != prevhour: if not thishour: hoy -= 24 dt = DateTime.from_hoy(hoy, self.is_leap_year) chours.append((dt.month, dt.day, dt.hour)) prevhour = thishour tt = [] for hcount in range(int(len(chours) / 2)): st = chours[2 * hcount] en = chours[2 * hcount + 1] if self.latitude >= 0: tt = [self.calculate_sun(*st)] + \ [self.calculate_sun(st[0], d, h) for d in xrange(st[1] + 1, 29, 7)] + \ [self.calculate_sun(m, d, h) for m in xrange(st[0] + 1, en[0]) for d in xrange(3, 29, 7)] + \ [self.calculate_sun(en[0], d, h) for d in xrange(3, en[1], 7)] + \ [self.calculate_sun(*en)] else: tt = [self.calculate_sun(*en)] + \ [self.calculate_sun(en[0], d, h) for d in xrange(en[1] + 1, 29, 7)] + \ [self.calculate_sun(m, d, h) for m in xrange(en[0] + 1, 13) for d in xrange(3, 29, 7)] + \ [self.calculate_sun(m, d, h) for m in xrange(1, st[0]) for d in xrange(3, 29, 7)] + \ [self.calculate_sun(st[0], d, h) for d in xrange(3, st[1], 7)] + \ [self.calculate_sun(*st)] yield tt else: yield tuple(self.calculate_sun((m % 12) + 1, d, h) for m in xrange(0, 13) for d in (7, 14, 21))[:-2]
[ "def", "_analemma_suns", "(", "self", ")", ":", "for", "h", "in", "xrange", "(", "0", ",", "24", ")", ":", "if", "self", ".", "_analemma_position", "(", "h", ")", "<", "0", ":", "continue", "elif", "self", ".", "_analemma_position", "(", "h", ")", "==", "0", ":", "chours", "=", "[", "]", "# this is an hour that not all the hours are day or night", "prevhour", "=", "self", ".", "latitude", "<=", "0", "num_of_days", "=", "8760", "if", "not", "self", ".", "is_leap_year", "else", "8760", "+", "24", "for", "hoy", "in", "xrange", "(", "h", ",", "num_of_days", ",", "24", ")", ":", "thishour", "=", "self", ".", "calculate_sun_from_hoy", "(", "hoy", ")", ".", "is_during_day", "if", "thishour", "!=", "prevhour", ":", "if", "not", "thishour", ":", "hoy", "-=", "24", "dt", "=", "DateTime", ".", "from_hoy", "(", "hoy", ",", "self", ".", "is_leap_year", ")", "chours", ".", "append", "(", "(", "dt", ".", "month", ",", "dt", ".", "day", ",", "dt", ".", "hour", ")", ")", "prevhour", "=", "thishour", "tt", "=", "[", "]", "for", "hcount", "in", "range", "(", "int", "(", "len", "(", "chours", ")", "/", "2", ")", ")", ":", "st", "=", "chours", "[", "2", "*", "hcount", "]", "en", "=", "chours", "[", "2", "*", "hcount", "+", "1", "]", "if", "self", ".", "latitude", ">=", "0", ":", "tt", "=", "[", "self", ".", "calculate_sun", "(", "*", "st", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "st", "[", "0", "]", ",", "d", ",", "h", ")", "for", "d", "in", "xrange", "(", "st", "[", "1", "]", "+", "1", ",", "29", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "m", ",", "d", ",", "h", ")", "for", "m", "in", "xrange", "(", "st", "[", "0", "]", "+", "1", ",", "en", "[", "0", "]", ")", "for", "d", "in", "xrange", "(", "3", ",", "29", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "en", "[", "0", "]", ",", "d", ",", "h", ")", "for", "d", "in", "xrange", "(", "3", ",", "en", "[", "1", "]", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "*", "en", ")", "]", "else", ":", "tt", "=", "[", "self", ".", "calculate_sun", "(", "*", "en", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "en", "[", "0", "]", ",", "d", ",", "h", ")", "for", "d", "in", "xrange", "(", "en", "[", "1", "]", "+", "1", ",", "29", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "m", ",", "d", ",", "h", ")", "for", "m", "in", "xrange", "(", "en", "[", "0", "]", "+", "1", ",", "13", ")", "for", "d", "in", "xrange", "(", "3", ",", "29", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "m", ",", "d", ",", "h", ")", "for", "m", "in", "xrange", "(", "1", ",", "st", "[", "0", "]", ")", "for", "d", "in", "xrange", "(", "3", ",", "29", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "st", "[", "0", "]", ",", "d", ",", "h", ")", "for", "d", "in", "xrange", "(", "3", ",", "st", "[", "1", "]", ",", "7", ")", "]", "+", "[", "self", ".", "calculate_sun", "(", "*", "st", ")", "]", "yield", "tt", "else", ":", "yield", "tuple", "(", "self", ".", "calculate_sun", "(", "(", "m", "%", "12", ")", "+", "1", ",", "d", ",", "h", ")", "for", "m", "in", "xrange", "(", "0", ",", "13", ")", "for", "d", "in", "(", "7", ",", "14", ",", "21", ")", ")", "[", ":", "-", "2", "]" ]
Calculate times that should be used for drawing analemma_curves. Returns: A list of list of analemma suns.
[ "Calculate", "times", "that", "should", "be", "used", "for", "drawing", "analemma_curves", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L615-L666
4,680
ladybug-tools/ladybug
ladybug/sunpath.py
Sunpath._daily_suns
def _daily_suns(self, datetimes): """Get sun curve for multiple days of the year.""" for dt in datetimes: # calculate sunrise sunset and noon nss = self.calculate_sunrise_sunset(dt.month, dt.day) dts = tuple(nss[k] for k in ('sunrise', 'noon', 'sunset')) if dts[0] is None: # circle yield (self.calculate_sun(dt.month, dt.day, h) for h in (0, 12, 15)), \ False else: # Arc yield (self.calculate_sun_from_date_time(dt) for dt in dts), True
python
def _daily_suns(self, datetimes): """Get sun curve for multiple days of the year.""" for dt in datetimes: # calculate sunrise sunset and noon nss = self.calculate_sunrise_sunset(dt.month, dt.day) dts = tuple(nss[k] for k in ('sunrise', 'noon', 'sunset')) if dts[0] is None: # circle yield (self.calculate_sun(dt.month, dt.day, h) for h in (0, 12, 15)), \ False else: # Arc yield (self.calculate_sun_from_date_time(dt) for dt in dts), True
[ "def", "_daily_suns", "(", "self", ",", "datetimes", ")", ":", "for", "dt", "in", "datetimes", ":", "# calculate sunrise sunset and noon", "nss", "=", "self", ".", "calculate_sunrise_sunset", "(", "dt", ".", "month", ",", "dt", ".", "day", ")", "dts", "=", "tuple", "(", "nss", "[", "k", "]", "for", "k", "in", "(", "'sunrise'", ",", "'noon'", ",", "'sunset'", ")", ")", "if", "dts", "[", "0", "]", "is", "None", ":", "# circle", "yield", "(", "self", ".", "calculate_sun", "(", "dt", ".", "month", ",", "dt", ".", "day", ",", "h", ")", "for", "h", "in", "(", "0", ",", "12", ",", "15", ")", ")", ",", "False", "else", ":", "# Arc", "yield", "(", "self", ".", "calculate_sun_from_date_time", "(", "dt", ")", "for", "dt", "in", "dts", ")", ",", "True" ]
Get sun curve for multiple days of the year.
[ "Get", "sun", "curve", "for", "multiple", "days", "of", "the", "year", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L668-L681
4,681
ladybug-tools/ladybug
ladybug/sunpath.py
Sun._calculate_sun_vector
def _calculate_sun_vector(self): """Calculate sun vector for this sun.""" z_axis = Vector3(0., 0., -1.) x_axis = Vector3(1., 0., 0.) north_vector = Vector3(0., 1., 0.) # rotate north vector based on azimuth, altitude, and north _sun_vector = north_vector \ .rotate_around(x_axis, self.altitude_in_radians) \ .rotate_around(z_axis, self.azimuth_in_radians) \ .rotate_around(z_axis, math.radians(-1 * self.north_angle)) _sun_vector.normalize() try: _sun_vector.flip() except AttributeError: # euclid3 _sun_vector = Vector3(-1 * _sun_vector.x, -1 * _sun_vector.y, -1 * _sun_vector.z) self._sun_vector = _sun_vector
python
def _calculate_sun_vector(self): """Calculate sun vector for this sun.""" z_axis = Vector3(0., 0., -1.) x_axis = Vector3(1., 0., 0.) north_vector = Vector3(0., 1., 0.) # rotate north vector based on azimuth, altitude, and north _sun_vector = north_vector \ .rotate_around(x_axis, self.altitude_in_radians) \ .rotate_around(z_axis, self.azimuth_in_radians) \ .rotate_around(z_axis, math.radians(-1 * self.north_angle)) _sun_vector.normalize() try: _sun_vector.flip() except AttributeError: # euclid3 _sun_vector = Vector3(-1 * _sun_vector.x, -1 * _sun_vector.y, -1 * _sun_vector.z) self._sun_vector = _sun_vector
[ "def", "_calculate_sun_vector", "(", "self", ")", ":", "z_axis", "=", "Vector3", "(", "0.", ",", "0.", ",", "-", "1.", ")", "x_axis", "=", "Vector3", "(", "1.", ",", "0.", ",", "0.", ")", "north_vector", "=", "Vector3", "(", "0.", ",", "1.", ",", "0.", ")", "# rotate north vector based on azimuth, altitude, and north", "_sun_vector", "=", "north_vector", ".", "rotate_around", "(", "x_axis", ",", "self", ".", "altitude_in_radians", ")", ".", "rotate_around", "(", "z_axis", ",", "self", ".", "azimuth_in_radians", ")", ".", "rotate_around", "(", "z_axis", ",", "math", ".", "radians", "(", "-", "1", "*", "self", ".", "north_angle", ")", ")", "_sun_vector", ".", "normalize", "(", ")", "try", ":", "_sun_vector", ".", "flip", "(", ")", "except", "AttributeError", ":", "# euclid3", "_sun_vector", "=", "Vector3", "(", "-", "1", "*", "_sun_vector", ".", "x", ",", "-", "1", "*", "_sun_vector", ".", "y", ",", "-", "1", "*", "_sun_vector", ".", "z", ")", "self", ".", "_sun_vector", "=", "_sun_vector" ]
Calculate sun vector for this sun.
[ "Calculate", "sun", "vector", "for", "this", "sun", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L798-L819
4,682
ladybug-tools/ladybug
ladybug/designday.py
DDY.from_json
def from_json(cls, data): """Create a DDY from a dictionary. Args: data = { "location": ladybug Location schema, "design_days": [] // list of ladybug DesignDay schemas} """ required_keys = ('location', 'design_days') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) return cls(Location.from_json(data['location']), [DesignDay.from_json(des_day) for des_day in data['design_days']])
python
def from_json(cls, data): """Create a DDY from a dictionary. Args: data = { "location": ladybug Location schema, "design_days": [] // list of ladybug DesignDay schemas} """ required_keys = ('location', 'design_days') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) return cls(Location.from_json(data['location']), [DesignDay.from_json(des_day) for des_day in data['design_days']])
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "required_keys", "=", "(", "'location'", ",", "'design_days'", ")", "for", "key", "in", "required_keys", ":", "assert", "key", "in", "data", ",", "'Required key \"{}\" is missing!'", ".", "format", "(", "key", ")", "return", "cls", "(", "Location", ".", "from_json", "(", "data", "[", "'location'", "]", ")", ",", "[", "DesignDay", ".", "from_json", "(", "des_day", ")", "for", "des_day", "in", "data", "[", "'design_days'", "]", "]", ")" ]
Create a DDY from a dictionary. Args: data = { "location": ladybug Location schema, "design_days": [] // list of ladybug DesignDay schemas}
[ "Create", "a", "DDY", "from", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L48-L61
4,683
ladybug-tools/ladybug
ladybug/designday.py
DDY.from_ddy_file
def from_ddy_file(cls, file_path): """Initalize from a ddy file object from an existing ddy file. args: file_path: A string representing a complete path to the .ddy file. """ # check that the file is there if not os.path.isfile(file_path): raise ValueError( 'Cannot find a .ddy file at {}'.format(file_path)) if not file_path.lower().endswith('.ddy'): raise ValueError( 'DDY file does not have a .ddy extension.') # check the python version and open the file try: iron_python = True if platform.python_implementation() == 'IronPython' \ else False except Exception: iron_python = True if iron_python: ddywin = codecs.open(file_path, 'r') else: ddywin = codecs.open(file_path, 'r', encoding='utf-8', errors='ignore') try: ddytxt = ddywin.read() location_format = re.compile( r"(Site:Location,(.|\n)*?((;\s*!)|(;\s*\n)|(;\n)))") design_day_format = re.compile( r"(SizingPeriod:DesignDay,(.|\n)*?((;\s*!)|(;\s*\n)|(;\n)))") location_matches = location_format.findall(ddytxt) des_day_matches = design_day_format.findall(ddytxt) except Exception as e: import traceback raise Exception('{}\n{}'.format(e, traceback.format_exc())) else: # check to be sure location was found assert len(location_matches) > 0, 'No location objects found ' \ 'in .ddy file.' # build design day and location objects location = Location.from_location(location_matches[0][0]) design_days = [DesignDay.from_ep_string( match[0], location) for match in des_day_matches] finally: ddywin.close() cls_ = cls(location, design_days) cls_._file_path = os.path.normpath(file_path) return cls_
python
def from_ddy_file(cls, file_path): """Initalize from a ddy file object from an existing ddy file. args: file_path: A string representing a complete path to the .ddy file. """ # check that the file is there if not os.path.isfile(file_path): raise ValueError( 'Cannot find a .ddy file at {}'.format(file_path)) if not file_path.lower().endswith('.ddy'): raise ValueError( 'DDY file does not have a .ddy extension.') # check the python version and open the file try: iron_python = True if platform.python_implementation() == 'IronPython' \ else False except Exception: iron_python = True if iron_python: ddywin = codecs.open(file_path, 'r') else: ddywin = codecs.open(file_path, 'r', encoding='utf-8', errors='ignore') try: ddytxt = ddywin.read() location_format = re.compile( r"(Site:Location,(.|\n)*?((;\s*!)|(;\s*\n)|(;\n)))") design_day_format = re.compile( r"(SizingPeriod:DesignDay,(.|\n)*?((;\s*!)|(;\s*\n)|(;\n)))") location_matches = location_format.findall(ddytxt) des_day_matches = design_day_format.findall(ddytxt) except Exception as e: import traceback raise Exception('{}\n{}'.format(e, traceback.format_exc())) else: # check to be sure location was found assert len(location_matches) > 0, 'No location objects found ' \ 'in .ddy file.' # build design day and location objects location = Location.from_location(location_matches[0][0]) design_days = [DesignDay.from_ep_string( match[0], location) for match in des_day_matches] finally: ddywin.close() cls_ = cls(location, design_days) cls_._file_path = os.path.normpath(file_path) return cls_
[ "def", "from_ddy_file", "(", "cls", ",", "file_path", ")", ":", "# check that the file is there", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "raise", "ValueError", "(", "'Cannot find a .ddy file at {}'", ".", "format", "(", "file_path", ")", ")", "if", "not", "file_path", ".", "lower", "(", ")", ".", "endswith", "(", "'.ddy'", ")", ":", "raise", "ValueError", "(", "'DDY file does not have a .ddy extension.'", ")", "# check the python version and open the file", "try", ":", "iron_python", "=", "True", "if", "platform", ".", "python_implementation", "(", ")", "==", "'IronPython'", "else", "False", "except", "Exception", ":", "iron_python", "=", "True", "if", "iron_python", ":", "ddywin", "=", "codecs", ".", "open", "(", "file_path", ",", "'r'", ")", "else", ":", "ddywin", "=", "codecs", ".", "open", "(", "file_path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'ignore'", ")", "try", ":", "ddytxt", "=", "ddywin", ".", "read", "(", ")", "location_format", "=", "re", ".", "compile", "(", "r\"(Site:Location,(.|\\n)*?((;\\s*!)|(;\\s*\\n)|(;\\n)))\"", ")", "design_day_format", "=", "re", ".", "compile", "(", "r\"(SizingPeriod:DesignDay,(.|\\n)*?((;\\s*!)|(;\\s*\\n)|(;\\n)))\"", ")", "location_matches", "=", "location_format", ".", "findall", "(", "ddytxt", ")", "des_day_matches", "=", "design_day_format", ".", "findall", "(", "ddytxt", ")", "except", "Exception", "as", "e", ":", "import", "traceback", "raise", "Exception", "(", "'{}\\n{}'", ".", "format", "(", "e", ",", "traceback", ".", "format_exc", "(", ")", ")", ")", "else", ":", "# check to be sure location was found", "assert", "len", "(", "location_matches", ")", ">", "0", ",", "'No location objects found '", "'in .ddy file.'", "# build design day and location objects", "location", "=", "Location", ".", "from_location", "(", "location_matches", "[", "0", "]", "[", "0", "]", ")", "design_days", "=", "[", "DesignDay", ".", "from_ep_string", "(", "match", "[", "0", "]", ",", "location", ")", "for", "match", "in", "des_day_matches", "]", "finally", ":", "ddywin", ".", "close", "(", ")", "cls_", "=", "cls", "(", "location", ",", "design_days", ")", "cls_", ".", "_file_path", "=", "os", ".", "path", ".", "normpath", "(", "file_path", ")", "return", "cls_" ]
Initalize from a ddy file object from an existing ddy file. args: file_path: A string representing a complete path to the .ddy file.
[ "Initalize", "from", "a", "ddy", "file", "object", "from", "an", "existing", "ddy", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L64-L115
4,684
ladybug-tools/ladybug
ladybug/designday.py
DDY.save
def save(self, file_path): """Save ddy object as a .ddy file. args: file_path: A string representing the path to write the ddy file to. """ # write all data into the file # write the file data = self.location.ep_style_location_string + '\n\n' for d_day in self.design_days: data = data + d_day.ep_style_string + '\n\n' write_to_file(file_path, data, True)
python
def save(self, file_path): """Save ddy object as a .ddy file. args: file_path: A string representing the path to write the ddy file to. """ # write all data into the file # write the file data = self.location.ep_style_location_string + '\n\n' for d_day in self.design_days: data = data + d_day.ep_style_string + '\n\n' write_to_file(file_path, data, True)
[ "def", "save", "(", "self", ",", "file_path", ")", ":", "# write all data into the file", "# write the file", "data", "=", "self", ".", "location", ".", "ep_style_location_string", "+", "'\\n\\n'", "for", "d_day", "in", "self", ".", "design_days", ":", "data", "=", "data", "+", "d_day", ".", "ep_style_string", "+", "'\\n\\n'", "write_to_file", "(", "file_path", ",", "data", ",", "True", ")" ]
Save ddy object as a .ddy file. args: file_path: A string representing the path to write the ddy file to.
[ "Save", "ddy", "object", "as", "a", ".", "ddy", "file", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L126-L137
4,685
ladybug-tools/ladybug
ladybug/designday.py
DDY.filter_by_keyword
def filter_by_keyword(self, keyword): """Return a list of ddys that have a certain keyword in their name. This is useful for selecting out design days from a ddy file that are for a specific type of condition (for example, .4% cooling design days) """ filtered_days = [] for des_day in self.design_days: if keyword in des_day.name: filtered_days.append(des_day) return filtered_days
python
def filter_by_keyword(self, keyword): """Return a list of ddys that have a certain keyword in their name. This is useful for selecting out design days from a ddy file that are for a specific type of condition (for example, .4% cooling design days) """ filtered_days = [] for des_day in self.design_days: if keyword in des_day.name: filtered_days.append(des_day) return filtered_days
[ "def", "filter_by_keyword", "(", "self", ",", "keyword", ")", ":", "filtered_days", "=", "[", "]", "for", "des_day", "in", "self", ".", "design_days", ":", "if", "keyword", "in", "des_day", ".", "name", ":", "filtered_days", ".", "append", "(", "des_day", ")", "return", "filtered_days" ]
Return a list of ddys that have a certain keyword in their name. This is useful for selecting out design days from a ddy file that are for a specific type of condition (for example, .4% cooling design days)
[ "Return", "a", "list", "of", "ddys", "that", "have", "a", "certain", "keyword", "in", "their", "name", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L139-L149
4,686
ladybug-tools/ladybug
ladybug/designday.py
DesignDay.from_json
def from_json(cls, data): """Create a Design Day from a dictionary. Args: data = { "name": string, "day_type": string, "location": ladybug Location schema, "dry_bulb_condition": ladybug DryBulbCondition schema, "humidity_condition": ladybug HumidityCondition schema, "wind_condition": ladybug WindCondition schema, "sky_condition": ladybug SkyCondition schema} """ required_keys = ('name', 'day_type', 'location', 'dry_bulb_condition', 'humidity_condition', 'wind_condition', 'sky_condition') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) return cls(data['name'], data['day_type'], Location.from_json(data['location']), DryBulbCondition.from_json(data['dry_bulb_condition']), HumidityCondition.from_json(data['humidity_condition']), WindCondition.from_json(data['wind_condition']), SkyCondition.from_json(data['sky_condition']))
python
def from_json(cls, data): """Create a Design Day from a dictionary. Args: data = { "name": string, "day_type": string, "location": ladybug Location schema, "dry_bulb_condition": ladybug DryBulbCondition schema, "humidity_condition": ladybug HumidityCondition schema, "wind_condition": ladybug WindCondition schema, "sky_condition": ladybug SkyCondition schema} """ required_keys = ('name', 'day_type', 'location', 'dry_bulb_condition', 'humidity_condition', 'wind_condition', 'sky_condition') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) return cls(data['name'], data['day_type'], Location.from_json(data['location']), DryBulbCondition.from_json(data['dry_bulb_condition']), HumidityCondition.from_json(data['humidity_condition']), WindCondition.from_json(data['wind_condition']), SkyCondition.from_json(data['sky_condition']))
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "required_keys", "=", "(", "'name'", ",", "'day_type'", ",", "'location'", ",", "'dry_bulb_condition'", ",", "'humidity_condition'", ",", "'wind_condition'", ",", "'sky_condition'", ")", "for", "key", "in", "required_keys", ":", "assert", "key", "in", "data", ",", "'Required key \"{}\" is missing!'", ".", "format", "(", "key", ")", "return", "cls", "(", "data", "[", "'name'", "]", ",", "data", "[", "'day_type'", "]", ",", "Location", ".", "from_json", "(", "data", "[", "'location'", "]", ")", ",", "DryBulbCondition", ".", "from_json", "(", "data", "[", "'dry_bulb_condition'", "]", ")", ",", "HumidityCondition", ".", "from_json", "(", "data", "[", "'humidity_condition'", "]", ")", ",", "WindCondition", ".", "from_json", "(", "data", "[", "'wind_condition'", "]", ")", ",", "SkyCondition", ".", "from_json", "(", "data", "[", "'sky_condition'", "]", ")", ")" ]
Create a Design Day from a dictionary. Args: data = { "name": string, "day_type": string, "location": ladybug Location schema, "dry_bulb_condition": ladybug DryBulbCondition schema, "humidity_condition": ladybug HumidityCondition schema, "wind_condition": ladybug WindCondition schema, "sky_condition": ladybug SkyCondition schema}
[ "Create", "a", "Design", "Day", "from", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L298-L320
4,687
ladybug-tools/ladybug
ladybug/designday.py
DesignDay.from_design_day_properties
def from_design_day_properties(cls, name, day_type, location, analysis_period, dry_bulb_max, dry_bulb_range, humidity_type, humidity_value, barometric_p, wind_speed, wind_dir, sky_model, sky_properties): """Create a design day object from various key properties. Args: name: A text string to set the name of the design day day_type: Choose from 'SummerDesignDay', 'WinterDesignDay' or other EnergyPlus days location: Location for the design day analysis_period: Analysis period for the design day dry_bulb_max: Maximum dry bulb temperature over the design day (in C). dry_bulb_range: Dry bulb range over the design day (in C). humidity_type: Type of humidity to use. Choose from Wetbulb, Dewpoint, HumidityRatio, Enthalpy humidity_value: The value of the condition above. barometric_p: Barometric pressure in Pa. wind_speed: Wind speed over the design day in m/s. wind_dir: Wind direction over the design day in degrees. sky_model: Type of solar model to use. Choose from ASHRAEClearSky, ASHRAETau sky_properties: A list of properties describing the sky above. For ASHRAEClearSky this is a single value for clearness For ASHRAETau, this is the tau_beam and tau_diffuse """ dry_bulb_condition = DryBulbCondition( dry_bulb_max, dry_bulb_range) humidity_condition = HumidityCondition( humidity_type, humidity_value, barometric_p) wind_condition = WindCondition( wind_speed, wind_dir) if sky_model == 'ASHRAEClearSky': sky_condition = OriginalClearSkyCondition.from_analysis_period( analysis_period, sky_properties[0]) elif sky_model == 'ASHRAETau': sky_condition = RevisedClearSkyCondition.from_analysis_period( analysis_period, sky_properties[0], sky_properties[-1]) return cls(name, day_type, location, dry_bulb_condition, humidity_condition, wind_condition, sky_condition)
python
def from_design_day_properties(cls, name, day_type, location, analysis_period, dry_bulb_max, dry_bulb_range, humidity_type, humidity_value, barometric_p, wind_speed, wind_dir, sky_model, sky_properties): """Create a design day object from various key properties. Args: name: A text string to set the name of the design day day_type: Choose from 'SummerDesignDay', 'WinterDesignDay' or other EnergyPlus days location: Location for the design day analysis_period: Analysis period for the design day dry_bulb_max: Maximum dry bulb temperature over the design day (in C). dry_bulb_range: Dry bulb range over the design day (in C). humidity_type: Type of humidity to use. Choose from Wetbulb, Dewpoint, HumidityRatio, Enthalpy humidity_value: The value of the condition above. barometric_p: Barometric pressure in Pa. wind_speed: Wind speed over the design day in m/s. wind_dir: Wind direction over the design day in degrees. sky_model: Type of solar model to use. Choose from ASHRAEClearSky, ASHRAETau sky_properties: A list of properties describing the sky above. For ASHRAEClearSky this is a single value for clearness For ASHRAETau, this is the tau_beam and tau_diffuse """ dry_bulb_condition = DryBulbCondition( dry_bulb_max, dry_bulb_range) humidity_condition = HumidityCondition( humidity_type, humidity_value, barometric_p) wind_condition = WindCondition( wind_speed, wind_dir) if sky_model == 'ASHRAEClearSky': sky_condition = OriginalClearSkyCondition.from_analysis_period( analysis_period, sky_properties[0]) elif sky_model == 'ASHRAETau': sky_condition = RevisedClearSkyCondition.from_analysis_period( analysis_period, sky_properties[0], sky_properties[-1]) return cls(name, day_type, location, dry_bulb_condition, humidity_condition, wind_condition, sky_condition)
[ "def", "from_design_day_properties", "(", "cls", ",", "name", ",", "day_type", ",", "location", ",", "analysis_period", ",", "dry_bulb_max", ",", "dry_bulb_range", ",", "humidity_type", ",", "humidity_value", ",", "barometric_p", ",", "wind_speed", ",", "wind_dir", ",", "sky_model", ",", "sky_properties", ")", ":", "dry_bulb_condition", "=", "DryBulbCondition", "(", "dry_bulb_max", ",", "dry_bulb_range", ")", "humidity_condition", "=", "HumidityCondition", "(", "humidity_type", ",", "humidity_value", ",", "barometric_p", ")", "wind_condition", "=", "WindCondition", "(", "wind_speed", ",", "wind_dir", ")", "if", "sky_model", "==", "'ASHRAEClearSky'", ":", "sky_condition", "=", "OriginalClearSkyCondition", ".", "from_analysis_period", "(", "analysis_period", ",", "sky_properties", "[", "0", "]", ")", "elif", "sky_model", "==", "'ASHRAETau'", ":", "sky_condition", "=", "RevisedClearSkyCondition", ".", "from_analysis_period", "(", "analysis_period", ",", "sky_properties", "[", "0", "]", ",", "sky_properties", "[", "-", "1", "]", ")", "return", "cls", "(", "name", ",", "day_type", ",", "location", ",", "dry_bulb_condition", ",", "humidity_condition", ",", "wind_condition", ",", "sky_condition", ")" ]
Create a design day object from various key properties. Args: name: A text string to set the name of the design day day_type: Choose from 'SummerDesignDay', 'WinterDesignDay' or other EnergyPlus days location: Location for the design day analysis_period: Analysis period for the design day dry_bulb_max: Maximum dry bulb temperature over the design day (in C). dry_bulb_range: Dry bulb range over the design day (in C). humidity_type: Type of humidity to use. Choose from Wetbulb, Dewpoint, HumidityRatio, Enthalpy humidity_value: The value of the condition above. barometric_p: Barometric pressure in Pa. wind_speed: Wind speed over the design day in m/s. wind_dir: Wind direction over the design day in degrees. sky_model: Type of solar model to use. Choose from ASHRAEClearSky, ASHRAETau sky_properties: A list of properties describing the sky above. For ASHRAEClearSky this is a single value for clearness For ASHRAETau, this is the tau_beam and tau_diffuse
[ "Create", "a", "design", "day", "object", "from", "various", "key", "properties", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L386-L425
4,688
ladybug-tools/ladybug
ladybug/designday.py
DesignDay.analysis_period
def analysis_period(self): """The analysisperiod of the design day.""" return AnalysisPeriod( self.sky_condition.month, self.sky_condition.day_of_month, 0, self.sky_condition.month, self.sky_condition.day_of_month, 23)
python
def analysis_period(self): """The analysisperiod of the design day.""" return AnalysisPeriod( self.sky_condition.month, self.sky_condition.day_of_month, 0, self.sky_condition.month, self.sky_condition.day_of_month, 23)
[ "def", "analysis_period", "(", "self", ")", ":", "return", "AnalysisPeriod", "(", "self", ".", "sky_condition", ".", "month", ",", "self", ".", "sky_condition", ".", "day_of_month", ",", "0", ",", "self", ".", "sky_condition", ".", "month", ",", "self", ".", "sky_condition", ".", "day_of_month", ",", "23", ")" ]
The analysisperiod of the design day.
[ "The", "analysisperiod", "of", "the", "design", "day", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L629-L637
4,689
ladybug-tools/ladybug
ladybug/designday.py
DesignDay.hourly_dew_point
def hourly_dew_point(self): """A data collection containing hourly dew points over they day.""" dpt_data = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) return self._get_daily_data_collections( temperature.DewPointTemperature(), 'C', dpt_data)
python
def hourly_dew_point(self): """A data collection containing hourly dew points over they day.""" dpt_data = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) return self._get_daily_data_collections( temperature.DewPointTemperature(), 'C', dpt_data)
[ "def", "hourly_dew_point", "(", "self", ")", ":", "dpt_data", "=", "self", ".", "_humidity_condition", ".", "hourly_dew_point_values", "(", "self", ".", "_dry_bulb_condition", ")", "return", "self", ".", "_get_daily_data_collections", "(", "temperature", ".", "DewPointTemperature", "(", ")", ",", "'C'", ",", "dpt_data", ")" ]
A data collection containing hourly dew points over they day.
[ "A", "data", "collection", "containing", "hourly", "dew", "points", "over", "they", "day", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L651-L656
4,690
ladybug-tools/ladybug
ladybug/designday.py
DesignDay.hourly_relative_humidity
def hourly_relative_humidity(self): """A data collection containing hourly relative humidity over they day.""" dpt_data = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) rh_data = [rel_humid_from_db_dpt(x, y) for x, y in zip( self._dry_bulb_condition.hourly_values, dpt_data)] return self._get_daily_data_collections( fraction.RelativeHumidity(), '%', rh_data)
python
def hourly_relative_humidity(self): """A data collection containing hourly relative humidity over they day.""" dpt_data = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) rh_data = [rel_humid_from_db_dpt(x, y) for x, y in zip( self._dry_bulb_condition.hourly_values, dpt_data)] return self._get_daily_data_collections( fraction.RelativeHumidity(), '%', rh_data)
[ "def", "hourly_relative_humidity", "(", "self", ")", ":", "dpt_data", "=", "self", ".", "_humidity_condition", ".", "hourly_dew_point_values", "(", "self", ".", "_dry_bulb_condition", ")", "rh_data", "=", "[", "rel_humid_from_db_dpt", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "self", ".", "_dry_bulb_condition", ".", "hourly_values", ",", "dpt_data", ")", "]", "return", "self", ".", "_get_daily_data_collections", "(", "fraction", ".", "RelativeHumidity", "(", ")", ",", "'%'", ",", "rh_data", ")" ]
A data collection containing hourly relative humidity over they day.
[ "A", "data", "collection", "containing", "hourly", "relative", "humidity", "over", "they", "day", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L659-L666
4,691
ladybug-tools/ladybug
ladybug/designday.py
DesignDay.hourly_solar_radiation
def hourly_solar_radiation(self): """Three data collections containing hourly direct normal, diffuse horizontal, and global horizontal radiation. """ dir_norm, diff_horiz, glob_horiz = \ self._sky_condition.radiation_values(self._location) dir_norm_data = self._get_daily_data_collections( energyintensity.DirectNormalRadiation(), 'Wh/m2', dir_norm) diff_horiz_data = self._get_daily_data_collections( energyintensity.DiffuseHorizontalRadiation(), 'Wh/m2', diff_horiz) glob_horiz_data = self._get_daily_data_collections( energyintensity.GlobalHorizontalRadiation(), 'Wh/m2', glob_horiz) return dir_norm_data, diff_horiz_data, glob_horiz_data
python
def hourly_solar_radiation(self): """Three data collections containing hourly direct normal, diffuse horizontal, and global horizontal radiation. """ dir_norm, diff_horiz, glob_horiz = \ self._sky_condition.radiation_values(self._location) dir_norm_data = self._get_daily_data_collections( energyintensity.DirectNormalRadiation(), 'Wh/m2', dir_norm) diff_horiz_data = self._get_daily_data_collections( energyintensity.DiffuseHorizontalRadiation(), 'Wh/m2', diff_horiz) glob_horiz_data = self._get_daily_data_collections( energyintensity.GlobalHorizontalRadiation(), 'Wh/m2', glob_horiz) return dir_norm_data, diff_horiz_data, glob_horiz_data
[ "def", "hourly_solar_radiation", "(", "self", ")", ":", "dir_norm", ",", "diff_horiz", ",", "glob_horiz", "=", "self", ".", "_sky_condition", ".", "radiation_values", "(", "self", ".", "_location", ")", "dir_norm_data", "=", "self", ".", "_get_daily_data_collections", "(", "energyintensity", ".", "DirectNormalRadiation", "(", ")", ",", "'Wh/m2'", ",", "dir_norm", ")", "diff_horiz_data", "=", "self", ".", "_get_daily_data_collections", "(", "energyintensity", ".", "DiffuseHorizontalRadiation", "(", ")", ",", "'Wh/m2'", ",", "diff_horiz", ")", "glob_horiz_data", "=", "self", ".", "_get_daily_data_collections", "(", "energyintensity", ".", "GlobalHorizontalRadiation", "(", ")", ",", "'Wh/m2'", ",", "glob_horiz", ")", "return", "dir_norm_data", ",", "diff_horiz_data", ",", "glob_horiz_data" ]
Three data collections containing hourly direct normal, diffuse horizontal, and global horizontal radiation.
[ "Three", "data", "collections", "containing", "hourly", "direct", "normal", "diffuse", "horizontal", "and", "global", "horizontal", "radiation", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L688-L702
4,692
ladybug-tools/ladybug
ladybug/designday.py
DesignDay._get_daily_data_collections
def _get_daily_data_collections(self, data_type, unit, values): """Return an empty data collection.""" data_header = Header(data_type=data_type, unit=unit, analysis_period=self.analysis_period, metadata={'source': self._location.source, 'country': self._location.country, 'city': self._location.city}) return HourlyContinuousCollection(data_header, values)
python
def _get_daily_data_collections(self, data_type, unit, values): """Return an empty data collection.""" data_header = Header(data_type=data_type, unit=unit, analysis_period=self.analysis_period, metadata={'source': self._location.source, 'country': self._location.country, 'city': self._location.city}) return HourlyContinuousCollection(data_header, values)
[ "def", "_get_daily_data_collections", "(", "self", ",", "data_type", ",", "unit", ",", "values", ")", ":", "data_header", "=", "Header", "(", "data_type", "=", "data_type", ",", "unit", "=", "unit", ",", "analysis_period", "=", "self", ".", "analysis_period", ",", "metadata", "=", "{", "'source'", ":", "self", ".", "_location", ".", "source", ",", "'country'", ":", "self", ".", "_location", ".", "country", ",", "'city'", ":", "self", ".", "_location", ".", "city", "}", ")", "return", "HourlyContinuousCollection", "(", "data_header", ",", "values", ")" ]
Return an empty data collection.
[ "Return", "an", "empty", "data", "collection", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L727-L734
4,693
ladybug-tools/ladybug
ladybug/designday.py
DryBulbCondition.hourly_values
def hourly_values(self): """A list of temperature values for each hour over the design day.""" return [self._dry_bulb_max - self._dry_bulb_range * x for x in self.temp_multipliers]
python
def hourly_values(self): """A list of temperature values for each hour over the design day.""" return [self._dry_bulb_max - self._dry_bulb_range * x for x in self.temp_multipliers]
[ "def", "hourly_values", "(", "self", ")", ":", "return", "[", "self", ".", "_dry_bulb_max", "-", "self", ".", "_dry_bulb_range", "*", "x", "for", "x", "in", "self", ".", "temp_multipliers", "]" ]
A list of temperature values for each hour over the design day.
[ "A", "list", "of", "temperature", "values", "for", "each", "hour", "over", "the", "design", "day", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L805-L808
4,694
ladybug-tools/ladybug
ladybug/designday.py
DryBulbCondition.to_json
def to_json(self): """Convert the Dry Bulb Condition to a dictionary.""" return { 'dry_bulb_max': self.dry_bulb_max, 'dry_bulb_range': self.dry_bulb_range, 'modifier_type': self.modifier_type, 'modifier_schedule': self.modifier_schedule }
python
def to_json(self): """Convert the Dry Bulb Condition to a dictionary.""" return { 'dry_bulb_max': self.dry_bulb_max, 'dry_bulb_range': self.dry_bulb_range, 'modifier_type': self.modifier_type, 'modifier_schedule': self.modifier_schedule }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'dry_bulb_max'", ":", "self", ".", "dry_bulb_max", ",", "'dry_bulb_range'", ":", "self", ".", "dry_bulb_range", ",", "'modifier_type'", ":", "self", ".", "modifier_type", ",", "'modifier_schedule'", ":", "self", ".", "modifier_schedule", "}" ]
Convert the Dry Bulb Condition to a dictionary.
[ "Convert", "the", "Dry", "Bulb", "Condition", "to", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L846-L853
4,695
ladybug-tools/ladybug
ladybug/designday.py
HumidityCondition.from_json
def from_json(cls, data): """Create a Humidity Condition from a dictionary. Args: data = { "hum_type": string, "hum_value": float, "barometric_pressure": float, "schedule": string, "wet_bulb_range": string} """ # Check required and optional keys required_keys = ('hum_type', 'hum_value') optional_keys = {'barometric_pressure': 101325, 'schedule': '', 'wet_bulb_range': ''} for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) for key, val in optional_keys.items(): if key not in data: data[key] = val return cls(data['hum_type'], data['hum_value'], data['barometric_pressure'], data['schedule'], data['wet_bulb_range'])
python
def from_json(cls, data): """Create a Humidity Condition from a dictionary. Args: data = { "hum_type": string, "hum_value": float, "barometric_pressure": float, "schedule": string, "wet_bulb_range": string} """ # Check required and optional keys required_keys = ('hum_type', 'hum_value') optional_keys = {'barometric_pressure': 101325, 'schedule': '', 'wet_bulb_range': ''} for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) for key, val in optional_keys.items(): if key not in data: data[key] = val return cls(data['hum_type'], data['hum_value'], data['barometric_pressure'], data['schedule'], data['wet_bulb_range'])
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "# Check required and optional keys", "required_keys", "=", "(", "'hum_type'", ",", "'hum_value'", ")", "optional_keys", "=", "{", "'barometric_pressure'", ":", "101325", ",", "'schedule'", ":", "''", ",", "'wet_bulb_range'", ":", "''", "}", "for", "key", "in", "required_keys", ":", "assert", "key", "in", "data", ",", "'Required key \"{}\" is missing!'", ".", "format", "(", "key", ")", "for", "key", ",", "val", "in", "optional_keys", ".", "items", "(", ")", ":", "if", "key", "not", "in", "data", ":", "data", "[", "key", "]", "=", "val", "return", "cls", "(", "data", "[", "'hum_type'", "]", ",", "data", "[", "'hum_value'", "]", ",", "data", "[", "'barometric_pressure'", "]", ",", "data", "[", "'schedule'", "]", ",", "data", "[", "'wet_bulb_range'", "]", ")" ]
Create a Humidity Condition from a dictionary. Args: data = { "hum_type": string, "hum_value": float, "barometric_pressure": float, "schedule": string, "wet_bulb_range": string}
[ "Create", "a", "Humidity", "Condition", "from", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L886-L908
4,696
ladybug-tools/ladybug
ladybug/designday.py
HumidityCondition.to_json
def to_json(self): """Convert the Humidity Condition to a dictionary.""" return { 'hum_type': self.hum_type, 'hum_value': self.hum_value, 'barometric_pressure': self.barometric_pressure, 'schedule': self.schedule, 'wet_bulb_range': self.wet_bulb_range, }
python
def to_json(self): """Convert the Humidity Condition to a dictionary.""" return { 'hum_type': self.hum_type, 'hum_value': self.hum_value, 'barometric_pressure': self.barometric_pressure, 'schedule': self.schedule, 'wet_bulb_range': self.wet_bulb_range, }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'hum_type'", ":", "self", ".", "hum_type", ",", "'hum_value'", ":", "self", ".", "hum_value", ",", "'barometric_pressure'", ":", "self", ".", "barometric_pressure", ",", "'schedule'", ":", "self", ".", "schedule", ",", "'wet_bulb_range'", ":", "self", ".", "wet_bulb_range", ",", "}" ]
Convert the Humidity Condition to a dictionary.
[ "Convert", "the", "Humidity", "Condition", "to", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L991-L999
4,697
ladybug-tools/ladybug
ladybug/designday.py
WindCondition.from_json
def from_json(cls, data): """Create a Wind Condition from a dictionary. Args: data = { "wind_speed": float, "wind_direction": float, "rain": bool, "snow_on_ground": bool} """ # Check required and optional keys optional_keys = {'wind_direction': 0, 'rain': False, 'snow_on_ground': False} assert 'wind_speed' in data, 'Required key "wind_speed" is missing!' for key, val in optional_keys.items(): if key not in data: data[key] = val return cls(data['wind_speed'], data['wind_direction'], data['rain'], data['snow_on_ground'])
python
def from_json(cls, data): """Create a Wind Condition from a dictionary. Args: data = { "wind_speed": float, "wind_direction": float, "rain": bool, "snow_on_ground": bool} """ # Check required and optional keys optional_keys = {'wind_direction': 0, 'rain': False, 'snow_on_ground': False} assert 'wind_speed' in data, 'Required key "wind_speed" is missing!' for key, val in optional_keys.items(): if key not in data: data[key] = val return cls(data['wind_speed'], data['wind_direction'], data['rain'], data['snow_on_ground'])
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "# Check required and optional keys", "optional_keys", "=", "{", "'wind_direction'", ":", "0", ",", "'rain'", ":", "False", ",", "'snow_on_ground'", ":", "False", "}", "assert", "'wind_speed'", "in", "data", ",", "'Required key \"wind_speed\" is missing!'", "for", "key", ",", "val", "in", "optional_keys", ".", "items", "(", ")", ":", "if", "key", "not", "in", "data", ":", "data", "[", "key", "]", "=", "val", "return", "cls", "(", "data", "[", "'wind_speed'", "]", ",", "data", "[", "'wind_direction'", "]", ",", "data", "[", "'rain'", "]", ",", "data", "[", "'snow_on_ground'", "]", ")" ]
Create a Wind Condition from a dictionary. Args: data = { "wind_speed": float, "wind_direction": float, "rain": bool, "snow_on_ground": bool}
[ "Create", "a", "Wind", "Condition", "from", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1029-L1047
4,698
ladybug-tools/ladybug
ladybug/designday.py
WindCondition.to_json
def to_json(self): """Convert the Wind Condition to a dictionary.""" return { 'wind_speed': self.wind_speed, 'wind_direction': self.wind_direction, 'rain': self.rain, 'snow_on_ground': self.snow_on_ground }
python
def to_json(self): """Convert the Wind Condition to a dictionary.""" return { 'wind_speed': self.wind_speed, 'wind_direction': self.wind_direction, 'rain': self.rain, 'snow_on_ground': self.snow_on_ground }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'wind_speed'", ":", "self", ".", "wind_speed", ",", "'wind_direction'", ":", "self", ".", "wind_direction", ",", "'rain'", ":", "self", ".", "rain", ",", "'snow_on_ground'", ":", "self", ".", "snow_on_ground", "}" ]
Convert the Wind Condition to a dictionary.
[ "Convert", "the", "Wind", "Condition", "to", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1116-L1123
4,699
ladybug-tools/ladybug
ladybug/designday.py
SkyCondition._get_datetimes
def _get_datetimes(self, timestep=1): """List of datetimes based on design day date and timestep.""" start_moy = DateTime(self._month, self._day_of_month).moy if timestep == 1: start_moy = start_moy + 30 num_moys = 24 * timestep return tuple( DateTime.from_moy(start_moy + (i * (1 / timestep) * 60)) for i in xrange(num_moys) )
python
def _get_datetimes(self, timestep=1): """List of datetimes based on design day date and timestep.""" start_moy = DateTime(self._month, self._day_of_month).moy if timestep == 1: start_moy = start_moy + 30 num_moys = 24 * timestep return tuple( DateTime.from_moy(start_moy + (i * (1 / timestep) * 60)) for i in xrange(num_moys) )
[ "def", "_get_datetimes", "(", "self", ",", "timestep", "=", "1", ")", ":", "start_moy", "=", "DateTime", "(", "self", ".", "_month", ",", "self", ".", "_day_of_month", ")", ".", "moy", "if", "timestep", "==", "1", ":", "start_moy", "=", "start_moy", "+", "30", "num_moys", "=", "24", "*", "timestep", "return", "tuple", "(", "DateTime", ".", "from_moy", "(", "start_moy", "+", "(", "i", "*", "(", "1", "/", "timestep", ")", "*", "60", ")", ")", "for", "i", "in", "xrange", "(", "num_moys", ")", ")" ]
List of datetimes based on design day date and timestep.
[ "List", "of", "datetimes", "based", "on", "design", "day", "date", "and", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1230-L1239