INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Copy the complete lookup data into redis. Old data will be overwritten.
def copy_data_in_redis(self, redis_prefix, redis_instance): """ Copy the complete lookup data into redis. Old data will be overwritten. Args: redis_prefix (str): Prefix to distinguish the data in redis for the different looktypes redis_instance (str): an Instance of Redi...
Returns lookup data of an ADIF Entity
def lookup_entity(self, entity=None): """Returns lookup data of an ADIF Entity Args: entity (int): ADIF identifier of country Returns: dict: Dictionary containing the country specific data Raises: KeyError: No matching entity found Example:...
Create a copy of dict and remove not needed data
def _strip_metadata(self, my_dict): """ Create a copy of dict and remove not needed data """ new_dict = copy.deepcopy(my_dict) if const.START in new_dict: del new_dict[const.START] if const.END in new_dict: del new_dict[const.END] if const....
Returns lookup data if an exception exists for a callsign
def lookup_callsign(self, callsign=None, timestamp=timestamp_now): """ Returns lookup data if an exception exists for a callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: ...
Retrieve the data of an item from redis and put it in an index and data dictionary to match the common query interface.
def _get_dicts_from_redis(self, name, index_name, redis_prefix, item): """ Retrieve the data of an item from redis and put it in an index and data dictionary to match the common query interface. """ r = self._redis data_dict = {} data_index_dict = {} if r...
Checks if the item is found in the index. An entry in the index points to the data in the data_dict. This is mainly used retrieve callsigns and prefixes. In case data is found for item a dict containing the data is returned. Otherwise a KeyError is raised.
def _check_data_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the item is found in the index. An entry in the index points to the data in the data_dict. This is mainly used retrieve callsigns and prefixes. In case data is found for item, a dict containing the...
Checks if the callsign is marked as an invalid operation for a given timestamp. In case the operation is invalid True is returned. Otherwise a KeyError is raised.
def _check_inv_operation_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the callsign is marked as an invalid operation for a given timestamp. In case the operation is invalid, True is returned. Otherwise a KeyError is raised. """ if item in data_index...
Returns lookup data of a Prefix
def lookup_prefix(self, prefix, timestamp=timestamp_now): """ Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary contai...
Returns True if an operations is known as invalid
def is_invalid_operation(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns True if an operations is known as invalid Args: callsign (string): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Ret...
Checks the index and data if a cq - zone exception exists for the callsign When a zone exception is found the zone is returned. If no exception is found a KeyError is raised
def _check_zone_exception_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks the index and data if a cq-zone exception exists for the callsign When a zone exception is found, the zone is returned. If no exception is found a KeyError is raised """ if ...
Returns a CQ Zone if an exception exists for the given callsign
def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns a CQ Zone if an exception exists for the given callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) ...
Set up the Lookup object for Clublog Online API
def _lookup_clublogAPI(self, callsign=None, timestamp=timestamp_now, url="https://secure.clublog.org/dxcc", apikey=None): """ Set up the Lookup object for Clublog Online API """ params = {"year" : timestamp.strftime("%Y"), "month" : timestamp.strftime("%m"), "day" : time...
Performs the dxcc lookup against the QRZ. com XML API:
def _lookup_qrz_dxcc(self, dxcc_or_callsign, apikey, apiv="1.3.3"): """ Performs the dxcc lookup against the QRZ.com XML API: """ response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey, apiv=apiv) root = BeautifulSoup(response.text, "html.parser") lookup = {} ...
Performs the callsign lookup against the QRZ. com XML API:
def _lookup_qrz_callsign(self, callsign=None, apikey=None, apiv="1.3.3"): """ Performs the callsign lookup against the QRZ.com XML API: """ if apikey is None: raise AttributeError("Session Key Missing") callsign = callsign.upper() response = self._request_callsign_...
Load and process the ClublogXML file either as a download or from file
def _load_clublogXML(self, url="https://secure.clublog.org/cty.php", apikey=None, cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ if self._download: cty_file = self...
Load and process the ClublogXML file either as a download or from file
def _load_countryfile(self, url="https://www.country-files.com/cty/cty.plist", country_mapping_filename="countryfilemapping.json", cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ ...
Download lookup files either from Clublog or Country - files. com
def _download_file(self, url, apikey=None): """ Download lookup files either from Clublog or Country-files.com """ import gzip import tempfile cty = {} cty_date = "" cty_file_path = None filename = None # download file if apikey: # clubl...
Extract the header of the Clublog XML File
def _extract_clublog_header(self, cty_xml_filename): """ Extract the header of the Clublog XML File """ cty_header = {} try: with open(cty_xml_filename, "r") as cty: raw_header = cty.readline() cty_date = re.search("date='.+'", raw_heade...
remove the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser
def _remove_clublog_xml_header(self, cty_xml_filename): """ remove the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser """ import tempfile try: with open(cty_xml_filename, "r") as f: c...
parse the content of a clublog XML file and return the parsed values in dictionaries
def _parse_clublog_xml(self, cty_xml_filename): """ parse the content of a clublog XML file and return the parsed values in dictionaries """ entities = {} call_exceptions = {} prefixes = {} invalid_operations = {} zone_exceptions = {} ca...
Parse the content of a PLIST file from country - files. com return the parsed values in dictionaries. Country - files. com provides Prefixes and Exceptions
def _parse_country_file(self, cty_file, country_mapping_filename=None): """ Parse the content of a PLIST file from country-files.com return the parsed values in dictionaries. Country-files.com provides Prefixes and Exceptions """ import plistlib cty_list = None...
Generates a random word
def _generate_random_word(self, length): """ Generates a random word """ return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
Checks if the API Key is valid and if the request returned a 200 status ( ok )
def _check_html_response(self, response): """ Checks if the API Key is valid and if the request returned a 200 status (ok) """ error1 = "Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php" error2 = "Invalid or missing API Key...
Serialize a Dictionary into JSON
def _serialize_data(self, my_dict): """ Serialize a Dictionary into JSON """ new_dict = {} for item in my_dict: if isinstance(my_dict[item], datetime): new_dict[item] = my_dict[item].strftime('%Y-%m-%d%H:%M:%S') else: new_di...
Deserialize a JSON into a dictionary
def _deserialize_data(self, json_data): """ Deserialize a JSON into a dictionary """ my_dict = json.loads(json_data.decode('utf8').replace("'", '"'), encoding='UTF-8') for item in my_dict: if item == const.ADIF: my_dict[item] = int(my_dic...
Return the names of all callable attributes of an object
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
Create a new Config object from a configuration file.
def from_file(cls, filename, *, strict=True): """ Create a new Config object from a configuration file. Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. ...
Load the configuration from a file.
def load_from_file(self, filename=None, *, strict=True): """ Load the configuration from a file. The location of the configuration file can either be specified directly in the parameter filename or is searched for in the following order: 1. In the environment variable given by LIGH...
Load the configuration from a dictionary.
def load_from_dict(self, conf_dict=None): """ Load the configuration from a dictionary. Args: conf_dict (dict): Dictionary with the configuration. """ self.set_to_default() self._update_dict(self._config, conf_dict) self._update_python_paths()
Helper method to update an existing configuration with the values from a file.
def _update_from_file(self, filename): """ Helper method to update an existing configuration with the values from a file. Loads a configuration file and replaces all values in the existing configuration dictionary with the values from the file. Args: filename (str): The pat...
Recursively merges the fields for two dictionaries.
def _update_dict(self, to_dict, from_dict): """ Recursively merges the fields for two dictionaries. Args: to_dict (dict): The dictionary onto which the merge is executed. from_dict (dict): The dictionary merged into to_dict """ for key, value in from_dict.items()...
Append the workflow and libraries paths to the PYTHONPATH.
def _update_python_paths(self): """ Append the workflow and libraries paths to the PYTHONPATH. """ for path in self._config['workflows'] + self._config['libraries']: if os.path.isdir(os.path.abspath(path)): if path not in sys.path: sys.path.append(path) ...
Chop Line from DX - Cluster into pieces and return a dict with the spot data
def decode_char_spot(raw_string): """Chop Line from DX-Cluster into pieces and return a dict with the spot data""" data = {} # Spotter callsign if re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]): data[const.SPOTTER] = re.sub(':', '', re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]).group(0)) ...
Decode PC11 message which usually contains DX Spots
def decode_pc11_message(raw_string): """Decode PC11 message, which usually contains DX Spots""" data = {} spot = raw_string.split("^") data[const.FREQUENCY] = float(spot[1]) data[const.DX] = spot[2] data[const.TIME] = datetime.fromtimestamp(mktime(strptime(spot[3]+" "+spot[4][:-1], "%d-%b-%Y %H...
Decode PC23 Message which usually contains WCY
def decode_pc23_message(raw_string): """ Decode PC23 Message which usually contains WCY """ data = {} wcy = raw_string.split("^") data[const.R] = int(wcy[1]) data[const.expk] = int(wcy[2]) data[const.CALLSIGN] = wcy[3] data[const.A] = wcy[4] data[const.SFI] = wcy[5] data[const.K] = ...
The internal run method that decorates the public run method.
def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None): """ The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskDat...
converts WGS84 coordinates into the corresponding Maidenhead Locator
def latlong_to_locator (latitude, longitude): """converts WGS84 coordinates into the corresponding Maidenhead Locator Args: latitude (float): Latitude longitude (float): Longitude Returns: string: Maidenhead locator Raises: ValueError: When ...
converts Maidenhead locator in the corresponding WGS84 coordinates
def locator_to_latlong (locator): """converts Maidenhead locator in the corresponding WGS84 coordinates Args: locator (string): Locator, either 4 or 6 characters Returns: tuple (float, float): Latitude, Longitude Raises: ValueError: When called with wro...
calculates the ( shortpath ) distance between two Maidenhead locators
def calculate_distance(locator1, locator2): """calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km ...
calculates the ( longpath ) distance between two Maidenhead locators
def calculate_distance_longpath(locator1, locator2): """calculates the (longpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in...
calculates the heading from the first to the second locator
def calculate_heading(locator1, locator2): """calculates the heading from the first to the second locator Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Heading in deg Rais...
calculates the heading from the first to the second locator ( long path )
def calculate_heading_longpath(locator1, locator2): """calculates the heading from the first to the second locator (long path) Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Long pa...
calculates the next sunset and sunrise for a Maidenhead locator at a give date & time
def calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args: locator1 (string): Maidenhead Locator, either 4 or 6 characters calc_date (datetime, optional): Starting datetime for th...
Encode Python objects into a byte stream using cloudpickle.
def cloudpickle_dumps(obj, dumper=cloudpickle.dumps): """ Encode Python objects into a byte stream using cloudpickle. """ return dumper(obj, protocol=serialization.pickle_protocol)
Monkey patch Celery to use cloudpickle instead of pickle.
def patch_celery(): """ Monkey patch Celery to use cloudpickle instead of pickle. """ registry = serialization.registry serialization.pickle = cloudpickle registry.unregister('pickle') registry.register('pickle', cloudpickle_dumps, cloudpickle_loads, content_type='application/x...
Connects to the redis database.
def connect(self): """ Connects to the redis database. """ self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
Returns a single request.
def receive(self): """ Returns a single request. Takes the first request from the list of requests and returns it. If the list is empty, None is returned. Returns: Response: If a new request is available a Request object is returned, otherwise None is ...
Send a response back to the client that issued a request.
def send(self, response): """ Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent. """ self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), ...
Push the request back onto the queue.
def restore(self, request): """ Push the request back onto the queue. Args: request (Request): Reference to a request object that should be pushed back onto the request queue. """ self._connection.connection.rpush(self._request_key, pickle.dump...
Send a request to the server and wait for its response.
def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request. """ self._connection.c...
Verifies if pattern for matching and finding fulfill expected structure.
def verify_pattern(pattern): """Verifies if pattern for matching and finding fulfill expected structure. :param pattern: string pattern to verify :return: True if pattern has proper syntax, False otherwise """ regex = re.compile("^!?[a-zA-Z]+$|[*]{1,2}$") def __verify_pattern__(__pa...
Prints sentences tree as string using token_attr from token ( like pos_ tag_ etc. )
def print_tree(sent, token_attr): """Prints sentences tree as string using token_attr from token(like pos_, tag_ etc.) :param sent: sentence to print :param token_attr: choosen attr to present for tokens(e.g. dep_, pos_, tag_, ...) """ def __print_sent__(token, attr): print("{", en...
Matches given sentence with provided pattern.
def match_tree(sentence, pattern): """Matches given sentence with provided pattern. :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: True if sentence match to...
Find all tokens from parts of sentence fitted to pattern being on the end of matched sub - tree ( of sentence )
def find_tokens(sentence, pattern): """Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which senten...
Split a string using a single - character delimter
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret ==...
Render this template by applying it to context.
def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string """ # Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(se...
Add a line of source to the code. Indentation and newline will be added for you don t provide them.
def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add """ if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
Get or set the logging level.
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
Fetch currency conversion rate from the database
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %...
Get conversion rate to use in exchange
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """ reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency ...
Exchanges Money TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument ( target currency ) that returns proper conversion rate
def exchange_currency( base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: """ Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate """ if base....
Normalize * location_name * by stripping punctuation and collapsing runs of whitespace and return the normalized name.
def normalize(location_name, preserve_commas=False): """Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.""" def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORM...
Calculates precipitation statistics for the cascade model while aggregating hourly observations
def calc_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of n...
Calculates statistics in order to derive diurnal patterns of wind speed
def calc_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """ a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_shift)
Calculates statistics in order to derive diurnal patterns of relative humidity.
def calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """ a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hou...
Calculates statistics in order to derive diurnal patterns of temperature
def calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """ self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_cou...
Calculates statistics in order to derive solar radiation from sunshine duration or minimum/ maximum temperature.
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data ...
Exports statistical data to a JSON formatted file
def to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data """ def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series)...
Imports statistical data from a JSON formatted file
def from_json(cls, filename): """ Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data """ def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatist...
general function for radiation disaggregation Args: daily_data: daily values sun_times: daily dataframe including results of the util. sun_times function pot_rad: hourly dataframe including potential radiation method: keyword specifying the disaggregation method to be used angstr_a: parameter a of the Angstrom model ( ...
def disaggregate_radiation(data_daily, sun_times=None, pot_rad=None, method='pot_rad', angstr_a=0.25, angstr_b=0.5, bristcamp_a=0.75, ...
Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston G. E. and Elder K. ( 2006 ): A Meteorological Distribution System for High - Resolution Terrestrial Modeling ( MicroMet ) J. Hydrometeorol. 7 217–234. Corrections for eccentricity a...
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E...
calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow Keith L. and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricultural and forest meteorology 31. 2 (...
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and ...
Fit the A and C parameters for the Bristow & Campbell ( 1984 ) model using observed daily minimum and maximum temperature and mean daily ( e. g. aggregated from hourly values ) solar radiation. Parameters ---------- tmin: Series Observed daily minimum temperature. tmax: Series Observed daily maximum temperature. pot_ra...
def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily): """ Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------...
Calculate mean daily radiation from observed sunshine duration according to Angstroem ( 1924 ). Parameters ---------- ssd: Series Observed daily sunshine duration. day_length: Series Day lengths as calculated by calc_sun_times. pot_rad_daily: Series Mean potential daily solar radiation. a: float First parameter for the...
def angstroem(ssd, day_length, pot_rad_daily, a, b): """ Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by...
Fit the a and b parameters for the Angstroem ( 1924 ) model using observed daily sunshine duration and mean daily ( e. g. aggregated from hourly values ) solar radiation. Parameters ---------- ssd: Series Observed daily sunshine duration. day_length: Series Day lengths as calculated by calc_sun_times. pot_rad_daily: Se...
def fit_angstroem_params(ssd, day_length, pot_rad_daily, obs_rad_daily): """ Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series ...
Return a decorator that registers the decorated class as a resolver with the given * name *.
def register(name): """Return a decorator that registers the decorated class as a resolver with the given *name*.""" def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
Return a location resolver. The * order * argument if given should be a list of resolver names ; results from resolvers named earlier in the list are preferred over later ones. For a list of built - in resolver names see: doc:/ resolvers. The * options * argument can be used to pass configuration options to individual ...
def get_resolver(order=None, options=None, modules=None): """Return a location resolver. The *order* argument, if given, should be a list of resolver names; results from resolvers named earlier in the list are preferred over later ones. For a list of built-in resolver names, see :doc:`/resolvers`. Th...
Load locations into this resolver from the given * location_file * which should contain one JSON object per line representing a location. If * location_file * is not specified an internal location database is used.
def load_locations(self, location_file=None): """Load locations into this resolver from the given *location_file*, which should contain one JSON object per line representing a location. If *location_file* is not specified, an internal location database is used.""" if location_fi...
Return a tuple containing a canonicalized version of this location s country state county and city names.
def canonical(self): """Return a tuple containing a canonicalized version of this location's country, state, county, and city names.""" try: return tuple(map(lambda x: x.lower(), self.name())) except: return tuple([x.lower() for x in self.name()])
Return a tuple containing this location s country state county and city names.
def name(self): """Return a tuple containing this location's country, state, county, and city names.""" try: return tuple( getattr(self, x) if getattr(self, x) else u'' for x in ('country', 'state', 'county', 'city')) except: return...
Return a location representing the administrative unit above the one represented by this location.
def parent(self): """Return a location representing the administrative unit above the one represented by this location.""" if self.city: return Location( country=self.country, state=self.state, county=self.county) if self.county: return Location(co...
general function for humidity disaggregation
def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=None, kr=None, month_hour_precip_mean=None, preserve_daily_mean=False): """general function for humidity disaggregation Args: daily_data: daily values method: keyword...
genrates a diurnal course of windspeed accroding to the cosine function
def _cosine_function(x, a, b, t_shift): """genrates a diurnal course of windspeed accroding to the cosine function Args: x: series of euqally distributed windspeed values a: parameter a for the cosine function b: parameter b for the cosine function t_shift: parameter t_shift for...
general function for windspeed disaggregation
def disaggregate_wind(wind_daily, method='equal', a=None, b=None, t_shift=None): """general function for windspeed disaggregation Args: wind_daily: daily values method: keyword specifying the disaggregation method to be used a: parameter a for the cosine function b: parameter b ...
fits a cosine function to observed hourly windspeed data
def fit_cosine_function(wind): """fits a cosine function to observed hourly windspeed data Args: wind: observed hourly windspeed data Returns: parameters needed to generate diurnal features of windspeed using a cosine function """ wind_daily = wind.groupby(wind.index.date)....
Reads smet data and returns the data in required dataformat ( pd df )
def read_smet(filename, mode): """Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SMET file to read mode : "...
Reads dwd ( German Weather Service ) data and returns the data in required dataformat ( pd df )
def read_dwd(filename, metadata, mode="d", skip_last=True): """Reads dwd (German Weather Service) data and returns the data in required dataformat (pd df) Parameters ---- filename : DWD file to read (full path) / list of hourly files (RR+TU+FF) metadata : corresponding DWD metadata file to rea...
writes smet files
def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True): """writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use ...
reads a single file of KNMI s meteorological time series
def read_single_knmi_file(filename): """reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: filename: the file to be opened Returns: pandas data frame including time series """ hourly_data_obs_raw ...
Reads files from a directory and merges the time series
def read_knmi_dataset(directory): """Reads files from a directory and merges the time series Please note: For each station, a separate directory must be provided! data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: directory: directory including the files Returns: ...
Computes the times of sunrise solar noon and sunset for each day.
def calc_sun_times(self): """ Computes the times of sunrise, solar noon, and sunset for each day. """ self.sun_times = melodist.util.get_sun_times(self.data_daily.index, self.lon, self.lat, self.timezone)
Disaggregate wind speed.
def disaggregate_wind(self, method='equal'): """ Disaggregate wind speed. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily wind speed is duplicated for the 24 hours of the day. (Default) ...
Disaggregate relative humidity.
def disaggregate_humidity(self, method='equal', preserve_daily_mean=False): """ Disaggregate relative humidity. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily humidity is duplicated for the 24 hou...
Disaggregate air temperature.
def disaggregate_temperature(self, method='sine_min_max', min_max_time='fix', mod_nighttime=False): """ Disaggregate air temperature. Parameters ---------- method : str, optional Disaggregation method. ``sine_min_max`` Hourly temperatures...
Disaggregate precipitation.
def disaggregate_precipitation(self, method='equal', zerodiv='uniform', shift=0, master_precip=None): """ Disaggregate precipitation. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Daily precipitation is dis...
Disaggregate solar radiation.
def disaggregate_radiation(self, method='pot_rad', pot_rad=None): """ Disaggregate solar radiation. Parameters ---------- method : str, optional Disaggregation method. ``pot_rad`` Calculates potential clear-sky hourly radiation and scales...
Wrapper function for pandas. Series. interpolate that can be used to disaggregate values using various interpolation methods.
def interpolate(self, column_hours, method='linear', limit=24, limit_direction='both', **kwargs): """ Wrapper function for ``pandas.Series.interpolate`` that can be used to "disaggregate" values using various interpolation methods. Parameters ---------- column_hours : di...
Internal helper for preparing queries.
def _query_helper(self, by=None): """ Internal helper for preparing queries. """ if by is None: primary_keys = self.table.primary_key.columns.keys() if len(primary_keys) > 1: warnings.warn("WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. " ...
Get the first n entries for a given Table/ Column. Additional keywords passed to QueryDb. query ().
def head(self, n=10, by=None, **kwargs): """ Get the first n entries for a given Table/Column. Additional keywords passed to QueryDb.query(). Requires that the given table has a primary key specified. """ col, id_col = self._query_helper(by=by) select = ("SELECT...
Alias for. tail ().
def last(self, n=10, by=None, **kwargs): """ Alias for .tail(). """ return self.tail(n=n, by=by, **kwargs)