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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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
train
237,500
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
train
237,501
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
train
237,502
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
train
237,503
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
train
237,504
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
train
237,505
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
train
237,506
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
train
237,507
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
train
237,508
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
train
237,509
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
train
237,510
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
train
237,511
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
train
237,512
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
train
237,513
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
train
237,514
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
train
237,515
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
train
237,516
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
train
237,517
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
train
237,518
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
train
237,519
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
train
237,520
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
train
237,521
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
train
237,522
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
train
237,523
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
train
237,524
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
train
237,525
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
train
237,526
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
train
237,527
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
train
237,528
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 \ (Trygve.Wastvedt@gmail.com) 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 \ (Trygve.Wastvedt@gmail.com) 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 \ (Trygve.Wastvedt@gmail.com) 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
train
237,529
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
train
237,530
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
train
237,531
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
train
237,532
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
train
237,533
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
train
237,534
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
train
237,535
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
train
237,536
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
train
237,537
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
train
237,538
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
train
237,539
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
train
237,540
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
train
237,541
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
train
237,542
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
train
237,543
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
train
237,544
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
train
237,545
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
train
237,546
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
train
237,547
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
train
237,548
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
train
237,549
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
train
237,550
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
train
237,551
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
train
237,552
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
train
237,553
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
train
237,554
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
train
237,555
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
train
237,556
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
train
237,557
ladybug-tools/ladybug
ladybug/designday.py
OriginalClearSkyCondition.from_analysis_period
def from_analysis_period(cls, analysis_period, clearness=1, daylight_savings_indicator='No'): """"Initialize a OriginalClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, clearness, daylight_savings_indicator)
python
def from_analysis_period(cls, analysis_period, clearness=1, daylight_savings_indicator='No'): """"Initialize a OriginalClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, clearness, daylight_savings_indicator)
[ "def", "from_analysis_period", "(", "cls", ",", "analysis_period", ",", "clearness", "=", "1", ",", "daylight_savings_indicator", "=", "'No'", ")", ":", "_check_analysis_period", "(", "analysis_period", ")", "return", "cls", "(", "analysis_period", ".", "st_month", ",", "analysis_period", ".", "st_day", ",", "clearness", ",", "daylight_savings_indicator", ")" ]
Initialize a OriginalClearSkyCondition from an analysis_period
[ "Initialize", "a", "OriginalClearSkyCondition", "from", "an", "analysis_period" ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1289-L1294
train
237,558
ladybug-tools/ladybug
ladybug/designday.py
OriginalClearSkyCondition.radiation_values
def radiation_values(self, location, timestep=1): """Lists of driect normal, diffuse horiz, and global horiz rad at each timestep. """ # create sunpath and get altitude at every timestep of the design day sp = Sunpath.from_location(location) altitudes = [] dates = self._get_datetimes(timestep) for t_date in dates: sun = sp.calculate_sun_from_date_time(t_date) altitudes.append(sun.altitude) dir_norm, diff_horiz = ashrae_clear_sky( altitudes, self._month, self._clearness) glob_horiz = [dhr + dnr * math.sin(math.radians(alt)) for alt, dnr, dhr in zip(altitudes, dir_norm, diff_horiz)] return dir_norm, diff_horiz, glob_horiz
python
def radiation_values(self, location, timestep=1): """Lists of driect normal, diffuse horiz, and global horiz rad at each timestep. """ # create sunpath and get altitude at every timestep of the design day sp = Sunpath.from_location(location) altitudes = [] dates = self._get_datetimes(timestep) for t_date in dates: sun = sp.calculate_sun_from_date_time(t_date) altitudes.append(sun.altitude) dir_norm, diff_horiz = ashrae_clear_sky( altitudes, self._month, self._clearness) glob_horiz = [dhr + dnr * math.sin(math.radians(alt)) for alt, dnr, dhr in zip(altitudes, dir_norm, diff_horiz)] return dir_norm, diff_horiz, glob_horiz
[ "def", "radiation_values", "(", "self", ",", "location", ",", "timestep", "=", "1", ")", ":", "# create sunpath and get altitude at every timestep of the design day", "sp", "=", "Sunpath", ".", "from_location", "(", "location", ")", "altitudes", "=", "[", "]", "dates", "=", "self", ".", "_get_datetimes", "(", "timestep", ")", "for", "t_date", "in", "dates", ":", "sun", "=", "sp", ".", "calculate_sun_from_date_time", "(", "t_date", ")", "altitudes", ".", "append", "(", "sun", ".", "altitude", ")", "dir_norm", ",", "diff_horiz", "=", "ashrae_clear_sky", "(", "altitudes", ",", "self", ".", "_month", ",", "self", ".", "_clearness", ")", "glob_horiz", "=", "[", "dhr", "+", "dnr", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "alt", ")", ")", "for", "alt", ",", "dnr", ",", "dhr", "in", "zip", "(", "altitudes", ",", "dir_norm", ",", "diff_horiz", ")", "]", "return", "dir_norm", ",", "diff_horiz", ",", "glob_horiz" ]
Lists of driect normal, diffuse horiz, and global horiz rad at each timestep.
[ "Lists", "of", "driect", "normal", "diffuse", "horiz", "and", "global", "horiz", "rad", "at", "each", "timestep", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1341-L1355
train
237,559
ladybug-tools/ladybug
ladybug/designday.py
RevisedClearSkyCondition.from_analysis_period
def from_analysis_period(cls, analysis_period, tau_b, tau_d, daylight_savings_indicator='No'): """"Initialize a RevisedClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, tau_b, tau_d, daylight_savings_indicator)
python
def from_analysis_period(cls, analysis_period, tau_b, tau_d, daylight_savings_indicator='No'): """"Initialize a RevisedClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, tau_b, tau_d, daylight_savings_indicator)
[ "def", "from_analysis_period", "(", "cls", ",", "analysis_period", ",", "tau_b", ",", "tau_d", ",", "daylight_savings_indicator", "=", "'No'", ")", ":", "_check_analysis_period", "(", "analysis_period", ")", "return", "cls", "(", "analysis_period", ".", "st_month", ",", "analysis_period", ".", "st_day", ",", "tau_b", ",", "tau_d", ",", "daylight_savings_indicator", ")" ]
Initialize a RevisedClearSkyCondition from an analysis_period
[ "Initialize", "a", "RevisedClearSkyCondition", "from", "an", "analysis_period" ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1387-L1392
train
237,560
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.convert_to_unit
def convert_to_unit(self, unit): """Convert the Data Collection to the input unit.""" self._values = self._header.data_type.to_unit( self._values, unit, self._header.unit) self._header._unit = unit
python
def convert_to_unit(self, unit): """Convert the Data Collection to the input unit.""" self._values = self._header.data_type.to_unit( self._values, unit, self._header.unit) self._header._unit = unit
[ "def", "convert_to_unit", "(", "self", ",", "unit", ")", ":", "self", ".", "_values", "=", "self", ".", "_header", ".", "data_type", ".", "to_unit", "(", "self", ".", "_values", ",", "unit", ",", "self", ".", "_header", ".", "unit", ")", "self", ".", "_header", ".", "_unit", "=", "unit" ]
Convert the Data Collection to the input unit.
[ "Convert", "the", "Data", "Collection", "to", "the", "input", "unit", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L126-L130
train
237,561
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.convert_to_ip
def convert_to_ip(self): """Convert the Data Collection to IP units.""" self._values, self._header._unit = self._header.data_type.to_ip( self._values, self._header.unit)
python
def convert_to_ip(self): """Convert the Data Collection to IP units.""" self._values, self._header._unit = self._header.data_type.to_ip( self._values, self._header.unit)
[ "def", "convert_to_ip", "(", "self", ")", ":", "self", ".", "_values", ",", "self", ".", "_header", ".", "_unit", "=", "self", ".", "_header", ".", "data_type", ".", "to_ip", "(", "self", ".", "_values", ",", "self", ".", "_header", ".", "unit", ")" ]
Convert the Data Collection to IP units.
[ "Convert", "the", "Data", "Collection", "to", "IP", "units", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L132-L135
train
237,562
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.convert_to_si
def convert_to_si(self): """Convert the Data Collection to SI units.""" self._values, self._header._unit = self._header.data_type.to_si( self._values, self._header.unit)
python
def convert_to_si(self): """Convert the Data Collection to SI units.""" self._values, self._header._unit = self._header.data_type.to_si( self._values, self._header.unit)
[ "def", "convert_to_si", "(", "self", ")", ":", "self", ".", "_values", ",", "self", ".", "_header", ".", "_unit", "=", "self", ".", "_header", ".", "data_type", ".", "to_si", "(", "self", ".", "_values", ",", "self", ".", "_header", ".", "unit", ")" ]
Convert the Data Collection to SI units.
[ "Convert", "the", "Data", "Collection", "to", "SI", "units", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L137-L140
train
237,563
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.to_unit
def to_unit(self, unit): """Return a Data Collection in the input unit.""" new_data_c = self.duplicate() new_data_c.convert_to_unit(unit) return new_data_c
python
def to_unit(self, unit): """Return a Data Collection in the input unit.""" new_data_c = self.duplicate() new_data_c.convert_to_unit(unit) return new_data_c
[ "def", "to_unit", "(", "self", ",", "unit", ")", ":", "new_data_c", "=", "self", ".", "duplicate", "(", ")", "new_data_c", ".", "convert_to_unit", "(", "unit", ")", "return", "new_data_c" ]
Return a Data Collection in the input unit.
[ "Return", "a", "Data", "Collection", "in", "the", "input", "unit", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L142-L146
train
237,564
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.is_in_data_type_range
def is_in_data_type_range(self, raise_exception=True): """Check if collection values are in physically possible ranges for the data_type. If this method returns False, the Data Collection's data is physically or mathematically impossible for the data_type.""" return self._header.data_type.is_in_range( self._values, self._header.unit, raise_exception)
python
def is_in_data_type_range(self, raise_exception=True): """Check if collection values are in physically possible ranges for the data_type. If this method returns False, the Data Collection's data is physically or mathematically impossible for the data_type.""" return self._header.data_type.is_in_range( self._values, self._header.unit, raise_exception)
[ "def", "is_in_data_type_range", "(", "self", ",", "raise_exception", "=", "True", ")", ":", "return", "self", ".", "_header", ".", "data_type", ".", "is_in_range", "(", "self", ".", "_values", ",", "self", ".", "_header", ".", "unit", ",", "raise_exception", ")" ]
Check if collection values are in physically possible ranges for the data_type. If this method returns False, the Data Collection's data is physically or mathematically impossible for the data_type.
[ "Check", "if", "collection", "values", "are", "in", "physically", "possible", "ranges", "for", "the", "data_type", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L160-L166
train
237,565
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.get_highest_values
def get_highest_values(self, count): """Get a list of the the x highest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the largest values of a data collection occur. For example, there is a European dayight code that requires an analysis for the hours of the year with the greatest exterior illuminance level. This method can be used to help build a shcedule for such a study. Args: count: Integer representing the number of highest values to account for. Returns: highest_values: The n highest values in data list, ordered from highest to lowest. highest_values_index: Indicies of the n highest values in data list, ordered from highest to lowest. """ count = int(count) assert count <= len(self._values), \ 'count must be smaller than or equal to values length. {} > {}.'.format( count, len(self._values)) assert count > 0, \ 'count must be greater than 0. Got {}.'.format(count) highest_values = sorted(self._values, reverse=True)[0:count] highest_values_index = sorted(list(xrange(len(self._values))), key=lambda k: self._values[k], reverse=True)[0:count] return highest_values, highest_values_index
python
def get_highest_values(self, count): """Get a list of the the x highest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the largest values of a data collection occur. For example, there is a European dayight code that requires an analysis for the hours of the year with the greatest exterior illuminance level. This method can be used to help build a shcedule for such a study. Args: count: Integer representing the number of highest values to account for. Returns: highest_values: The n highest values in data list, ordered from highest to lowest. highest_values_index: Indicies of the n highest values in data list, ordered from highest to lowest. """ count = int(count) assert count <= len(self._values), \ 'count must be smaller than or equal to values length. {} > {}.'.format( count, len(self._values)) assert count > 0, \ 'count must be greater than 0. Got {}.'.format(count) highest_values = sorted(self._values, reverse=True)[0:count] highest_values_index = sorted(list(xrange(len(self._values))), key=lambda k: self._values[k], reverse=True)[0:count] return highest_values, highest_values_index
[ "def", "get_highest_values", "(", "self", ",", "count", ")", ":", "count", "=", "int", "(", "count", ")", "assert", "count", "<=", "len", "(", "self", ".", "_values", ")", ",", "'count must be smaller than or equal to values length. {} > {}.'", ".", "format", "(", "count", ",", "len", "(", "self", ".", "_values", ")", ")", "assert", "count", ">", "0", ",", "'count must be greater than 0. Got {}.'", ".", "format", "(", "count", ")", "highest_values", "=", "sorted", "(", "self", ".", "_values", ",", "reverse", "=", "True", ")", "[", "0", ":", "count", "]", "highest_values_index", "=", "sorted", "(", "list", "(", "xrange", "(", "len", "(", "self", ".", "_values", ")", ")", ")", ",", "key", "=", "lambda", "k", ":", "self", ".", "_values", "[", "k", "]", ",", "reverse", "=", "True", ")", "[", "0", ":", "count", "]", "return", "highest_values", ",", "highest_values_index" ]
Get a list of the the x highest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the largest values of a data collection occur. For example, there is a European dayight code that requires an analysis for the hours of the year with the greatest exterior illuminance level. This method can be used to help build a shcedule for such a study. Args: count: Integer representing the number of highest values to account for. Returns: highest_values: The n highest values in data list, ordered from highest to lowest. highest_values_index: Indicies of the n highest values in data list, ordered from highest to lowest.
[ "Get", "a", "list", "of", "the", "the", "x", "highest", "values", "of", "the", "Data", "Collection", "and", "their", "indices", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L179-L207
train
237,566
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.get_lowest_values
def get_lowest_values(self, count): """Get a list of the the x lowest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the smallest values of a data collection occur. Args: count: Integer representing the number of lowest values to account for. Returns: highest_values: The n lowest values in data list, ordered from lowest to lowest. lowest_values_index: Indicies of the n lowest values in data list, ordered from lowest to lowest. """ count = int(count) assert count <= len(self._values), \ 'count must be <= to Data Collection len. {} > {}.'.format( count, len(self._values)) assert count > 0, \ 'count must be greater than 0. Got {}.'.format(count) lowest_values = sorted(self._values)[0:count] lowest_values_index = sorted(list(xrange(len(self._values))), key=lambda k: self._values[k])[0:count] return lowest_values, lowest_values_index
python
def get_lowest_values(self, count): """Get a list of the the x lowest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the smallest values of a data collection occur. Args: count: Integer representing the number of lowest values to account for. Returns: highest_values: The n lowest values in data list, ordered from lowest to lowest. lowest_values_index: Indicies of the n lowest values in data list, ordered from lowest to lowest. """ count = int(count) assert count <= len(self._values), \ 'count must be <= to Data Collection len. {} > {}.'.format( count, len(self._values)) assert count > 0, \ 'count must be greater than 0. Got {}.'.format(count) lowest_values = sorted(self._values)[0:count] lowest_values_index = sorted(list(xrange(len(self._values))), key=lambda k: self._values[k])[0:count] return lowest_values, lowest_values_index
[ "def", "get_lowest_values", "(", "self", ",", "count", ")", ":", "count", "=", "int", "(", "count", ")", "assert", "count", "<=", "len", "(", "self", ".", "_values", ")", ",", "'count must be <= to Data Collection len. {} > {}.'", ".", "format", "(", "count", ",", "len", "(", "self", ".", "_values", ")", ")", "assert", "count", ">", "0", ",", "'count must be greater than 0. Got {}.'", ".", "format", "(", "count", ")", "lowest_values", "=", "sorted", "(", "self", ".", "_values", ")", "[", "0", ":", "count", "]", "lowest_values_index", "=", "sorted", "(", "list", "(", "xrange", "(", "len", "(", "self", ".", "_values", ")", ")", ")", ",", "key", "=", "lambda", "k", ":", "self", ".", "_values", "[", "k", "]", ")", "[", "0", ":", "count", "]", "return", "lowest_values", ",", "lowest_values_index" ]
Get a list of the the x lowest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the smallest values of a data collection occur. Args: count: Integer representing the number of lowest values to account for. Returns: highest_values: The n lowest values in data list, ordered from lowest to lowest. lowest_values_index: Indicies of the n lowest values in data list, ordered from lowest to lowest.
[ "Get", "a", "list", "of", "the", "the", "x", "lowest", "values", "of", "the", "Data", "Collection", "and", "their", "indices", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L209-L233
train
237,567
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.get_percentile
def get_percentile(self, percentile): """Get a value representing a the input percentile of the Data Collection. Args: percentile: A float value from 0 to 100 representing the requested percentile. Return: The Data Collection value at the input percentile """ assert 0 <= percentile <= 100, \ 'percentile must be between 0 and 100. Got {}'.format(percentile) return self._percentile(self._values, percentile)
python
def get_percentile(self, percentile): """Get a value representing a the input percentile of the Data Collection. Args: percentile: A float value from 0 to 100 representing the requested percentile. Return: The Data Collection value at the input percentile """ assert 0 <= percentile <= 100, \ 'percentile must be between 0 and 100. Got {}'.format(percentile) return self._percentile(self._values, percentile)
[ "def", "get_percentile", "(", "self", ",", "percentile", ")", ":", "assert", "0", "<=", "percentile", "<=", "100", ",", "'percentile must be between 0 and 100. Got {}'", ".", "format", "(", "percentile", ")", "return", "self", ".", "_percentile", "(", "self", ".", "_values", ",", "percentile", ")" ]
Get a value representing a the input percentile of the Data Collection. Args: percentile: A float value from 0 to 100 representing the requested percentile. Return: The Data Collection value at the input percentile
[ "Get", "a", "value", "representing", "a", "the", "input", "percentile", "of", "the", "Data", "Collection", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L235-L247
train
237,568
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.get_aligned_collection
def get_aligned_collection(self, value=0, data_type=None, unit=None, mutable=None): """Return a Collection aligned with this one composed of one repeated value. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: value: A value to be repeated in the aliged collection values or A list of values that has the same length as this collection. Default: 0. data_type: The data type of the aligned collection. Default is to use the data type of this collection. unit: The unit of the aligned collection. Default is to use the unit of this collection or the base unit of the input data_type (if it exists). mutable: An optional Boolean to set whether the returned aligned collection is mutable (True) or immutable (False). The default is None, which will simply set the aligned collection to have the same mutability as the starting collection. """ # set up the header of the new collection header = self._check_aligned_header(data_type, unit) # set up the values of the new collection values = self._check_aligned_value(value) # get the correct base class for the aligned collection (mutable or immutable) if mutable is None: collection = self.__class__(header, values, self.datetimes) else: if self._enumeration is None: self._get_mutable_enumeration() if mutable is False: col_obj = self._enumeration['immutable'][self._collection_type] else: col_obj = self._enumeration['mutable'][self._collection_type] collection = col_obj(header, values, self.datetimes) collection._validated_a_period = self._validated_a_period return collection
python
def get_aligned_collection(self, value=0, data_type=None, unit=None, mutable=None): """Return a Collection aligned with this one composed of one repeated value. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: value: A value to be repeated in the aliged collection values or A list of values that has the same length as this collection. Default: 0. data_type: The data type of the aligned collection. Default is to use the data type of this collection. unit: The unit of the aligned collection. Default is to use the unit of this collection or the base unit of the input data_type (if it exists). mutable: An optional Boolean to set whether the returned aligned collection is mutable (True) or immutable (False). The default is None, which will simply set the aligned collection to have the same mutability as the starting collection. """ # set up the header of the new collection header = self._check_aligned_header(data_type, unit) # set up the values of the new collection values = self._check_aligned_value(value) # get the correct base class for the aligned collection (mutable or immutable) if mutable is None: collection = self.__class__(header, values, self.datetimes) else: if self._enumeration is None: self._get_mutable_enumeration() if mutable is False: col_obj = self._enumeration['immutable'][self._collection_type] else: col_obj = self._enumeration['mutable'][self._collection_type] collection = col_obj(header, values, self.datetimes) collection._validated_a_period = self._validated_a_period return collection
[ "def", "get_aligned_collection", "(", "self", ",", "value", "=", "0", ",", "data_type", "=", "None", ",", "unit", "=", "None", ",", "mutable", "=", "None", ")", ":", "# set up the header of the new collection", "header", "=", "self", ".", "_check_aligned_header", "(", "data_type", ",", "unit", ")", "# set up the values of the new collection", "values", "=", "self", ".", "_check_aligned_value", "(", "value", ")", "# get the correct base class for the aligned collection (mutable or immutable)", "if", "mutable", "is", "None", ":", "collection", "=", "self", ".", "__class__", "(", "header", ",", "values", ",", "self", ".", "datetimes", ")", "else", ":", "if", "self", ".", "_enumeration", "is", "None", ":", "self", ".", "_get_mutable_enumeration", "(", ")", "if", "mutable", "is", "False", ":", "col_obj", "=", "self", ".", "_enumeration", "[", "'immutable'", "]", "[", "self", ".", "_collection_type", "]", "else", ":", "col_obj", "=", "self", ".", "_enumeration", "[", "'mutable'", "]", "[", "self", ".", "_collection_type", "]", "collection", "=", "col_obj", "(", "header", ",", "values", ",", "self", ".", "datetimes", ")", "collection", ".", "_validated_a_period", "=", "self", ".", "_validated_a_period", "return", "collection" ]
Return a Collection aligned with this one composed of one repeated value. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: value: A value to be repeated in the aliged collection values or A list of values that has the same length as this collection. Default: 0. data_type: The data type of the aligned collection. Default is to use the data type of this collection. unit: The unit of the aligned collection. Default is to use the unit of this collection or the base unit of the input data_type (if it exists). mutable: An optional Boolean to set whether the returned aligned collection is mutable (True) or immutable (False). The default is None, which will simply set the aligned collection to have the same mutability as the starting collection.
[ "Return", "a", "Collection", "aligned", "with", "this", "one", "composed", "of", "one", "repeated", "value", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L308-L346
train
237,569
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.duplicate
def duplicate(self): """Return a copy of the current Data Collection.""" collection = self.__class__(self.header.duplicate(), self.values, self.datetimes) collection._validated_a_period = self._validated_a_period return collection
python
def duplicate(self): """Return a copy of the current Data Collection.""" collection = self.__class__(self.header.duplicate(), self.values, self.datetimes) collection._validated_a_period = self._validated_a_period return collection
[ "def", "duplicate", "(", "self", ")", ":", "collection", "=", "self", ".", "__class__", "(", "self", ".", "header", ".", "duplicate", "(", ")", ",", "self", ".", "values", ",", "self", ".", "datetimes", ")", "collection", ".", "_validated_a_period", "=", "self", ".", "_validated_a_period", "return", "collection" ]
Return a copy of the current Data Collection.
[ "Return", "a", "copy", "of", "the", "current", "Data", "Collection", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L348-L352
train
237,570
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.to_json
def to_json(self): """Convert Data Collection to a dictionary.""" return { 'header': self.header.to_json(), 'values': self._values, 'datetimes': self.datetimes, 'validated_a_period': self._validated_a_period }
python
def to_json(self): """Convert Data Collection to a dictionary.""" return { 'header': self.header.to_json(), 'values': self._values, 'datetimes': self.datetimes, 'validated_a_period': self._validated_a_period }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'header'", ":", "self", ".", "header", ".", "to_json", "(", ")", ",", "'values'", ":", "self", ".", "_values", ",", "'datetimes'", ":", "self", ".", "datetimes", ",", "'validated_a_period'", ":", "self", ".", "_validated_a_period", "}" ]
Convert Data Collection to a dictionary.
[ "Convert", "Data", "Collection", "to", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L354-L361
train
237,571
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.filter_collections_by_statement
def filter_collections_by_statement(data_collections, statement): """Generate a filtered data collections according to a conditional statement. Args: data_collections: A list of aligned Data Collections to be evaluated against the statement. statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). Return: collections: A list of Data Collections that have been filtered based on the statement. """ pattern = BaseCollection.pattern_from_collections_and_statement( data_collections, statement) collections = [coll.filter_by_pattern(pattern) for coll in data_collections] return collections
python
def filter_collections_by_statement(data_collections, statement): """Generate a filtered data collections according to a conditional statement. Args: data_collections: A list of aligned Data Collections to be evaluated against the statement. statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). Return: collections: A list of Data Collections that have been filtered based on the statement. """ pattern = BaseCollection.pattern_from_collections_and_statement( data_collections, statement) collections = [coll.filter_by_pattern(pattern) for coll in data_collections] return collections
[ "def", "filter_collections_by_statement", "(", "data_collections", ",", "statement", ")", ":", "pattern", "=", "BaseCollection", ".", "pattern_from_collections_and_statement", "(", "data_collections", ",", "statement", ")", "collections", "=", "[", "coll", ".", "filter_by_pattern", "(", "pattern", ")", "for", "coll", "in", "data_collections", "]", "return", "collections" ]
Generate a filtered data collections according to a conditional statement. Args: data_collections: A list of aligned Data Collections to be evaluated against the statement. statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). Return: collections: A list of Data Collections that have been filtered based on the statement.
[ "Generate", "a", "filtered", "data", "collections", "according", "to", "a", "conditional", "statement", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L364-L380
train
237,572
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.pattern_from_collections_and_statement
def pattern_from_collections_and_statement(data_collections, statement): """Generate a list of booleans from data collections and a conditional statement. Args: data_collections: A list of aligned Data Collections to be evaluated against the statement. statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). Return: pattern: A list of True/False booleans with the length of the Data Collections where True meets the conditional statement and False does not. """ BaseCollection.are_collections_aligned(data_collections) correct_var = BaseCollection._check_conditional_statement( statement, len(data_collections)) # replace the operators of the statement with non-alphanumeric characters # necessary to avoid replacing the characters of the operators num_statement_clean = BaseCollection._replace_operators(statement) pattern = [] for i in xrange(len(data_collections[0])): num_statement = num_statement_clean # replace the variable names with their numerical values for j, coll in enumerate(data_collections): var = correct_var[j] num_statement = num_statement.replace(var, str(coll[i])) # put back the operators num_statement = BaseCollection._restore_operators(num_statement) pattern.append(eval(num_statement, {})) return pattern
python
def pattern_from_collections_and_statement(data_collections, statement): """Generate a list of booleans from data collections and a conditional statement. Args: data_collections: A list of aligned Data Collections to be evaluated against the statement. statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). Return: pattern: A list of True/False booleans with the length of the Data Collections where True meets the conditional statement and False does not. """ BaseCollection.are_collections_aligned(data_collections) correct_var = BaseCollection._check_conditional_statement( statement, len(data_collections)) # replace the operators of the statement with non-alphanumeric characters # necessary to avoid replacing the characters of the operators num_statement_clean = BaseCollection._replace_operators(statement) pattern = [] for i in xrange(len(data_collections[0])): num_statement = num_statement_clean # replace the variable names with their numerical values for j, coll in enumerate(data_collections): var = correct_var[j] num_statement = num_statement.replace(var, str(coll[i])) # put back the operators num_statement = BaseCollection._restore_operators(num_statement) pattern.append(eval(num_statement, {})) return pattern
[ "def", "pattern_from_collections_and_statement", "(", "data_collections", ",", "statement", ")", ":", "BaseCollection", ".", "are_collections_aligned", "(", "data_collections", ")", "correct_var", "=", "BaseCollection", ".", "_check_conditional_statement", "(", "statement", ",", "len", "(", "data_collections", ")", ")", "# replace the operators of the statement with non-alphanumeric characters", "# necessary to avoid replacing the characters of the operators", "num_statement_clean", "=", "BaseCollection", ".", "_replace_operators", "(", "statement", ")", "pattern", "=", "[", "]", "for", "i", "in", "xrange", "(", "len", "(", "data_collections", "[", "0", "]", ")", ")", ":", "num_statement", "=", "num_statement_clean", "# replace the variable names with their numerical values", "for", "j", ",", "coll", "in", "enumerate", "(", "data_collections", ")", ":", "var", "=", "correct_var", "[", "j", "]", "num_statement", "=", "num_statement", ".", "replace", "(", "var", ",", "str", "(", "coll", "[", "i", "]", ")", ")", "# put back the operators", "num_statement", "=", "BaseCollection", ".", "_restore_operators", "(", "num_statement", ")", "pattern", ".", "append", "(", "eval", "(", "num_statement", ",", "{", "}", ")", ")", "return", "pattern" ]
Generate a list of booleans from data collections and a conditional statement. Args: data_collections: A list of aligned Data Collections to be evaluated against the statement. statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). Return: pattern: A list of True/False booleans with the length of the Data Collections where True meets the conditional statement and False does not.
[ "Generate", "a", "list", "of", "booleans", "from", "data", "collections", "and", "a", "conditional", "statement", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L383-L415
train
237,573
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.are_collections_aligned
def are_collections_aligned(data_collections, raise_exception=True): """Test if a series of Data Collections are aligned with one another. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: data_collections: A list of Data Collections for which you want to test if they are al aligned with one another. Return: True if collections are aligned, False if not aligned """ if len(data_collections) > 1: first_coll = data_collections[0] for coll in data_collections[1:]: if not first_coll.is_collection_aligned(coll): if raise_exception is True: error_msg = '{} Data Collection is not aligned with '\ '{} Data Collection.'.format( first_coll.header.data_type, coll.header.data_type) raise ValueError(error_msg) return False return True
python
def are_collections_aligned(data_collections, raise_exception=True): """Test if a series of Data Collections are aligned with one another. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: data_collections: A list of Data Collections for which you want to test if they are al aligned with one another. Return: True if collections are aligned, False if not aligned """ if len(data_collections) > 1: first_coll = data_collections[0] for coll in data_collections[1:]: if not first_coll.is_collection_aligned(coll): if raise_exception is True: error_msg = '{} Data Collection is not aligned with '\ '{} Data Collection.'.format( first_coll.header.data_type, coll.header.data_type) raise ValueError(error_msg) return False return True
[ "def", "are_collections_aligned", "(", "data_collections", ",", "raise_exception", "=", "True", ")", ":", "if", "len", "(", "data_collections", ")", ">", "1", ":", "first_coll", "=", "data_collections", "[", "0", "]", "for", "coll", "in", "data_collections", "[", "1", ":", "]", ":", "if", "not", "first_coll", ".", "is_collection_aligned", "(", "coll", ")", ":", "if", "raise_exception", "is", "True", ":", "error_msg", "=", "'{} Data Collection is not aligned with '", "'{} Data Collection.'", ".", "format", "(", "first_coll", ".", "header", ".", "data_type", ",", "coll", ".", "header", ".", "data_type", ")", "raise", "ValueError", "(", "error_msg", ")", "return", "False", "return", "True" ]
Test if a series of Data Collections are aligned with one another. Aligned Data Collections are of the same Data Collection class, have the same number of values and have matching datetimes. Args: data_collections: A list of Data Collections for which you want to test if they are al aligned with one another. Return: True if collections are aligned, False if not aligned
[ "Test", "if", "a", "series", "of", "Data", "Collections", "are", "aligned", "with", "one", "another", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L418-L441
train
237,574
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection.compute_function_aligned
def compute_function_aligned(funct, data_collections, data_type, unit): """Compute a function with a list of aligned data collections or individual values. Args: funct: A function with a single numerical value as output and one or more numerical values as input. data_collections: A list with a length equal to the number of arguments for the function. Items of the list can be either Data Collections or individual values to be used at each datetime of other collections. data_type: An instance of a Ladybug data type that describes the results of the funct. unit: The units of the funct results. Return: A Data Collection with the results function. If all items in this list of data_collections are individual values, only a single value will be returned. Usage: from ladybug.datacollection import HourlyContinuousCollection from ladybug.epw import EPW from ladybug.psychrometrics import humid_ratio_from_db_rh from ladybug.datatype.percentage import HumidityRatio epw_file_path = './epws/denver.epw' denver_epw = EPW(epw_file_path) pressure_at_denver = 85000 hr_inputs = [denver_epw.dry_bulb_temperature, denver_epw.relative_humidity, pressure_at_denver] humid_ratio = HourlyContinuousCollection.compute_function_aligned( humid_ratio_from_db_rh, hr_inputs, HumidityRatio(), 'fraction') # humid_ratio will be a Data Colleciton of humidity ratios at Denver """ # check that all inputs are either data collections or floats data_colls = [] for i, func_input in enumerate(data_collections): if isinstance(func_input, BaseCollection): data_colls.append(func_input) else: try: data_collections[i] = float(func_input) except ValueError: raise TypeError('Expected a number or a Data Colleciton. ' 'Got {}'.format(type(func_input))) # run the function and return the result if len(data_colls) == 0: return funct(*data_collections) else: BaseCollection.are_collections_aligned(data_colls) val_len = len(data_colls[0].values) for i, col in enumerate(data_collections): data_collections[i] = [col] * val_len if isinstance(col, float) else col result = data_colls[0].get_aligned_collection(data_type=data_type, unit=unit) for i in xrange(val_len): result[i] = funct(*[col[i] for col in data_collections]) return result
python
def compute_function_aligned(funct, data_collections, data_type, unit): """Compute a function with a list of aligned data collections or individual values. Args: funct: A function with a single numerical value as output and one or more numerical values as input. data_collections: A list with a length equal to the number of arguments for the function. Items of the list can be either Data Collections or individual values to be used at each datetime of other collections. data_type: An instance of a Ladybug data type that describes the results of the funct. unit: The units of the funct results. Return: A Data Collection with the results function. If all items in this list of data_collections are individual values, only a single value will be returned. Usage: from ladybug.datacollection import HourlyContinuousCollection from ladybug.epw import EPW from ladybug.psychrometrics import humid_ratio_from_db_rh from ladybug.datatype.percentage import HumidityRatio epw_file_path = './epws/denver.epw' denver_epw = EPW(epw_file_path) pressure_at_denver = 85000 hr_inputs = [denver_epw.dry_bulb_temperature, denver_epw.relative_humidity, pressure_at_denver] humid_ratio = HourlyContinuousCollection.compute_function_aligned( humid_ratio_from_db_rh, hr_inputs, HumidityRatio(), 'fraction') # humid_ratio will be a Data Colleciton of humidity ratios at Denver """ # check that all inputs are either data collections or floats data_colls = [] for i, func_input in enumerate(data_collections): if isinstance(func_input, BaseCollection): data_colls.append(func_input) else: try: data_collections[i] = float(func_input) except ValueError: raise TypeError('Expected a number or a Data Colleciton. ' 'Got {}'.format(type(func_input))) # run the function and return the result if len(data_colls) == 0: return funct(*data_collections) else: BaseCollection.are_collections_aligned(data_colls) val_len = len(data_colls[0].values) for i, col in enumerate(data_collections): data_collections[i] = [col] * val_len if isinstance(col, float) else col result = data_colls[0].get_aligned_collection(data_type=data_type, unit=unit) for i in xrange(val_len): result[i] = funct(*[col[i] for col in data_collections]) return result
[ "def", "compute_function_aligned", "(", "funct", ",", "data_collections", ",", "data_type", ",", "unit", ")", ":", "# check that all inputs are either data collections or floats", "data_colls", "=", "[", "]", "for", "i", ",", "func_input", "in", "enumerate", "(", "data_collections", ")", ":", "if", "isinstance", "(", "func_input", ",", "BaseCollection", ")", ":", "data_colls", ".", "append", "(", "func_input", ")", "else", ":", "try", ":", "data_collections", "[", "i", "]", "=", "float", "(", "func_input", ")", "except", "ValueError", ":", "raise", "TypeError", "(", "'Expected a number or a Data Colleciton. '", "'Got {}'", ".", "format", "(", "type", "(", "func_input", ")", ")", ")", "# run the function and return the result", "if", "len", "(", "data_colls", ")", "==", "0", ":", "return", "funct", "(", "*", "data_collections", ")", "else", ":", "BaseCollection", ".", "are_collections_aligned", "(", "data_colls", ")", "val_len", "=", "len", "(", "data_colls", "[", "0", "]", ".", "values", ")", "for", "i", ",", "col", "in", "enumerate", "(", "data_collections", ")", ":", "data_collections", "[", "i", "]", "=", "[", "col", "]", "*", "val_len", "if", "isinstance", "(", "col", ",", "float", ")", "else", "col", "result", "=", "data_colls", "[", "0", "]", ".", "get_aligned_collection", "(", "data_type", "=", "data_type", ",", "unit", "=", "unit", ")", "for", "i", "in", "xrange", "(", "val_len", ")", ":", "result", "[", "i", "]", "=", "funct", "(", "*", "[", "col", "[", "i", "]", "for", "col", "in", "data_collections", "]", ")", "return", "result" ]
Compute a function with a list of aligned data collections or individual values. Args: funct: A function with a single numerical value as output and one or more numerical values as input. data_collections: A list with a length equal to the number of arguments for the function. Items of the list can be either Data Collections or individual values to be used at each datetime of other collections. data_type: An instance of a Ladybug data type that describes the results of the funct. unit: The units of the funct results. Return: A Data Collection with the results function. If all items in this list of data_collections are individual values, only a single value will be returned. Usage: from ladybug.datacollection import HourlyContinuousCollection from ladybug.epw import EPW from ladybug.psychrometrics import humid_ratio_from_db_rh from ladybug.datatype.percentage import HumidityRatio epw_file_path = './epws/denver.epw' denver_epw = EPW(epw_file_path) pressure_at_denver = 85000 hr_inputs = [denver_epw.dry_bulb_temperature, denver_epw.relative_humidity, pressure_at_denver] humid_ratio = HourlyContinuousCollection.compute_function_aligned( humid_ratio_from_db_rh, hr_inputs, HumidityRatio(), 'fraction') # humid_ratio will be a Data Colleciton of humidity ratios at Denver
[ "Compute", "a", "function", "with", "a", "list", "of", "aligned", "data", "collections", "or", "individual", "values", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L444-L500
train
237,575
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection._check_conditional_statement
def _check_conditional_statement(statement, num_collections): """Method to check conditional statements to be sure that they are valid. Args: statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). num_collections: An integer representing the number of data collections that the statement will be evaluating. Return: correct_var: A list of the correct variable names that should be used within the statement (eg. ['a', 'b', 'c']) """ # Determine what the list of variables should be based on the num_collections correct_var = list(ascii_lowercase)[:num_collections] # Clean out the operators of the statement st_statement = BaseCollection._remove_operators(statement) parsed_st = [s for s in st_statement if s.isalpha()] # Perform the check for var in parsed_st: if var not in correct_var: raise ValueError( 'Invalid conditional statement: {}\n ' 'Statement should be a valid Python statement' ' and the variables should be named as follows: {}'.format( statement, ', '.join(correct_var)) ) return correct_var
python
def _check_conditional_statement(statement, num_collections): """Method to check conditional statements to be sure that they are valid. Args: statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). num_collections: An integer representing the number of data collections that the statement will be evaluating. Return: correct_var: A list of the correct variable names that should be used within the statement (eg. ['a', 'b', 'c']) """ # Determine what the list of variables should be based on the num_collections correct_var = list(ascii_lowercase)[:num_collections] # Clean out the operators of the statement st_statement = BaseCollection._remove_operators(statement) parsed_st = [s for s in st_statement if s.isalpha()] # Perform the check for var in parsed_st: if var not in correct_var: raise ValueError( 'Invalid conditional statement: {}\n ' 'Statement should be a valid Python statement' ' and the variables should be named as follows: {}'.format( statement, ', '.join(correct_var)) ) return correct_var
[ "def", "_check_conditional_statement", "(", "statement", ",", "num_collections", ")", ":", "# Determine what the list of variables should be based on the num_collections", "correct_var", "=", "list", "(", "ascii_lowercase", ")", "[", ":", "num_collections", "]", "# Clean out the operators of the statement", "st_statement", "=", "BaseCollection", ".", "_remove_operators", "(", "statement", ")", "parsed_st", "=", "[", "s", "for", "s", "in", "st_statement", "if", "s", ".", "isalpha", "(", ")", "]", "# Perform the check", "for", "var", "in", "parsed_st", ":", "if", "var", "not", "in", "correct_var", ":", "raise", "ValueError", "(", "'Invalid conditional statement: {}\\n '", "'Statement should be a valid Python statement'", "' and the variables should be named as follows: {}'", ".", "format", "(", "statement", ",", "', '", ".", "join", "(", "correct_var", ")", ")", ")", "return", "correct_var" ]
Method to check conditional statements to be sure that they are valid. Args: statement: A conditional statement as a string (e.g. a>25 and a%5==0). The variable should always be named as 'a' (without quotations). num_collections: An integer representing the number of data collections that the statement will be evaluating. Return: correct_var: A list of the correct variable names that should be used within the statement (eg. ['a', 'b', 'c'])
[ "Method", "to", "check", "conditional", "statements", "to", "be", "sure", "that", "they", "are", "valid", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L503-L532
train
237,576
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection._filter_by_statement
def _filter_by_statement(self, statement): """Filter the data collection based on a conditional statement.""" self.__class__._check_conditional_statement(statement, 1) _filt_values, _filt_datetimes = [], [] for i, a in enumerate(self._values): if eval(statement, {'a': a}): _filt_values.append(a) _filt_datetimes.append(self.datetimes[i]) return _filt_values, _filt_datetimes
python
def _filter_by_statement(self, statement): """Filter the data collection based on a conditional statement.""" self.__class__._check_conditional_statement(statement, 1) _filt_values, _filt_datetimes = [], [] for i, a in enumerate(self._values): if eval(statement, {'a': a}): _filt_values.append(a) _filt_datetimes.append(self.datetimes[i]) return _filt_values, _filt_datetimes
[ "def", "_filter_by_statement", "(", "self", ",", "statement", ")", ":", "self", ".", "__class__", ".", "_check_conditional_statement", "(", "statement", ",", "1", ")", "_filt_values", ",", "_filt_datetimes", "=", "[", "]", ",", "[", "]", "for", "i", ",", "a", "in", "enumerate", "(", "self", ".", "_values", ")", ":", "if", "eval", "(", "statement", ",", "{", "'a'", ":", "a", "}", ")", ":", "_filt_values", ".", "append", "(", "a", ")", "_filt_datetimes", ".", "append", "(", "self", ".", "datetimes", "[", "i", "]", ")", "return", "_filt_values", ",", "_filt_datetimes" ]
Filter the data collection based on a conditional statement.
[ "Filter", "the", "data", "collection", "based", "on", "a", "conditional", "statement", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L552-L560
train
237,577
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection._filter_by_pattern
def _filter_by_pattern(self, pattern): """Filter the Filter the Data Collection based on a list of booleans.""" try: _len = len(pattern) except TypeError: raise TypeError("pattern is not a list of Booleans. Got {}".format( type(pattern))) _filt_values = [d for i, d in enumerate(self._values) if pattern[i % _len]] _filt_datetimes = [d for i, d in enumerate(self.datetimes) if pattern[i % _len]] return _filt_values, _filt_datetimes
python
def _filter_by_pattern(self, pattern): """Filter the Filter the Data Collection based on a list of booleans.""" try: _len = len(pattern) except TypeError: raise TypeError("pattern is not a list of Booleans. Got {}".format( type(pattern))) _filt_values = [d for i, d in enumerate(self._values) if pattern[i % _len]] _filt_datetimes = [d for i, d in enumerate(self.datetimes) if pattern[i % _len]] return _filt_values, _filt_datetimes
[ "def", "_filter_by_pattern", "(", "self", ",", "pattern", ")", ":", "try", ":", "_len", "=", "len", "(", "pattern", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "\"pattern is not a list of Booleans. Got {}\"", ".", "format", "(", "type", "(", "pattern", ")", ")", ")", "_filt_values", "=", "[", "d", "for", "i", ",", "d", "in", "enumerate", "(", "self", ".", "_values", ")", "if", "pattern", "[", "i", "%", "_len", "]", "]", "_filt_datetimes", "=", "[", "d", "for", "i", ",", "d", "in", "enumerate", "(", "self", ".", "datetimes", ")", "if", "pattern", "[", "i", "%", "_len", "]", "]", "return", "_filt_values", ",", "_filt_datetimes" ]
Filter the Filter the Data Collection based on a list of booleans.
[ "Filter", "the", "Filter", "the", "Data", "Collection", "based", "on", "a", "list", "of", "booleans", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L562-L571
train
237,578
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection._check_aligned_header
def _check_aligned_header(self, data_type, unit): """Check the header inputs whenever get_aligned_collection is called.""" if data_type is not None: assert isinstance(data_type, DataTypeBase), \ 'data_type must be a Ladybug DataType. Got {}'.format(type(data_type)) if unit is None: unit = data_type.units[0] else: data_type = self.header.data_type unit = unit or self.header.unit return Header(data_type, unit, self.header.analysis_period, self.header.metadata)
python
def _check_aligned_header(self, data_type, unit): """Check the header inputs whenever get_aligned_collection is called.""" if data_type is not None: assert isinstance(data_type, DataTypeBase), \ 'data_type must be a Ladybug DataType. Got {}'.format(type(data_type)) if unit is None: unit = data_type.units[0] else: data_type = self.header.data_type unit = unit or self.header.unit return Header(data_type, unit, self.header.analysis_period, self.header.metadata)
[ "def", "_check_aligned_header", "(", "self", ",", "data_type", ",", "unit", ")", ":", "if", "data_type", "is", "not", "None", ":", "assert", "isinstance", "(", "data_type", ",", "DataTypeBase", ")", ",", "'data_type must be a Ladybug DataType. Got {}'", ".", "format", "(", "type", "(", "data_type", ")", ")", "if", "unit", "is", "None", ":", "unit", "=", "data_type", ".", "units", "[", "0", "]", "else", ":", "data_type", "=", "self", ".", "header", ".", "data_type", "unit", "=", "unit", "or", "self", ".", "header", ".", "unit", "return", "Header", "(", "data_type", ",", "unit", ",", "self", ".", "header", ".", "analysis_period", ",", "self", ".", "header", ".", "metadata", ")" ]
Check the header inputs whenever get_aligned_collection is called.
[ "Check", "the", "header", "inputs", "whenever", "get_aligned_collection", "is", "called", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L583-L593
train
237,579
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
BaseCollection._check_aligned_value
def _check_aligned_value(self, value): """Check the value input whenever get_aligned_collection is called.""" if isinstance(value, Iterable) and not isinstance( value, (str, dict, bytes, bytearray)): assert len(value) == len(self._values), "Length of value ({}) must match "\ "the length of this collection's values ({})".format( len(value), len(self._values)) values = value else: values = [value] * len(self._values) return values
python
def _check_aligned_value(self, value): """Check the value input whenever get_aligned_collection is called.""" if isinstance(value, Iterable) and not isinstance( value, (str, dict, bytes, bytearray)): assert len(value) == len(self._values), "Length of value ({}) must match "\ "the length of this collection's values ({})".format( len(value), len(self._values)) values = value else: values = [value] * len(self._values) return values
[ "def", "_check_aligned_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Iterable", ")", "and", "not", "isinstance", "(", "value", ",", "(", "str", ",", "dict", ",", "bytes", ",", "bytearray", ")", ")", ":", "assert", "len", "(", "value", ")", "==", "len", "(", "self", ".", "_values", ")", ",", "\"Length of value ({}) must match \"", "\"the length of this collection's values ({})\"", ".", "format", "(", "len", "(", "value", ")", ",", "len", "(", "self", ".", "_values", ")", ")", "values", "=", "value", "else", ":", "values", "=", "[", "value", "]", "*", "len", "(", "self", ".", "_values", ")", "return", "values" ]
Check the value input whenever get_aligned_collection is called.
[ "Check", "the", "value", "input", "whenever", "get_aligned_collection", "is", "called", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L595-L605
train
237,580
ladybug-tools/ladybug
ladybug/dt.py
DateTime.from_json
def from_json(cls, data): """Creat datetime from a dictionary. Args: data: { 'month': A value for month between 1-12. (Defualt: 1) 'day': A value for day between 1-31. (Defualt: 1) 'hour': A value for hour between 0-23. (Defualt: 0) 'minute': A value for month between 0-59. (Defualt: 0) } """ if 'month' not in data: data['month'] = 1 if 'day' not in data: data['day'] = 1 if 'hour' not in data: data['hour'] = 0 if 'minute' not in data: data['minute'] = 0 if 'year' not in data: data['year'] = 2017 leap_year = True if int(data['year']) == 2016 else False return cls(data['month'], data['day'], data['hour'], data['minute'], leap_year)
python
def from_json(cls, data): """Creat datetime from a dictionary. Args: data: { 'month': A value for month between 1-12. (Defualt: 1) 'day': A value for day between 1-31. (Defualt: 1) 'hour': A value for hour between 0-23. (Defualt: 0) 'minute': A value for month between 0-59. (Defualt: 0) } """ if 'month' not in data: data['month'] = 1 if 'day' not in data: data['day'] = 1 if 'hour' not in data: data['hour'] = 0 if 'minute' not in data: data['minute'] = 0 if 'year' not in data: data['year'] = 2017 leap_year = True if int(data['year']) == 2016 else False return cls(data['month'], data['day'], data['hour'], data['minute'], leap_year)
[ "def", "from_json", "(", "cls", ",", "data", ")", ":", "if", "'month'", "not", "in", "data", ":", "data", "[", "'month'", "]", "=", "1", "if", "'day'", "not", "in", "data", ":", "data", "[", "'day'", "]", "=", "1", "if", "'hour'", "not", "in", "data", ":", "data", "[", "'hour'", "]", "=", "0", "if", "'minute'", "not", "in", "data", ":", "data", "[", "'minute'", "]", "=", "0", "if", "'year'", "not", "in", "data", ":", "data", "[", "'year'", "]", "=", "2017", "leap_year", "=", "True", "if", "int", "(", "data", "[", "'year'", "]", ")", "==", "2016", "else", "False", "return", "cls", "(", "data", "[", "'month'", "]", ",", "data", "[", "'day'", "]", ",", "data", "[", "'hour'", "]", ",", "data", "[", "'minute'", "]", ",", "leap_year", ")" ]
Creat datetime from a dictionary. Args: data: { 'month': A value for month between 1-12. (Defualt: 1) 'day': A value for day between 1-31. (Defualt: 1) 'hour': A value for hour between 0-23. (Defualt: 0) 'minute': A value for month between 0-59. (Defualt: 0) }
[ "Creat", "datetime", "from", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L43-L70
train
237,581
ladybug-tools/ladybug
ladybug/dt.py
DateTime.from_hoy
def from_hoy(cls, hoy, leap_year=False): """Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760 """ return cls.from_moy(round(hoy * 60), leap_year)
python
def from_hoy(cls, hoy, leap_year=False): """Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760 """ return cls.from_moy(round(hoy * 60), leap_year)
[ "def", "from_hoy", "(", "cls", ",", "hoy", ",", "leap_year", "=", "False", ")", ":", "return", "cls", ".", "from_moy", "(", "round", "(", "hoy", "*", "60", ")", ",", "leap_year", ")" ]
Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760
[ "Create", "Ladybug", "Datetime", "from", "an", "hour", "of", "the", "year", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L73-L79
train
237,582
ladybug-tools/ladybug
ladybug/dt.py
DateTime.from_moy
def from_moy(cls, moy, leap_year=False): """Create Ladybug Datetime from a minute of the year. Args: moy: An integer value 0 <= and < 525600 """ if not leap_year: num_of_minutes_until_month = (0, 44640, 84960, 129600, 172800, 217440, 260640, 305280, 349920, 393120, 437760, 480960, 525600) else: num_of_minutes_until_month = (0, 44640, 84960 + 1440, 129600 + 1440, 172800 + 1440, 217440 + 1440, 260640 + 1440, 305280 + 1440, 349920 + 1440, 393120 + 1440, 437760 + 1440, 480960 + 1440, 525600 + 1440) # find month for monthCount in range(12): if int(moy) < num_of_minutes_until_month[monthCount + 1]: month = monthCount + 1 break try: day = int((moy - num_of_minutes_until_month[month - 1]) / (60 * 24)) + 1 except UnboundLocalError: raise ValueError( "moy must be positive and smaller than 525600. Invalid input %d" % (moy) ) else: hour = int((moy / 60) % 24) minute = int(moy % 60) return cls(month, day, hour, minute, leap_year)
python
def from_moy(cls, moy, leap_year=False): """Create Ladybug Datetime from a minute of the year. Args: moy: An integer value 0 <= and < 525600 """ if not leap_year: num_of_minutes_until_month = (0, 44640, 84960, 129600, 172800, 217440, 260640, 305280, 349920, 393120, 437760, 480960, 525600) else: num_of_minutes_until_month = (0, 44640, 84960 + 1440, 129600 + 1440, 172800 + 1440, 217440 + 1440, 260640 + 1440, 305280 + 1440, 349920 + 1440, 393120 + 1440, 437760 + 1440, 480960 + 1440, 525600 + 1440) # find month for monthCount in range(12): if int(moy) < num_of_minutes_until_month[monthCount + 1]: month = monthCount + 1 break try: day = int((moy - num_of_minutes_until_month[month - 1]) / (60 * 24)) + 1 except UnboundLocalError: raise ValueError( "moy must be positive and smaller than 525600. Invalid input %d" % (moy) ) else: hour = int((moy / 60) % 24) minute = int(moy % 60) return cls(month, day, hour, minute, leap_year)
[ "def", "from_moy", "(", "cls", ",", "moy", ",", "leap_year", "=", "False", ")", ":", "if", "not", "leap_year", ":", "num_of_minutes_until_month", "=", "(", "0", ",", "44640", ",", "84960", ",", "129600", ",", "172800", ",", "217440", ",", "260640", ",", "305280", ",", "349920", ",", "393120", ",", "437760", ",", "480960", ",", "525600", ")", "else", ":", "num_of_minutes_until_month", "=", "(", "0", ",", "44640", ",", "84960", "+", "1440", ",", "129600", "+", "1440", ",", "172800", "+", "1440", ",", "217440", "+", "1440", ",", "260640", "+", "1440", ",", "305280", "+", "1440", ",", "349920", "+", "1440", ",", "393120", "+", "1440", ",", "437760", "+", "1440", ",", "480960", "+", "1440", ",", "525600", "+", "1440", ")", "# find month", "for", "monthCount", "in", "range", "(", "12", ")", ":", "if", "int", "(", "moy", ")", "<", "num_of_minutes_until_month", "[", "monthCount", "+", "1", "]", ":", "month", "=", "monthCount", "+", "1", "break", "try", ":", "day", "=", "int", "(", "(", "moy", "-", "num_of_minutes_until_month", "[", "month", "-", "1", "]", ")", "/", "(", "60", "*", "24", ")", ")", "+", "1", "except", "UnboundLocalError", ":", "raise", "ValueError", "(", "\"moy must be positive and smaller than 525600. Invalid input %d\"", "%", "(", "moy", ")", ")", "else", ":", "hour", "=", "int", "(", "(", "moy", "/", "60", ")", "%", "24", ")", "minute", "=", "int", "(", "moy", "%", "60", ")", "return", "cls", "(", "month", ",", "day", ",", "hour", ",", "minute", ",", "leap_year", ")" ]
Create Ladybug Datetime from a minute of the year. Args: moy: An integer value 0 <= and < 525600
[ "Create", "Ladybug", "Datetime", "from", "a", "minute", "of", "the", "year", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L82-L112
train
237,583
ladybug-tools/ladybug
ladybug/dt.py
DateTime.from_date_time_string
def from_date_time_string(cls, datetime_string, leap_year=False): """Create Ladybug DateTime from a DateTime string. Usage: dt = DateTime.from_date_time_string("31 Dec 12:00") """ dt = datetime.strptime(datetime_string, '%d %b %H:%M') return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year)
python
def from_date_time_string(cls, datetime_string, leap_year=False): """Create Ladybug DateTime from a DateTime string. Usage: dt = DateTime.from_date_time_string("31 Dec 12:00") """ dt = datetime.strptime(datetime_string, '%d %b %H:%M') return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year)
[ "def", "from_date_time_string", "(", "cls", ",", "datetime_string", ",", "leap_year", "=", "False", ")", ":", "dt", "=", "datetime", ".", "strptime", "(", "datetime_string", ",", "'%d %b %H:%M'", ")", "return", "cls", "(", "dt", ".", "month", ",", "dt", ".", "day", ",", "dt", ".", "hour", ",", "dt", ".", "minute", ",", "leap_year", ")" ]
Create Ladybug DateTime from a DateTime string. Usage: dt = DateTime.from_date_time_string("31 Dec 12:00")
[ "Create", "Ladybug", "DateTime", "from", "a", "DateTime", "string", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L115-L123
train
237,584
ladybug-tools/ladybug
ladybug/dt.py
DateTime._calculate_hour_and_minute
def _calculate_hour_and_minute(float_hour): """Calculate hour and minutes as integers from a float hour.""" hour, minute = int(float_hour), int(round((float_hour - int(float_hour)) * 60)) if minute == 60: return hour + 1, 0 else: return hour, minute
python
def _calculate_hour_and_minute(float_hour): """Calculate hour and minutes as integers from a float hour.""" hour, minute = int(float_hour), int(round((float_hour - int(float_hour)) * 60)) if minute == 60: return hour + 1, 0 else: return hour, minute
[ "def", "_calculate_hour_and_minute", "(", "float_hour", ")", ":", "hour", ",", "minute", "=", "int", "(", "float_hour", ")", ",", "int", "(", "round", "(", "(", "float_hour", "-", "int", "(", "float_hour", ")", ")", "*", "60", ")", ")", "if", "minute", "==", "60", ":", "return", "hour", "+", "1", ",", "0", "else", ":", "return", "hour", ",", "minute" ]
Calculate hour and minutes as integers from a float hour.
[ "Calculate", "hour", "and", "minutes", "as", "integers", "from", "a", "float", "hour", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L159-L165
train
237,585
ladybug-tools/ladybug
ladybug/dt.py
DateTime.add_minute
def add_minute(self, minute): """Create a new DateTime after the minutes are added. Args: minute: An integer value for minutes. """ _moy = self.moy + int(minute) return self.__class__.from_moy(_moy)
python
def add_minute(self, minute): """Create a new DateTime after the minutes are added. Args: minute: An integer value for minutes. """ _moy = self.moy + int(minute) return self.__class__.from_moy(_moy)
[ "def", "add_minute", "(", "self", ",", "minute", ")", ":", "_moy", "=", "self", ".", "moy", "+", "int", "(", "minute", ")", "return", "self", ".", "__class__", ".", "from_moy", "(", "_moy", ")" ]
Create a new DateTime after the minutes are added. Args: minute: An integer value for minutes.
[ "Create", "a", "new", "DateTime", "after", "the", "minutes", "are", "added", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L167-L174
train
237,586
ladybug-tools/ladybug
ladybug/dt.py
DateTime.to_json
def to_json(self): """Get date time as a dictionary.""" return {'year': self.year, 'month': self.month, 'day': self.day, 'hour': self.hour, 'minute': self.minute}
python
def to_json(self): """Get date time as a dictionary.""" return {'year': self.year, 'month': self.month, 'day': self.day, 'hour': self.hour, 'minute': self.minute}
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'year'", ":", "self", ".", "year", ",", "'month'", ":", "self", ".", "month", ",", "'day'", ":", "self", ".", "day", ",", "'hour'", ":", "self", ".", "hour", ",", "'minute'", ":", "self", ".", "minute", "}" ]
Get date time as a dictionary.
[ "Get", "date", "time", "as", "a", "dictionary", "." ]
c08b7308077a48d5612f644943f92d5b5dade583
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L208-L214
train
237,587
Neurosim-lab/netpyne
netpyne/network/conn.py
fullConn
def fullConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells ''' if sim.cfg.verbose: print('Generating set of all-to-all connections (rule: %s) ...' % (connParam['label'])) # get list of params that have a lambda function paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] for paramStrFunc in paramsStrFunc: # replace lambda function (with args as dict of lambda funcs) with list of values connParam[paramStrFunc[:-4]+'List'] = {(preGid,postGid): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].items()}) for preGid,preCellTags in preCellsTags.items() for postGid,postCellTags in postCellsTags.items()} for postCellGid in postCellsTags: # for each postsyn cell if postCellGid in self.gid2lid: # check if postsyn is in this node's list of gids for preCellGid, preCellTags in preCellsTags.items(): # for each presyn cell self._addCellConn(connParam, preCellGid, postCellGid)
python
def fullConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells ''' if sim.cfg.verbose: print('Generating set of all-to-all connections (rule: %s) ...' % (connParam['label'])) # get list of params that have a lambda function paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] for paramStrFunc in paramsStrFunc: # replace lambda function (with args as dict of lambda funcs) with list of values connParam[paramStrFunc[:-4]+'List'] = {(preGid,postGid): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].items()}) for preGid,preCellTags in preCellsTags.items() for postGid,postCellTags in postCellsTags.items()} for postCellGid in postCellsTags: # for each postsyn cell if postCellGid in self.gid2lid: # check if postsyn is in this node's list of gids for preCellGid, preCellTags in preCellsTags.items(): # for each presyn cell self._addCellConn(connParam, preCellGid, postCellGid)
[ "def", "fullConn", "(", "self", ",", "preCellsTags", ",", "postCellsTags", ",", "connParam", ")", ":", "from", ".", ".", "import", "sim", "if", "sim", ".", "cfg", ".", "verbose", ":", "print", "(", "'Generating set of all-to-all connections (rule: %s) ...'", "%", "(", "connParam", "[", "'label'", "]", ")", ")", "# get list of params that have a lambda function", "paramsStrFunc", "=", "[", "param", "for", "param", "in", "[", "p", "+", "'Func'", "for", "p", "in", "self", ".", "connStringFuncParams", "]", "if", "param", "in", "connParam", "]", "for", "paramStrFunc", "in", "paramsStrFunc", ":", "# replace lambda function (with args as dict of lambda funcs) with list of values", "connParam", "[", "paramStrFunc", "[", ":", "-", "4", "]", "+", "'List'", "]", "=", "{", "(", "preGid", ",", "postGid", ")", ":", "connParam", "[", "paramStrFunc", "]", "(", "*", "*", "{", "k", ":", "v", "if", "isinstance", "(", "v", ",", "Number", ")", "else", "v", "(", "preCellTags", ",", "postCellTags", ")", "for", "k", ",", "v", "in", "connParam", "[", "paramStrFunc", "+", "'Vars'", "]", ".", "items", "(", ")", "}", ")", "for", "preGid", ",", "preCellTags", "in", "preCellsTags", ".", "items", "(", ")", "for", "postGid", ",", "postCellTags", "in", "postCellsTags", ".", "items", "(", ")", "}", "for", "postCellGid", "in", "postCellsTags", ":", "# for each postsyn cell", "if", "postCellGid", "in", "self", ".", "gid2lid", ":", "# check if postsyn is in this node's list of gids", "for", "preCellGid", ",", "preCellTags", "in", "preCellsTags", ".", "items", "(", ")", ":", "# for each presyn cell", "self", ".", "_addCellConn", "(", "connParam", ",", "preCellGid", ",", "postCellGid", ")" ]
Generates connections between all pre and post-syn cells
[ "Generates", "connections", "between", "all", "pre", "and", "post", "-", "syn", "cells" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/network/conn.py#L310-L327
train
237,588
Neurosim-lab/netpyne
netpyne/network/conn.py
fromListConn
def fromListConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells based list of relative cell ids''' if sim.cfg.verbose: print('Generating set of connections from list (rule: %s) ...' % (connParam['label'])) orderedPreGids = sorted(preCellsTags) orderedPostGids = sorted(postCellsTags) # list of params that can have a lambda function paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] for paramStrFunc in paramsStrFunc: # replace lambda function (with args as dict of lambda funcs) with list of values connParam[paramStrFunc[:-4]+'List'] = {(orderedPreGids[preId],orderedPostGids[postId]): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellsTags[orderedPreGids[preId]], postCellsTags[orderedPostGids[postId]]) for k,v in connParam[paramStrFunc+'Vars'].items()}) for preId,postId in connParam['connList']} if 'weight' in connParam and isinstance(connParam['weight'], list): connParam['weightFromList'] = list(connParam['weight']) # if weight is a list, copy to weightFromList if 'delay' in connParam and isinstance(connParam['delay'], list): connParam['delayFromList'] = list(connParam['delay']) # if delay is a list, copy to delayFromList if 'loc' in connParam and isinstance(connParam['loc'], list): connParam['locFromList'] = list(connParam['loc']) # if delay is a list, copy to locFromList for iconn, (relativePreId, relativePostId) in enumerate(connParam['connList']): # for each postsyn cell preCellGid = orderedPreGids[relativePreId] postCellGid = orderedPostGids[relativePostId] if postCellGid in self.gid2lid: # check if postsyn is in this node's list of gids if 'weightFromList' in connParam: connParam['weight'] = connParam['weightFromList'][iconn] if 'delayFromList' in connParam: connParam['delay'] = connParam['delayFromList'][iconn] if 'locFromList' in connParam: connParam['loc'] = connParam['locFromList'][iconn] if preCellGid != postCellGid: # if not self-connection self._addCellConn(connParam, preCellGid, postCellGid)
python
def fromListConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells based list of relative cell ids''' if sim.cfg.verbose: print('Generating set of connections from list (rule: %s) ...' % (connParam['label'])) orderedPreGids = sorted(preCellsTags) orderedPostGids = sorted(postCellsTags) # list of params that can have a lambda function paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] for paramStrFunc in paramsStrFunc: # replace lambda function (with args as dict of lambda funcs) with list of values connParam[paramStrFunc[:-4]+'List'] = {(orderedPreGids[preId],orderedPostGids[postId]): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellsTags[orderedPreGids[preId]], postCellsTags[orderedPostGids[postId]]) for k,v in connParam[paramStrFunc+'Vars'].items()}) for preId,postId in connParam['connList']} if 'weight' in connParam and isinstance(connParam['weight'], list): connParam['weightFromList'] = list(connParam['weight']) # if weight is a list, copy to weightFromList if 'delay' in connParam and isinstance(connParam['delay'], list): connParam['delayFromList'] = list(connParam['delay']) # if delay is a list, copy to delayFromList if 'loc' in connParam and isinstance(connParam['loc'], list): connParam['locFromList'] = list(connParam['loc']) # if delay is a list, copy to locFromList for iconn, (relativePreId, relativePostId) in enumerate(connParam['connList']): # for each postsyn cell preCellGid = orderedPreGids[relativePreId] postCellGid = orderedPostGids[relativePostId] if postCellGid in self.gid2lid: # check if postsyn is in this node's list of gids if 'weightFromList' in connParam: connParam['weight'] = connParam['weightFromList'][iconn] if 'delayFromList' in connParam: connParam['delay'] = connParam['delayFromList'][iconn] if 'locFromList' in connParam: connParam['loc'] = connParam['locFromList'][iconn] if preCellGid != postCellGid: # if not self-connection self._addCellConn(connParam, preCellGid, postCellGid)
[ "def", "fromListConn", "(", "self", ",", "preCellsTags", ",", "postCellsTags", ",", "connParam", ")", ":", "from", ".", ".", "import", "sim", "if", "sim", ".", "cfg", ".", "verbose", ":", "print", "(", "'Generating set of connections from list (rule: %s) ...'", "%", "(", "connParam", "[", "'label'", "]", ")", ")", "orderedPreGids", "=", "sorted", "(", "preCellsTags", ")", "orderedPostGids", "=", "sorted", "(", "postCellsTags", ")", "# list of params that can have a lambda function", "paramsStrFunc", "=", "[", "param", "for", "param", "in", "[", "p", "+", "'Func'", "for", "p", "in", "self", ".", "connStringFuncParams", "]", "if", "param", "in", "connParam", "]", "for", "paramStrFunc", "in", "paramsStrFunc", ":", "# replace lambda function (with args as dict of lambda funcs) with list of values", "connParam", "[", "paramStrFunc", "[", ":", "-", "4", "]", "+", "'List'", "]", "=", "{", "(", "orderedPreGids", "[", "preId", "]", ",", "orderedPostGids", "[", "postId", "]", ")", ":", "connParam", "[", "paramStrFunc", "]", "(", "*", "*", "{", "k", ":", "v", "if", "isinstance", "(", "v", ",", "Number", ")", "else", "v", "(", "preCellsTags", "[", "orderedPreGids", "[", "preId", "]", "]", ",", "postCellsTags", "[", "orderedPostGids", "[", "postId", "]", "]", ")", "for", "k", ",", "v", "in", "connParam", "[", "paramStrFunc", "+", "'Vars'", "]", ".", "items", "(", ")", "}", ")", "for", "preId", ",", "postId", "in", "connParam", "[", "'connList'", "]", "}", "if", "'weight'", "in", "connParam", "and", "isinstance", "(", "connParam", "[", "'weight'", "]", ",", "list", ")", ":", "connParam", "[", "'weightFromList'", "]", "=", "list", "(", "connParam", "[", "'weight'", "]", ")", "# if weight is a list, copy to weightFromList", "if", "'delay'", "in", "connParam", "and", "isinstance", "(", "connParam", "[", "'delay'", "]", ",", "list", ")", ":", "connParam", "[", "'delayFromList'", "]", "=", "list", "(", "connParam", "[", "'delay'", "]", ")", "# if delay is a list, copy to delayFromList", "if", "'loc'", "in", "connParam", "and", "isinstance", "(", "connParam", "[", "'loc'", "]", ",", "list", ")", ":", "connParam", "[", "'locFromList'", "]", "=", "list", "(", "connParam", "[", "'loc'", "]", ")", "# if delay is a list, copy to locFromList", "for", "iconn", ",", "(", "relativePreId", ",", "relativePostId", ")", "in", "enumerate", "(", "connParam", "[", "'connList'", "]", ")", ":", "# for each postsyn cell", "preCellGid", "=", "orderedPreGids", "[", "relativePreId", "]", "postCellGid", "=", "orderedPostGids", "[", "relativePostId", "]", "if", "postCellGid", "in", "self", ".", "gid2lid", ":", "# check if postsyn is in this node's list of gids", "if", "'weightFromList'", "in", "connParam", ":", "connParam", "[", "'weight'", "]", "=", "connParam", "[", "'weightFromList'", "]", "[", "iconn", "]", "if", "'delayFromList'", "in", "connParam", ":", "connParam", "[", "'delay'", "]", "=", "connParam", "[", "'delayFromList'", "]", "[", "iconn", "]", "if", "'locFromList'", "in", "connParam", ":", "connParam", "[", "'loc'", "]", "=", "connParam", "[", "'locFromList'", "]", "[", "iconn", "]", "if", "preCellGid", "!=", "postCellGid", ":", "# if not self-connection", "self", ".", "_addCellConn", "(", "connParam", ",", "preCellGid", ",", "postCellGid", ")" ]
Generates connections between all pre and post-syn cells based list of relative cell ids
[ "Generates", "connections", "between", "all", "pre", "and", "post", "-", "syn", "cells", "based", "list", "of", "relative", "cell", "ids" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/network/conn.py#L514-L549
train
237,589
Neurosim-lab/netpyne
netpyne/cell/compartCell.py
CompartCell.setImembPtr
def setImembPtr(self): """Set PtrVector to point to the i_membrane_""" jseg = 0 for sec in list(self.secs.values()): hSec = sec['hObj'] for iseg, seg in enumerate(hSec): self.imembPtr.pset(jseg, seg._ref_i_membrane_) # notice the underscore at the end (in nA) jseg += 1
python
def setImembPtr(self): """Set PtrVector to point to the i_membrane_""" jseg = 0 for sec in list(self.secs.values()): hSec = sec['hObj'] for iseg, seg in enumerate(hSec): self.imembPtr.pset(jseg, seg._ref_i_membrane_) # notice the underscore at the end (in nA) jseg += 1
[ "def", "setImembPtr", "(", "self", ")", ":", "jseg", "=", "0", "for", "sec", "in", "list", "(", "self", ".", "secs", ".", "values", "(", ")", ")", ":", "hSec", "=", "sec", "[", "'hObj'", "]", "for", "iseg", ",", "seg", "in", "enumerate", "(", "hSec", ")", ":", "self", ".", "imembPtr", ".", "pset", "(", "jseg", ",", "seg", ".", "_ref_i_membrane_", ")", "# notice the underscore at the end (in nA)", "jseg", "+=", "1" ]
Set PtrVector to point to the i_membrane_
[ "Set", "PtrVector", "to", "point", "to", "the", "i_membrane_" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/cell/compartCell.py#L1245-L1252
train
237,590
Neurosim-lab/netpyne
examples/RL_arm/main.py
saveWeights
def saveWeights(sim): ''' Save the weights for each plastic synapse ''' with open(sim.weightsfilename,'w') as fid: for weightdata in sim.allWeights: fid.write('%0.0f' % weightdata[0]) # Time for i in range(1,len(weightdata)): fid.write('\t%0.8f' % weightdata[i]) fid.write('\n') print(('Saved weights as %s' % sim.weightsfilename))
python
def saveWeights(sim): ''' Save the weights for each plastic synapse ''' with open(sim.weightsfilename,'w') as fid: for weightdata in sim.allWeights: fid.write('%0.0f' % weightdata[0]) # Time for i in range(1,len(weightdata)): fid.write('\t%0.8f' % weightdata[i]) fid.write('\n') print(('Saved weights as %s' % sim.weightsfilename))
[ "def", "saveWeights", "(", "sim", ")", ":", "with", "open", "(", "sim", ".", "weightsfilename", ",", "'w'", ")", "as", "fid", ":", "for", "weightdata", "in", "sim", ".", "allWeights", ":", "fid", ".", "write", "(", "'%0.0f'", "%", "weightdata", "[", "0", "]", ")", "# Time", "for", "i", "in", "range", "(", "1", ",", "len", "(", "weightdata", ")", ")", ":", "fid", ".", "write", "(", "'\\t%0.8f'", "%", "weightdata", "[", "i", "]", ")", "fid", ".", "write", "(", "'\\n'", ")", "print", "(", "(", "'Saved weights as %s'", "%", "sim", ".", "weightsfilename", ")", ")" ]
Save the weights for each plastic synapse
[ "Save", "the", "weights", "for", "each", "plastic", "synapse" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/examples/RL_arm/main.py#L127-L134
train
237,591
Neurosim-lab/netpyne
netpyne/specs/utils.py
validateFunction
def validateFunction(strFunc, netParamsVars): ''' returns True if "strFunc" can be evaluated''' from math import exp, log, sqrt, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, pi, e rand = h.Random() stringFuncRandMethods = ['binomial', 'discunif', 'erlang', 'geometric', 'hypergeo', 'lognormal', 'negexp', 'normal', 'poisson', 'uniform', 'weibull'] for randmeth in stringFuncRandMethods: strFunc = strFunc.replace(randmeth, 'rand.'+randmeth) variables = { "pre_x" : 1, "pre_y" : 1, "pre_z" : 1, "post_x" : 1, "post_y" : 1, "post_z" : 1, "dist_x" : 1, "dist_y" : 1, "dist_z" : 1, "pre_xnorm" : 1, "pre_ynorm" : 1, "pre_znorm" : 1, "post_xnorm" : 1, "post_ynorm" : 1, "post_znorm" : 1, "dist_xnorm" : 1, "dist_ynorm" : 1, "dist_znorm" : 1, "dist_3D" : 1, "dist_3D_border" : 1, "dist_2D" : 1, "dist_norm3D": 1, "dist_norm2D" : 1, "rand": rand, "exp": exp, "log":log, "sqrt": sqrt, "sin":sin, "cos":cos, "tan":tan, "asin":asin, "acos":acos, "atan":atan, "sinh":sinh, "cosh":cosh, "tanh":tanh, "pi":pi,"e": e } # add netParams variables for k, v in netParamsVars.items(): if isinstance(v, Number): variables[k] = v try: eval(strFunc, variables) return True except: return False
python
def validateFunction(strFunc, netParamsVars): ''' returns True if "strFunc" can be evaluated''' from math import exp, log, sqrt, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, pi, e rand = h.Random() stringFuncRandMethods = ['binomial', 'discunif', 'erlang', 'geometric', 'hypergeo', 'lognormal', 'negexp', 'normal', 'poisson', 'uniform', 'weibull'] for randmeth in stringFuncRandMethods: strFunc = strFunc.replace(randmeth, 'rand.'+randmeth) variables = { "pre_x" : 1, "pre_y" : 1, "pre_z" : 1, "post_x" : 1, "post_y" : 1, "post_z" : 1, "dist_x" : 1, "dist_y" : 1, "dist_z" : 1, "pre_xnorm" : 1, "pre_ynorm" : 1, "pre_znorm" : 1, "post_xnorm" : 1, "post_ynorm" : 1, "post_znorm" : 1, "dist_xnorm" : 1, "dist_ynorm" : 1, "dist_znorm" : 1, "dist_3D" : 1, "dist_3D_border" : 1, "dist_2D" : 1, "dist_norm3D": 1, "dist_norm2D" : 1, "rand": rand, "exp": exp, "log":log, "sqrt": sqrt, "sin":sin, "cos":cos, "tan":tan, "asin":asin, "acos":acos, "atan":atan, "sinh":sinh, "cosh":cosh, "tanh":tanh, "pi":pi,"e": e } # add netParams variables for k, v in netParamsVars.items(): if isinstance(v, Number): variables[k] = v try: eval(strFunc, variables) return True except: return False
[ "def", "validateFunction", "(", "strFunc", ",", "netParamsVars", ")", ":", "from", "math", "import", "exp", ",", "log", ",", "sqrt", ",", "sin", ",", "cos", ",", "tan", ",", "asin", ",", "acos", ",", "atan", ",", "sinh", ",", "cosh", ",", "tanh", ",", "pi", ",", "e", "rand", "=", "h", ".", "Random", "(", ")", "stringFuncRandMethods", "=", "[", "'binomial'", ",", "'discunif'", ",", "'erlang'", ",", "'geometric'", ",", "'hypergeo'", ",", "'lognormal'", ",", "'negexp'", ",", "'normal'", ",", "'poisson'", ",", "'uniform'", ",", "'weibull'", "]", "for", "randmeth", "in", "stringFuncRandMethods", ":", "strFunc", "=", "strFunc", ".", "replace", "(", "randmeth", ",", "'rand.'", "+", "randmeth", ")", "variables", "=", "{", "\"pre_x\"", ":", "1", ",", "\"pre_y\"", ":", "1", ",", "\"pre_z\"", ":", "1", ",", "\"post_x\"", ":", "1", ",", "\"post_y\"", ":", "1", ",", "\"post_z\"", ":", "1", ",", "\"dist_x\"", ":", "1", ",", "\"dist_y\"", ":", "1", ",", "\"dist_z\"", ":", "1", ",", "\"pre_xnorm\"", ":", "1", ",", "\"pre_ynorm\"", ":", "1", ",", "\"pre_znorm\"", ":", "1", ",", "\"post_xnorm\"", ":", "1", ",", "\"post_ynorm\"", ":", "1", ",", "\"post_znorm\"", ":", "1", ",", "\"dist_xnorm\"", ":", "1", ",", "\"dist_ynorm\"", ":", "1", ",", "\"dist_znorm\"", ":", "1", ",", "\"dist_3D\"", ":", "1", ",", "\"dist_3D_border\"", ":", "1", ",", "\"dist_2D\"", ":", "1", ",", "\"dist_norm3D\"", ":", "1", ",", "\"dist_norm2D\"", ":", "1", ",", "\"rand\"", ":", "rand", ",", "\"exp\"", ":", "exp", ",", "\"log\"", ":", "log", ",", "\"sqrt\"", ":", "sqrt", ",", "\"sin\"", ":", "sin", ",", "\"cos\"", ":", "cos", ",", "\"tan\"", ":", "tan", ",", "\"asin\"", ":", "asin", ",", "\"acos\"", ":", "acos", ",", "\"atan\"", ":", "atan", ",", "\"sinh\"", ":", "sinh", ",", "\"cosh\"", ":", "cosh", ",", "\"tanh\"", ":", "tanh", ",", "\"pi\"", ":", "pi", ",", "\"e\"", ":", "e", "}", "# add netParams variables", "for", "k", ",", "v", "in", "netParamsVars", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "Number", ")", ":", "variables", "[", "k", "]", "=", "v", "try", ":", "eval", "(", "strFunc", ",", "variables", ")", "return", "True", "except", ":", "return", "False" ]
returns True if "strFunc" can be evaluated
[ "returns", "True", "if", "strFunc", "can", "be", "evaluated" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/specs/utils.py#L17-L50
train
237,592
Neurosim-lab/netpyne
netpyne/support/filter.py
bandpass
def bandpass(data, freqmin, freqmax, df, corners=4, zerophase=True): """ Butterworth-Bandpass Filter. Filter data from ``freqmin`` to ``freqmax`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Pass band low corner frequency. :param freqmax: Pass band high corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the filter order but zero phase shift in the resulting filtered trace. :return: Filtered data. """ fe = 0.5 * df low = freqmin / fe high = freqmax / fe # raise for some bad scenarios if high - 1.0 > -1e-6: msg = ("Selected high corner frequency ({}) of bandpass is at or " "above Nyquist ({}). Applying a high-pass instead.").format( freqmax, fe) warnings.warn(msg) return highpass(data, freq=freqmin, df=df, corners=corners, zerophase=zerophase) if low > 1: msg = "Selected low corner frequency is above Nyquist." raise ValueError(msg) z, p, k = iirfilter(corners, [low, high], btype='band', ftype='butter', output='zpk') sos = zpk2sos(z, p, k) if zerophase: firstpass = sosfilt(sos, data) return sosfilt(sos, firstpass[::-1])[::-1] else: return sosfilt(sos, data)
python
def bandpass(data, freqmin, freqmax, df, corners=4, zerophase=True): """ Butterworth-Bandpass Filter. Filter data from ``freqmin`` to ``freqmax`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Pass band low corner frequency. :param freqmax: Pass band high corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the filter order but zero phase shift in the resulting filtered trace. :return: Filtered data. """ fe = 0.5 * df low = freqmin / fe high = freqmax / fe # raise for some bad scenarios if high - 1.0 > -1e-6: msg = ("Selected high corner frequency ({}) of bandpass is at or " "above Nyquist ({}). Applying a high-pass instead.").format( freqmax, fe) warnings.warn(msg) return highpass(data, freq=freqmin, df=df, corners=corners, zerophase=zerophase) if low > 1: msg = "Selected low corner frequency is above Nyquist." raise ValueError(msg) z, p, k = iirfilter(corners, [low, high], btype='band', ftype='butter', output='zpk') sos = zpk2sos(z, p, k) if zerophase: firstpass = sosfilt(sos, data) return sosfilt(sos, firstpass[::-1])[::-1] else: return sosfilt(sos, data)
[ "def", "bandpass", "(", "data", ",", "freqmin", ",", "freqmax", ",", "df", ",", "corners", "=", "4", ",", "zerophase", "=", "True", ")", ":", "fe", "=", "0.5", "*", "df", "low", "=", "freqmin", "/", "fe", "high", "=", "freqmax", "/", "fe", "# raise for some bad scenarios", "if", "high", "-", "1.0", ">", "-", "1e-6", ":", "msg", "=", "(", "\"Selected high corner frequency ({}) of bandpass is at or \"", "\"above Nyquist ({}). Applying a high-pass instead.\"", ")", ".", "format", "(", "freqmax", ",", "fe", ")", "warnings", ".", "warn", "(", "msg", ")", "return", "highpass", "(", "data", ",", "freq", "=", "freqmin", ",", "df", "=", "df", ",", "corners", "=", "corners", ",", "zerophase", "=", "zerophase", ")", "if", "low", ">", "1", ":", "msg", "=", "\"Selected low corner frequency is above Nyquist.\"", "raise", "ValueError", "(", "msg", ")", "z", ",", "p", ",", "k", "=", "iirfilter", "(", "corners", ",", "[", "low", ",", "high", "]", ",", "btype", "=", "'band'", ",", "ftype", "=", "'butter'", ",", "output", "=", "'zpk'", ")", "sos", "=", "zpk2sos", "(", "z", ",", "p", ",", "k", ")", "if", "zerophase", ":", "firstpass", "=", "sosfilt", "(", "sos", ",", "data", ")", "return", "sosfilt", "(", "sos", ",", "firstpass", "[", ":", ":", "-", "1", "]", ")", "[", ":", ":", "-", "1", "]", "else", ":", "return", "sosfilt", "(", "sos", ",", "data", ")" ]
Butterworth-Bandpass Filter. Filter data from ``freqmin`` to ``freqmax`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Pass band low corner frequency. :param freqmax: Pass band high corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the filter order but zero phase shift in the resulting filtered trace. :return: Filtered data.
[ "Butterworth", "-", "Bandpass", "Filter", "." ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/filter.py#L45-L86
train
237,593
Neurosim-lab/netpyne
netpyne/support/filter.py
bandstop
def bandstop(data, freqmin, freqmax, df, corners=4, zerophase=False): """ Butterworth-Bandstop Filter. Filter data removing data between frequencies ``freqmin`` and ``freqmax`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Stop band low corner frequency. :param freqmax: Stop band high corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the number of corners but zero phase shift in the resulting filtered trace. :return: Filtered data. """ fe = 0.5 * df low = freqmin / fe high = freqmax / fe # raise for some bad scenarios if high > 1: high = 1.0 msg = "Selected high corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) if low > 1: msg = "Selected low corner frequency is above Nyquist." raise ValueError(msg) z, p, k = iirfilter(corners, [low, high], btype='bandstop', ftype='butter', output='zpk') sos = zpk2sos(z, p, k) if zerophase: firstpass = sosfilt(sos, data) return sosfilt(sos, firstpass[::-1])[::-1] else: return sosfilt(sos, data)
python
def bandstop(data, freqmin, freqmax, df, corners=4, zerophase=False): """ Butterworth-Bandstop Filter. Filter data removing data between frequencies ``freqmin`` and ``freqmax`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Stop band low corner frequency. :param freqmax: Stop band high corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the number of corners but zero phase shift in the resulting filtered trace. :return: Filtered data. """ fe = 0.5 * df low = freqmin / fe high = freqmax / fe # raise for some bad scenarios if high > 1: high = 1.0 msg = "Selected high corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) if low > 1: msg = "Selected low corner frequency is above Nyquist." raise ValueError(msg) z, p, k = iirfilter(corners, [low, high], btype='bandstop', ftype='butter', output='zpk') sos = zpk2sos(z, p, k) if zerophase: firstpass = sosfilt(sos, data) return sosfilt(sos, firstpass[::-1])[::-1] else: return sosfilt(sos, data)
[ "def", "bandstop", "(", "data", ",", "freqmin", ",", "freqmax", ",", "df", ",", "corners", "=", "4", ",", "zerophase", "=", "False", ")", ":", "fe", "=", "0.5", "*", "df", "low", "=", "freqmin", "/", "fe", "high", "=", "freqmax", "/", "fe", "# raise for some bad scenarios", "if", "high", ">", "1", ":", "high", "=", "1.0", "msg", "=", "\"Selected high corner frequency is above Nyquist. \"", "+", "\"Setting Nyquist as high corner.\"", "warnings", ".", "warn", "(", "msg", ")", "if", "low", ">", "1", ":", "msg", "=", "\"Selected low corner frequency is above Nyquist.\"", "raise", "ValueError", "(", "msg", ")", "z", ",", "p", ",", "k", "=", "iirfilter", "(", "corners", ",", "[", "low", ",", "high", "]", ",", "btype", "=", "'bandstop'", ",", "ftype", "=", "'butter'", ",", "output", "=", "'zpk'", ")", "sos", "=", "zpk2sos", "(", "z", ",", "p", ",", "k", ")", "if", "zerophase", ":", "firstpass", "=", "sosfilt", "(", "sos", ",", "data", ")", "return", "sosfilt", "(", "sos", ",", "firstpass", "[", ":", ":", "-", "1", "]", ")", "[", ":", ":", "-", "1", "]", "else", ":", "return", "sosfilt", "(", "sos", ",", "data", ")" ]
Butterworth-Bandstop Filter. Filter data removing data between frequencies ``freqmin`` and ``freqmax`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freqmin: Stop band low corner frequency. :param freqmax: Stop band high corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the number of corners but zero phase shift in the resulting filtered trace. :return: Filtered data.
[ "Butterworth", "-", "Bandstop", "Filter", "." ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/filter.py#L89-L128
train
237,594
Neurosim-lab/netpyne
netpyne/support/filter.py
lowpass
def lowpass(data, freq, df, corners=4, zerophase=False): """ Butterworth-Lowpass Filter. Filter data removing data over certain frequency ``freq`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freq: Filter corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the number of corners but zero phase shift in the resulting filtered trace. :return: Filtered data. """ fe = 0.5 * df f = freq / fe # raise for some bad scenarios if f > 1: f = 1.0 msg = "Selected corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) z, p, k = iirfilter(corners, f, btype='lowpass', ftype='butter', output='zpk') sos = zpk2sos(z, p, k) if zerophase: firstpass = sosfilt(sos, data) return sosfilt(sos, firstpass[::-1])[::-1] else: return sosfilt(sos, data)
python
def lowpass(data, freq, df, corners=4, zerophase=False): """ Butterworth-Lowpass Filter. Filter data removing data over certain frequency ``freq`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freq: Filter corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the number of corners but zero phase shift in the resulting filtered trace. :return: Filtered data. """ fe = 0.5 * df f = freq / fe # raise for some bad scenarios if f > 1: f = 1.0 msg = "Selected corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) z, p, k = iirfilter(corners, f, btype='lowpass', ftype='butter', output='zpk') sos = zpk2sos(z, p, k) if zerophase: firstpass = sosfilt(sos, data) return sosfilt(sos, firstpass[::-1])[::-1] else: return sosfilt(sos, data)
[ "def", "lowpass", "(", "data", ",", "freq", ",", "df", ",", "corners", "=", "4", ",", "zerophase", "=", "False", ")", ":", "fe", "=", "0.5", "*", "df", "f", "=", "freq", "/", "fe", "# raise for some bad scenarios", "if", "f", ">", "1", ":", "f", "=", "1.0", "msg", "=", "\"Selected corner frequency is above Nyquist. \"", "+", "\"Setting Nyquist as high corner.\"", "warnings", ".", "warn", "(", "msg", ")", "z", ",", "p", ",", "k", "=", "iirfilter", "(", "corners", ",", "f", ",", "btype", "=", "'lowpass'", ",", "ftype", "=", "'butter'", ",", "output", "=", "'zpk'", ")", "sos", "=", "zpk2sos", "(", "z", ",", "p", ",", "k", ")", "if", "zerophase", ":", "firstpass", "=", "sosfilt", "(", "sos", ",", "data", ")", "return", "sosfilt", "(", "sos", ",", "firstpass", "[", ":", ":", "-", "1", "]", ")", "[", ":", ":", "-", "1", "]", "else", ":", "return", "sosfilt", "(", "sos", ",", "data", ")" ]
Butterworth-Lowpass Filter. Filter data removing data over certain frequency ``freq`` using ``corners`` corners. The filter uses :func:`scipy.signal.iirfilter` (for design) and :func:`scipy.signal.sosfilt` (for applying the filter). :type data: numpy.ndarray :param data: Data to filter. :param freq: Filter corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners / order. :param zerophase: If True, apply filter once forwards and once backwards. This results in twice the number of corners but zero phase shift in the resulting filtered trace. :return: Filtered data.
[ "Butterworth", "-", "Lowpass", "Filter", "." ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/filter.py#L131-L165
train
237,595
Neurosim-lab/netpyne
netpyne/support/filter.py
integer_decimation
def integer_decimation(data, decimation_factor): """ Downsampling by applying a simple integer decimation. Make sure that no signal is present in frequency bands above the new Nyquist frequency (samp_rate/2/decimation_factor), e.g. by applying a lowpass filter beforehand! New sampling rate is old sampling rate divided by decimation_factor. :type data: numpy.ndarray :param data: Data to filter. :param decimation_factor: Integer decimation factor :return: Downsampled data (array length: old length / decimation_factor) """ if not isinstance(decimation_factor, int): msg = "Decimation_factor must be an integer!" raise TypeError(msg) # reshape and only use every decimation_factor-th sample data = np.array(data[::decimation_factor]) return data
python
def integer_decimation(data, decimation_factor): """ Downsampling by applying a simple integer decimation. Make sure that no signal is present in frequency bands above the new Nyquist frequency (samp_rate/2/decimation_factor), e.g. by applying a lowpass filter beforehand! New sampling rate is old sampling rate divided by decimation_factor. :type data: numpy.ndarray :param data: Data to filter. :param decimation_factor: Integer decimation factor :return: Downsampled data (array length: old length / decimation_factor) """ if not isinstance(decimation_factor, int): msg = "Decimation_factor must be an integer!" raise TypeError(msg) # reshape and only use every decimation_factor-th sample data = np.array(data[::decimation_factor]) return data
[ "def", "integer_decimation", "(", "data", ",", "decimation_factor", ")", ":", "if", "not", "isinstance", "(", "decimation_factor", ",", "int", ")", ":", "msg", "=", "\"Decimation_factor must be an integer!\"", "raise", "TypeError", "(", "msg", ")", "# reshape and only use every decimation_factor-th sample", "data", "=", "np", ".", "array", "(", "data", "[", ":", ":", "decimation_factor", "]", ")", "return", "data" ]
Downsampling by applying a simple integer decimation. Make sure that no signal is present in frequency bands above the new Nyquist frequency (samp_rate/2/decimation_factor), e.g. by applying a lowpass filter beforehand! New sampling rate is old sampling rate divided by decimation_factor. :type data: numpy.ndarray :param data: Data to filter. :param decimation_factor: Integer decimation factor :return: Downsampled data (array length: old length / decimation_factor)
[ "Downsampling", "by", "applying", "a", "simple", "integer", "decimation", "." ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/filter.py#L336-L356
train
237,596
Neurosim-lab/netpyne
netpyne/conversion/sonataImport.py
_distributeCells
def _distributeCells(numCellsPop): ''' distribute cells across compute nodes using round-robin''' from .. import sim hostCells = {} for i in range(sim.nhosts): hostCells[i] = [] for i in range(numCellsPop): hostCells[sim.nextHost].append(i) sim.nextHost+=1 if sim.nextHost>=sim.nhosts: sim.nextHost=0 if sim.cfg.verbose: print(("Distributed population of %i cells on %s hosts: %s, next: %s"%(numCellsPop,sim.nhosts,hostCells,sim.nextHost))) return hostCells
python
def _distributeCells(numCellsPop): ''' distribute cells across compute nodes using round-robin''' from .. import sim hostCells = {} for i in range(sim.nhosts): hostCells[i] = [] for i in range(numCellsPop): hostCells[sim.nextHost].append(i) sim.nextHost+=1 if sim.nextHost>=sim.nhosts: sim.nextHost=0 if sim.cfg.verbose: print(("Distributed population of %i cells on %s hosts: %s, next: %s"%(numCellsPop,sim.nhosts,hostCells,sim.nextHost))) return hostCells
[ "def", "_distributeCells", "(", "numCellsPop", ")", ":", "from", ".", ".", "import", "sim", "hostCells", "=", "{", "}", "for", "i", "in", "range", "(", "sim", ".", "nhosts", ")", ":", "hostCells", "[", "i", "]", "=", "[", "]", "for", "i", "in", "range", "(", "numCellsPop", ")", ":", "hostCells", "[", "sim", ".", "nextHost", "]", ".", "append", "(", "i", ")", "sim", ".", "nextHost", "+=", "1", "if", "sim", ".", "nextHost", ">=", "sim", ".", "nhosts", ":", "sim", ".", "nextHost", "=", "0", "if", "sim", ".", "cfg", ".", "verbose", ":", "print", "(", "(", "\"Distributed population of %i cells on %s hosts: %s, next: %s\"", "%", "(", "numCellsPop", ",", "sim", ".", "nhosts", ",", "hostCells", ",", "sim", ".", "nextHost", ")", ")", ")", "return", "hostCells" ]
distribute cells across compute nodes using round-robin
[ "distribute", "cells", "across", "compute", "nodes", "using", "round", "-", "robin" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/conversion/sonataImport.py#L82-L99
train
237,597
Neurosim-lab/netpyne
netpyne/support/csd.py
getCSD
def getCSD (lfps,sampr,minf=0.05,maxf=300,norm=True,vaknin=False,spacing=1.0): """ get current source density approximation using set of local field potentials with equidistant spacing first performs a lowpass filter lfps is a list or numpy array of LFPs arranged spatially by column spacing is in microns """ datband = getbandpass(lfps,sampr,minf,maxf) if datband.shape[0] > datband.shape[1]: # take CSD along smaller dimension ax = 1 else: ax = 0 # can change default to run Vaknin on bandpass filtered LFPs before calculating CSD, that # way would have same number of channels in CSD and LFP (but not critical, and would take more RAM); if vaknin: datband = Vaknin(datband) if norm: removemean(datband,ax=ax) # NB: when drawing CSD make sure that negative values (depolarizing intracellular current) drawn in red, # and positive values (hyperpolarizing intracellular current) drawn in blue CSD = -numpy.diff(datband,n=2,axis=ax) / spacing**2 # now each column (or row) is an electrode -- CSD along electrodes return CSD
python
def getCSD (lfps,sampr,minf=0.05,maxf=300,norm=True,vaknin=False,spacing=1.0): """ get current source density approximation using set of local field potentials with equidistant spacing first performs a lowpass filter lfps is a list or numpy array of LFPs arranged spatially by column spacing is in microns """ datband = getbandpass(lfps,sampr,minf,maxf) if datband.shape[0] > datband.shape[1]: # take CSD along smaller dimension ax = 1 else: ax = 0 # can change default to run Vaknin on bandpass filtered LFPs before calculating CSD, that # way would have same number of channels in CSD and LFP (but not critical, and would take more RAM); if vaknin: datband = Vaknin(datband) if norm: removemean(datband,ax=ax) # NB: when drawing CSD make sure that negative values (depolarizing intracellular current) drawn in red, # and positive values (hyperpolarizing intracellular current) drawn in blue CSD = -numpy.diff(datband,n=2,axis=ax) / spacing**2 # now each column (or row) is an electrode -- CSD along electrodes return CSD
[ "def", "getCSD", "(", "lfps", ",", "sampr", ",", "minf", "=", "0.05", ",", "maxf", "=", "300", ",", "norm", "=", "True", ",", "vaknin", "=", "False", ",", "spacing", "=", "1.0", ")", ":", "datband", "=", "getbandpass", "(", "lfps", ",", "sampr", ",", "minf", ",", "maxf", ")", "if", "datband", ".", "shape", "[", "0", "]", ">", "datband", ".", "shape", "[", "1", "]", ":", "# take CSD along smaller dimension", "ax", "=", "1", "else", ":", "ax", "=", "0", "# can change default to run Vaknin on bandpass filtered LFPs before calculating CSD, that", "# way would have same number of channels in CSD and LFP (but not critical, and would take more RAM);", "if", "vaknin", ":", "datband", "=", "Vaknin", "(", "datband", ")", "if", "norm", ":", "removemean", "(", "datband", ",", "ax", "=", "ax", ")", "# NB: when drawing CSD make sure that negative values (depolarizing intracellular current) drawn in red,", "# and positive values (hyperpolarizing intracellular current) drawn in blue", "CSD", "=", "-", "numpy", ".", "diff", "(", "datband", ",", "n", "=", "2", ",", "axis", "=", "ax", ")", "/", "spacing", "**", "2", "# now each column (or row) is an electrode -- CSD along electrodes", "return", "CSD" ]
get current source density approximation using set of local field potentials with equidistant spacing first performs a lowpass filter lfps is a list or numpy array of LFPs arranged spatially by column spacing is in microns
[ "get", "current", "source", "density", "approximation", "using", "set", "of", "local", "field", "potentials", "with", "equidistant", "spacing", "first", "performs", "a", "lowpass", "filter", "lfps", "is", "a", "list", "or", "numpy", "array", "of", "LFPs", "arranged", "spatially", "by", "column", "spacing", "is", "in", "microns" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/csd.py#L35-L54
train
237,598
Neurosim-lab/netpyne
doc/source/code/HHCellFile.py
Cell.createSynapses
def createSynapses(self): """Add an exponentially decaying synapse """ synsoma = h.ExpSyn(self.soma(0.5)) synsoma.tau = 2 synsoma.e = 0 syndend = h.ExpSyn(self.dend(0.5)) syndend.tau = 2 syndend.e = 0 self.synlist.append(synsoma) # synlist is defined in Cell self.synlist.append(syndend)
python
def createSynapses(self): """Add an exponentially decaying synapse """ synsoma = h.ExpSyn(self.soma(0.5)) synsoma.tau = 2 synsoma.e = 0 syndend = h.ExpSyn(self.dend(0.5)) syndend.tau = 2 syndend.e = 0 self.synlist.append(synsoma) # synlist is defined in Cell self.synlist.append(syndend)
[ "def", "createSynapses", "(", "self", ")", ":", "synsoma", "=", "h", ".", "ExpSyn", "(", "self", ".", "soma", "(", "0.5", ")", ")", "synsoma", ".", "tau", "=", "2", "synsoma", ".", "e", "=", "0", "syndend", "=", "h", ".", "ExpSyn", "(", "self", ".", "dend", "(", "0.5", ")", ")", "syndend", ".", "tau", "=", "2", "syndend", ".", "e", "=", "0", "self", ".", "synlist", ".", "append", "(", "synsoma", ")", "# synlist is defined in Cell", "self", ".", "synlist", ".", "append", "(", "syndend", ")" ]
Add an exponentially decaying synapse
[ "Add", "an", "exponentially", "decaying", "synapse" ]
edb67b5098b2e7923d55010ded59ad1bf75c0f18
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/doc/source/code/HHCellFile.py#L30-L39
train
237,599