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
neo4j-contrib/neomodel
neomodel/properties.py
Property.default_value
def default_value(self): """ Generate a default value :return: the value """ if self.has_default: if hasattr(self.default, '__call__'): return self.default() else: return self.default else: raise Exception("No default value specified")
python
def default_value(self): """ Generate a default value :return: the value """ if self.has_default: if hasattr(self.default, '__call__'): return self.default() else: return self.default else: raise Exception("No default value specified")
[ "def", "default_value", "(", "self", ")", ":", "if", "self", ".", "has_default", ":", "if", "hasattr", "(", "self", ".", "default", ",", "'__call__'", ")", ":", "return", "self", ".", "default", "(", ")", "else", ":", "return", "self", ".", "default", ...
Generate a default value :return: the value
[ "Generate", "a", "default", "value" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/properties.py#L178-L190
train
206,800
neo4j-contrib/neomodel
neomodel/relationship.py
StructuredRel.save
def save(self): """ Save the relationship :return: self """ props = self.deflate(self.__properties__) query = "MATCH ()-[r]->() WHERE id(r)={self} " for key in props: query += " SET r.{0} = {{{1}}}".format(key, key) props['self'] = self.id db.cypher_query(query, props) return self
python
def save(self): """ Save the relationship :return: self """ props = self.deflate(self.__properties__) query = "MATCH ()-[r]->() WHERE id(r)={self} " for key in props: query += " SET r.{0} = {{{1}}}".format(key, key) props['self'] = self.id db.cypher_query(query, props) return self
[ "def", "save", "(", "self", ")", ":", "props", "=", "self", ".", "deflate", "(", "self", ".", "__properties__", ")", "query", "=", "\"MATCH ()-[r]->() WHERE id(r)={self} \"", "for", "key", "in", "props", ":", "query", "+=", "\" SET r.{0} = {{{1}}}\"", ".", "fo...
Save the relationship :return: self
[ "Save", "the", "relationship" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship.py#L34-L48
train
206,801
neo4j-contrib/neomodel
neomodel/relationship.py
StructuredRel.start_node
def start_node(self): """ Get start node :return: StructuredNode """ return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._start_node_id), resolve_objects = True)[0][0][0]
python
def start_node(self): """ Get start node :return: StructuredNode """ return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._start_node_id), resolve_objects = True)[0][0][0]
[ "def", "start_node", "(", "self", ")", ":", "return", "db", ".", "cypher_query", "(", "\"MATCH (aNode) \"", "\"WHERE id(aNode)={nodeid} \"", "\"RETURN aNode\"", ".", "format", "(", "nodeid", "=", "self", ".", "_start_node_id", ")", ",", "resolve_objects", "=", "Tr...
Get start node :return: StructuredNode
[ "Get", "start", "node" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship.py#L55-L64
train
206,802
neo4j-contrib/neomodel
neomodel/relationship.py
StructuredRel.end_node
def end_node(self): """ Get end node :return: StructuredNode """ return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._end_node_id), resolve_objects = True)[0][0][0]
python
def end_node(self): """ Get end node :return: StructuredNode """ return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._end_node_id), resolve_objects = True)[0][0][0]
[ "def", "end_node", "(", "self", ")", ":", "return", "db", ".", "cypher_query", "(", "\"MATCH (aNode) \"", "\"WHERE id(aNode)={nodeid} \"", "\"RETURN aNode\"", ".", "format", "(", "nodeid", "=", "self", ".", "_end_node_id", ")", ",", "resolve_objects", "=", "True",...
Get end node :return: StructuredNode
[ "Get", "end", "node" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship.py#L66-L75
train
206,803
csparpa/pyowm
pyowm/pollutionapi30/airpollution_client.py
AirPollutionHttpClient.get_coi
def get_coi(self, params_dict): """ Invokes the CO Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) start = params_dict['start'] interval = params_dict['interval'] # build request URL if start is None: timeref = 'current' else: if interval is None: timeref = self._trim_to(timeformatutils.to_date(start), 'year') else: timeref = self._trim_to(timeformatutils.to_date(start), interval) fixed_url = '%s/%s,%s/%s.json' % (CO_INDEX_URL, lat, lon, timeref) uri = http_client.HttpClient.to_url(fixed_url, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri) return json_data
python
def get_coi(self, params_dict): """ Invokes the CO Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) start = params_dict['start'] interval = params_dict['interval'] # build request URL if start is None: timeref = 'current' else: if interval is None: timeref = self._trim_to(timeformatutils.to_date(start), 'year') else: timeref = self._trim_to(timeformatutils.to_date(start), interval) fixed_url = '%s/%s,%s/%s.json' % (CO_INDEX_URL, lat, lon, timeref) uri = http_client.HttpClient.to_url(fixed_url, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri) return json_data
[ "def", "get_coi", "(", "self", ",", "params_dict", ")", ":", "lat", "=", "str", "(", "params_dict", "[", "'lat'", "]", ")", "lon", "=", "str", "(", "params_dict", "[", "'lon'", "]", ")", "start", "=", "params_dict", "[", "'start'", "]", "interval", "...
Invokes the CO Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError*
[ "Invokes", "the", "CO", "Index", "endpoint" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/pollutionapi30/airpollution_client.py#L39-L65
train
206,804
csparpa/pyowm
pyowm/alertapi30/parsers.py
AlertParser.parse_JSON
def parse_JSON(self, JSON_string): """ Parses a `pyowm.alertapi30.alert.Alert` instance out of raw JSON data. :param JSON_string: a raw JSON string :type JSON_string: str :return: a `pyowm.alertapi30.alert.Alert` instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result """ if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: alert_id = d['_id'] t = d['last_update'].split('.')[0].replace('T', ' ') + '+00' alert_last_update = timeformatutils._ISO8601_to_UNIXtime(t) alert_trigger_id = d['triggerId'] alert_met_conds = [ dict(current_value=c['current_value']['min'], condition=Condition.from_dict(c['condition'])) for c in d['conditions'] ] alert_coords = d['coordinates'] return Alert(alert_id, alert_trigger_id, alert_met_conds, alert_coords, last_update=alert_last_update) except ValueError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e) except KeyError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e)
python
def parse_JSON(self, JSON_string): """ Parses a `pyowm.alertapi30.alert.Alert` instance out of raw JSON data. :param JSON_string: a raw JSON string :type JSON_string: str :return: a `pyowm.alertapi30.alert.Alert` instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result """ if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) try: alert_id = d['_id'] t = d['last_update'].split('.')[0].replace('T', ' ') + '+00' alert_last_update = timeformatutils._ISO8601_to_UNIXtime(t) alert_trigger_id = d['triggerId'] alert_met_conds = [ dict(current_value=c['current_value']['min'], condition=Condition.from_dict(c['condition'])) for c in d['conditions'] ] alert_coords = d['coordinates'] return Alert(alert_id, alert_trigger_id, alert_met_conds, alert_coords, last_update=alert_last_update) except ValueError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e) except KeyError as e: raise parse_response_error.ParseResponseError('Impossible to parse JSON: %s' % e)
[ "def", "parse_JSON", "(", "self", ",", "JSON_string", ")", ":", "if", "JSON_string", "is", "None", ":", "raise", "parse_response_error", ".", "ParseResponseError", "(", "'JSON data is None'", ")", "d", "=", "json", ".", "loads", "(", "JSON_string", ")", "try",...
Parses a `pyowm.alertapi30.alert.Alert` instance out of raw JSON data. :param JSON_string: a raw JSON string :type JSON_string: str :return: a `pyowm.alertapi30.alert.Alert` instance or ``None`` if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result
[ "Parses", "a", "pyowm", ".", "alertapi30", ".", "alert", ".", "Alert", "instance", "out", "of", "raw", "JSON", "data", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/alertapi30/parsers.py#L127-L157
train
206,805
csparpa/pyowm
pyowm/commons/frontlinkedlist.py
FrontLinkedList.add
def add(self, data): """ Adds a new data node to the front list. The provided data will be encapsulated into a new instance of LinkedListNode class and linked list pointers will be updated, as well as list's size. :param data: the data to be inserted in the new list node :type data: object """ node = LinkedListNode(data, None) if self._size == 0: self._first_node = node self._last_node = node else: second_node = self._first_node self._first_node = node self._first_node.update_next(second_node) self._size += 1
python
def add(self, data): """ Adds a new data node to the front list. The provided data will be encapsulated into a new instance of LinkedListNode class and linked list pointers will be updated, as well as list's size. :param data: the data to be inserted in the new list node :type data: object """ node = LinkedListNode(data, None) if self._size == 0: self._first_node = node self._last_node = node else: second_node = self._first_node self._first_node = node self._first_node.update_next(second_node) self._size += 1
[ "def", "add", "(", "self", ",", "data", ")", ":", "node", "=", "LinkedListNode", "(", "data", ",", "None", ")", "if", "self", ".", "_size", "==", "0", ":", "self", ".", "_first_node", "=", "node", "self", ".", "_last_node", "=", "node", "else", ":"...
Adds a new data node to the front list. The provided data will be encapsulated into a new instance of LinkedListNode class and linked list pointers will be updated, as well as list's size. :param data: the data to be inserted in the new list node :type data: object
[ "Adds", "a", "new", "data", "node", "to", "the", "front", "list", ".", "The", "provided", "data", "will", "be", "encapsulated", "into", "a", "new", "instance", "of", "LinkedListNode", "class", "and", "linked", "list", "pointers", "will", "be", "updated", "...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/frontlinkedlist.py#L137-L155
train
206,806
csparpa/pyowm
pyowm/commons/frontlinkedlist.py
FrontLinkedList.remove
def remove(self, data): """ Removes a data node from the list. If the list contains more than one node having the same data that shall be removed, then the node having the first occurrency of the data is removed. :param data: the data to be removed in the new list node :type data: object """ current_node = self._first_node deleted = False if self._size == 0: return if data == current_node.data(): # case 1: the list has only one item if current_node.next() is None: self._first_node = LinkedListNode(None, None) self._last_node = self._first_node self._size = 0 return # case 2: the list has more than one item current_node = current_node.next() self._first_node = current_node self._size -= 1 return while True: if current_node is None: deleted = False break # Check next element's data next_node = current_node.next() if next_node is not None: if data == next_node.data(): next_next_node = next_node.next() current_node.update_next(next_next_node) next_node = None deleted = True break current_node = current_node.next() if deleted: self._size -= 1
python
def remove(self, data): """ Removes a data node from the list. If the list contains more than one node having the same data that shall be removed, then the node having the first occurrency of the data is removed. :param data: the data to be removed in the new list node :type data: object """ current_node = self._first_node deleted = False if self._size == 0: return if data == current_node.data(): # case 1: the list has only one item if current_node.next() is None: self._first_node = LinkedListNode(None, None) self._last_node = self._first_node self._size = 0 return # case 2: the list has more than one item current_node = current_node.next() self._first_node = current_node self._size -= 1 return while True: if current_node is None: deleted = False break # Check next element's data next_node = current_node.next() if next_node is not None: if data == next_node.data(): next_next_node = next_node.next() current_node.update_next(next_next_node) next_node = None deleted = True break current_node = current_node.next() if deleted: self._size -= 1
[ "def", "remove", "(", "self", ",", "data", ")", ":", "current_node", "=", "self", ".", "_first_node", "deleted", "=", "False", "if", "self", ".", "_size", "==", "0", ":", "return", "if", "data", "==", "current_node", ".", "data", "(", ")", ":", "# ca...
Removes a data node from the list. If the list contains more than one node having the same data that shall be removed, then the node having the first occurrency of the data is removed. :param data: the data to be removed in the new list node :type data: object
[ "Removes", "a", "data", "node", "from", "the", "list", ".", "If", "the", "list", "contains", "more", "than", "one", "node", "having", "the", "same", "data", "that", "shall", "be", "removed", "then", "the", "node", "having", "the", "first", "occurrency", ...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/frontlinkedlist.py#L157-L201
train
206,807
csparpa/pyowm
pyowm/commons/frontlinkedlist.py
FrontLinkedList.contains
def contains(self, data): """ Checks if the provided data is stored in at least one node of the list. :param data: the seeked data :type data: object :returns: a boolean """ for item in self: if item.data() == data: return True return False
python
def contains(self, data): """ Checks if the provided data is stored in at least one node of the list. :param data: the seeked data :type data: object :returns: a boolean """ for item in self: if item.data() == data: return True return False
[ "def", "contains", "(", "self", ",", "data", ")", ":", "for", "item", "in", "self", ":", "if", "item", ".", "data", "(", ")", "==", "data", ":", "return", "True", "return", "False" ]
Checks if the provided data is stored in at least one node of the list. :param data: the seeked data :type data: object :returns: a boolean
[ "Checks", "if", "the", "provided", "data", "is", "stored", "in", "at", "least", "one", "node", "of", "the", "list", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/frontlinkedlist.py#L203-L215
train
206,808
csparpa/pyowm
pyowm/commons/frontlinkedlist.py
FrontLinkedList.pop
def pop(self): """ Removes the last node from the list """ popped = False result = None current_node = self._first_node while not popped: next_node = current_node.next() next_next_node = next_node.next() if not next_next_node: self._last_node = current_node self._last_node.update_next(None) self._size -= 1 result = next_node.data() popped = True current_node = next_node return result
python
def pop(self): """ Removes the last node from the list """ popped = False result = None current_node = self._first_node while not popped: next_node = current_node.next() next_next_node = next_node.next() if not next_next_node: self._last_node = current_node self._last_node.update_next(None) self._size -= 1 result = next_node.data() popped = True current_node = next_node return result
[ "def", "pop", "(", "self", ")", ":", "popped", "=", "False", "result", "=", "None", "current_node", "=", "self", ".", "_first_node", "while", "not", "popped", ":", "next_node", "=", "current_node", ".", "next", "(", ")", "next_next_node", "=", "next_node",...
Removes the last node from the list
[ "Removes", "the", "last", "node", "from", "the", "list" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/frontlinkedlist.py#L237-L255
train
206,809
csparpa/pyowm
pyowm/weatherapi25/weather.py
Weather.get_sunset_time
def get_sunset_time(self, timeformat='unix'): """Returns the GMT time of sunset :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError """ if self._sunset_time is None: return None return timeformatutils.timeformat(self._sunset_time, timeformat)
python
def get_sunset_time(self, timeformat='unix'): """Returns the GMT time of sunset :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError """ if self._sunset_time is None: return None return timeformatutils.timeformat(self._sunset_time, timeformat)
[ "def", "get_sunset_time", "(", "self", ",", "timeformat", "=", "'unix'", ")", ":", "if", "self", ".", "_sunset_time", "is", "None", ":", "return", "None", "return", "timeformatutils", ".", "timeformat", "(", "self", ".", "_sunset_time", ",", "timeformat", ")...
Returns the GMT time of sunset :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError
[ "Returns", "the", "GMT", "time", "of", "sunset" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/weather.py#L113-L126
train
206,810
csparpa/pyowm
pyowm/weatherapi25/weather.py
Weather.get_sunrise_time
def get_sunrise_time(self, timeformat='unix'): """Returns the GMT time of sunrise :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError """ if self._sunrise_time is None: return None return timeformatutils.timeformat(self._sunrise_time, timeformat)
python
def get_sunrise_time(self, timeformat='unix'): """Returns the GMT time of sunrise :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError """ if self._sunrise_time is None: return None return timeformatutils.timeformat(self._sunrise_time, timeformat)
[ "def", "get_sunrise_time", "(", "self", ",", "timeformat", "=", "'unix'", ")", ":", "if", "self", ".", "_sunrise_time", "is", "None", ":", "return", "None", "return", "timeformatutils", ".", "timeformat", "(", "self", ".", "_sunrise_time", ",", "timeformat", ...
Returns the GMT time of sunrise :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :raises: ValueError
[ "Returns", "the", "GMT", "time", "of", "sunrise" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/weather.py#L128-L141
train
206,811
csparpa/pyowm
pyowm/weatherapi25/weather.py
Weather.get_temperature
def get_temperature(self, unit='kelvin'): """Returns a dict with temperature info :param unit: the unit of measure for the temperature values. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a dict containing temperature values. :raises: ValueError when unknown temperature units are provided """ # This is due to the fact that the OWM Weather API responses are mixing # absolute temperatures and temperature deltas together to_be_converted = dict() not_to_be_converted = dict() for label, temp in self._temperature.items(): if temp is None or temp < 0: not_to_be_converted[label] = temp else: to_be_converted[label] = temp converted = temputils.kelvin_dict_to(to_be_converted, unit) return dict(list(converted.items()) + \ list(not_to_be_converted.items()))
python
def get_temperature(self, unit='kelvin'): """Returns a dict with temperature info :param unit: the unit of measure for the temperature values. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a dict containing temperature values. :raises: ValueError when unknown temperature units are provided """ # This is due to the fact that the OWM Weather API responses are mixing # absolute temperatures and temperature deltas together to_be_converted = dict() not_to_be_converted = dict() for label, temp in self._temperature.items(): if temp is None or temp < 0: not_to_be_converted[label] = temp else: to_be_converted[label] = temp converted = temputils.kelvin_dict_to(to_be_converted, unit) return dict(list(converted.items()) + \ list(not_to_be_converted.items()))
[ "def", "get_temperature", "(", "self", ",", "unit", "=", "'kelvin'", ")", ":", "# This is due to the fact that the OWM Weather API responses are mixing", "# absolute temperatures and temperature deltas together", "to_be_converted", "=", "dict", "(", ")", "not_to_be_converted", "=...
Returns a dict with temperature info :param unit: the unit of measure for the temperature values. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a dict containing temperature values. :raises: ValueError when unknown temperature units are provided
[ "Returns", "a", "dict", "with", "temperature", "info" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/weather.py#L200-L221
train
206,812
csparpa/pyowm
pyowm/stationsapi30/station.py
Station.creation_time
def creation_time(self, timeformat='unix'): """Returns the UTC time of creation of this station :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.created_at is None: return None return timeformatutils.timeformat(self.created_at, timeformat)
python
def creation_time(self, timeformat='unix'): """Returns the UTC time of creation of this station :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.created_at is None: return None return timeformatutils.timeformat(self.created_at, timeformat)
[ "def", "creation_time", "(", "self", ",", "timeformat", "=", "'unix'", ")", ":", "if", "self", ".", "created_at", "is", "None", ":", "return", "None", "return", "timeformatutils", ".", "timeformat", "(", "self", ".", "created_at", ",", "timeformat", ")" ]
Returns the UTC time of creation of this station :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
[ "Returns", "the", "UTC", "time", "of", "creation", "of", "this", "station" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/station.py#L87-L101
train
206,813
csparpa/pyowm
pyowm/stationsapi30/station.py
Station.last_update_time
def last_update_time(self, timeformat='unix'): """Returns the UTC time of the last update on this station's metadata :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.updated_at is None: return None return timeformatutils.timeformat(self.updated_at, timeformat)
python
def last_update_time(self, timeformat='unix'): """Returns the UTC time of the last update on this station's metadata :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.updated_at is None: return None return timeformatutils.timeformat(self.updated_at, timeformat)
[ "def", "last_update_time", "(", "self", ",", "timeformat", "=", "'unix'", ")", ":", "if", "self", ".", "updated_at", "is", "None", ":", "return", "None", "return", "timeformatutils", ".", "timeformat", "(", "self", ".", "updated_at", ",", "timeformat", ")" ]
Returns the UTC time of the last update on this station's metadata :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
[ "Returns", "the", "UTC", "time", "of", "the", "last", "update", "on", "this", "station", "s", "metadata" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/station.py#L103-L117
train
206,814
csparpa/pyowm
pyowm/commons/tile.py
Tile.bounding_polygon
def bounding_polygon(self): """ Returns the bounding box polygon for this tile :return: `pywom.utils.geo.Polygon` instance """ lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom) print(lon_left, lat_bottom, lon_right, lat_top) return Polygon([[[lon_left, lat_top], [lon_right, lat_top], [lon_right, lat_bottom], [lon_left, lat_bottom], [lon_left, lat_top]]])
python
def bounding_polygon(self): """ Returns the bounding box polygon for this tile :return: `pywom.utils.geo.Polygon` instance """ lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom) print(lon_left, lat_bottom, lon_right, lat_top) return Polygon([[[lon_left, lat_top], [lon_right, lat_top], [lon_right, lat_bottom], [lon_left, lat_bottom], [lon_left, lat_top]]])
[ "def", "bounding_polygon", "(", "self", ")", ":", "lon_left", ",", "lat_bottom", ",", "lon_right", ",", "lat_top", "=", "Tile", ".", "tile_coords_to_bbox", "(", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "zoom", ")", "print", "(", "lon_...
Returns the bounding box polygon for this tile :return: `pywom.utils.geo.Polygon` instance
[ "Returns", "the", "bounding", "box", "polygon", "for", "this", "tile" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/tile.py#L43-L55
train
206,815
csparpa/pyowm
pyowm/commons/tile.py
Tile.tile_coords_for_point
def tile_coords_for_point(cls, geopoint, zoom): """ Returns the coordinates of the tile containing the specified geopoint at the specified zoom level :param geopoint: the input geopoint instance :type geopoint: `pywom.utils.geo.Point` :param zoom: zoom level :type zoom: int :return: a tuple (x, y) containing the tile-coordinates """ return Tile.geoocoords_to_tile_coords(geopoint.lon, geopoint.lat, zoom)
python
def tile_coords_for_point(cls, geopoint, zoom): """ Returns the coordinates of the tile containing the specified geopoint at the specified zoom level :param geopoint: the input geopoint instance :type geopoint: `pywom.utils.geo.Point` :param zoom: zoom level :type zoom: int :return: a tuple (x, y) containing the tile-coordinates """ return Tile.geoocoords_to_tile_coords(geopoint.lon, geopoint.lat, zoom)
[ "def", "tile_coords_for_point", "(", "cls", ",", "geopoint", ",", "zoom", ")", ":", "return", "Tile", ".", "geoocoords_to_tile_coords", "(", "geopoint", ".", "lon", ",", "geopoint", ".", "lat", ",", "zoom", ")" ]
Returns the coordinates of the tile containing the specified geopoint at the specified zoom level :param geopoint: the input geopoint instance :type geopoint: `pywom.utils.geo.Point` :param zoom: zoom level :type zoom: int :return: a tuple (x, y) containing the tile-coordinates
[ "Returns", "the", "coordinates", "of", "the", "tile", "containing", "the", "specified", "geopoint", "at", "the", "specified", "zoom", "level" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/tile.py#L58-L68
train
206,816
csparpa/pyowm
pyowm/tiles/tile_manager.py
TileManager.get_tile
def get_tile(self, x, y, zoom): """ Retrieves the tile having the specified coordinates and zoom level :param x: horizontal tile number in OWM tile reference system :type x: int :param y: vertical tile number in OWM tile reference system :type y: int :param zoom: zoom level for the tile :type zoom: int :returns: a `pyowm.tiles.Tile` instance """ status, data = self.http_client.get_png( ROOT_TILE_URL % self.map_layer + '/%s/%s/%s.png' % (zoom, x, y), params={'appid': self.API_key}) img = Image(data, ImageTypeEnum.PNG) return Tile(x, y, zoom, self.map_layer, img)
python
def get_tile(self, x, y, zoom): """ Retrieves the tile having the specified coordinates and zoom level :param x: horizontal tile number in OWM tile reference system :type x: int :param y: vertical tile number in OWM tile reference system :type y: int :param zoom: zoom level for the tile :type zoom: int :returns: a `pyowm.tiles.Tile` instance """ status, data = self.http_client.get_png( ROOT_TILE_URL % self.map_layer + '/%s/%s/%s.png' % (zoom, x, y), params={'appid': self.API_key}) img = Image(data, ImageTypeEnum.PNG) return Tile(x, y, zoom, self.map_layer, img)
[ "def", "get_tile", "(", "self", ",", "x", ",", "y", ",", "zoom", ")", ":", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_png", "(", "ROOT_TILE_URL", "%", "self", ".", "map_layer", "+", "'/%s/%s/%s.png'", "%", "(", "zoom", ",", "x"...
Retrieves the tile having the specified coordinates and zoom level :param x: horizontal tile number in OWM tile reference system :type x: int :param y: vertical tile number in OWM tile reference system :type y: int :param zoom: zoom level for the tile :type zoom: int :returns: a `pyowm.tiles.Tile` instance
[ "Retrieves", "the", "tile", "having", "the", "specified", "coordinates", "and", "zoom", "level" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/tiles/tile_manager.py#L34-L51
train
206,817
csparpa/pyowm
pyowm/alertapi30/alert_manager.py
AlertManager.get_triggers
def get_triggers(self): """ Retrieves all of the user's triggers that are set on the Weather Alert API. :returns: list of `pyowm.alertapi30.trigger.Trigger` objects """ status, data = self.http_client.get_json( TRIGGERS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.trigger_parser.parse_dict(item) for item in data]
python
def get_triggers(self): """ Retrieves all of the user's triggers that are set on the Weather Alert API. :returns: list of `pyowm.alertapi30.trigger.Trigger` objects """ status, data = self.http_client.get_json( TRIGGERS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.trigger_parser.parse_dict(item) for item in data]
[ "def", "get_triggers", "(", "self", ")", ":", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_json", "(", "TRIGGERS_URI", ",", "params", "=", "{", "'appid'", ":", "self", ".", "API_key", "}", ",", "headers", "=", "{", "'Content-Type'", ...
Retrieves all of the user's triggers that are set on the Weather Alert API. :returns: list of `pyowm.alertapi30.trigger.Trigger` objects
[ "Retrieves", "all", "of", "the", "user", "s", "triggers", "that", "are", "set", "on", "the", "Weather", "Alert", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/alertapi30/alert_manager.py#L92-L103
train
206,818
csparpa/pyowm
pyowm/alertapi30/alert_manager.py
AlertManager.get_trigger
def get_trigger(self, trigger_id): """ Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance """ assert isinstance(trigger_id, str), "Value must be a string" status, data = self.http_client.get_json( NAMED_TRIGGER_URI % trigger_id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.trigger_parser.parse_dict(data)
python
def get_trigger(self, trigger_id): """ Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance """ assert isinstance(trigger_id, str), "Value must be a string" status, data = self.http_client.get_json( NAMED_TRIGGER_URI % trigger_id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.trigger_parser.parse_dict(data)
[ "def", "get_trigger", "(", "self", ",", "trigger_id", ")", ":", "assert", "isinstance", "(", "trigger_id", ",", "str", ")", ",", "\"Value must be a string\"", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_json", "(", "NAMED_TRIGGER_URI", "%...
Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance
[ "Retrieves", "the", "named", "trigger", "from", "the", "Weather", "Alert", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/alertapi30/alert_manager.py#L105-L118
train
206,819
csparpa/pyowm
pyowm/alertapi30/alert_manager.py
AlertManager.delete_trigger
def delete_trigger(self, trigger): """ Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: `pyowm.alertapi30.trigger.Trigger` :returns: `None` if deletion is successful, an exception otherwise """ assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" status, _ = self.http_client.delete( NAMED_TRIGGER_URI % trigger.id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
python
def delete_trigger(self, trigger): """ Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: `pyowm.alertapi30.trigger.Trigger` :returns: `None` if deletion is successful, an exception otherwise """ assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" status, _ = self.http_client.delete( NAMED_TRIGGER_URI % trigger.id, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
[ "def", "delete_trigger", "(", "self", ",", "trigger", ")", ":", "assert", "trigger", "is", "not", "None", "assert", "isinstance", "(", "trigger", ".", "id", ",", "str", ")", ",", "\"Value must be a string\"", "status", ",", "_", "=", "self", ".", "http_cli...
Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: `pyowm.alertapi30.trigger.Trigger` :returns: `None` if deletion is successful, an exception otherwise
[ "Deletes", "from", "the", "Alert", "API", "the", "trigger", "record", "identified", "by", "the", "ID", "of", "the", "provided", "pyowm", ".", "alertapi30", ".", "trigger", ".", "Trigger", "along", "with", "all", "related", "alerts" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/alertapi30/alert_manager.py#L150-L164
train
206,820
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.get_stations
def get_stations(self): """ Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects """ status, data = self.http_client.get_json( STATIONS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.stations_parser.parse_dict(item) for item in data]
python
def get_stations(self): """ Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects """ status, data = self.http_client.get_json( STATIONS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [self.stations_parser.parse_dict(item) for item in data]
[ "def", "get_stations", "(", "self", ")", ":", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_json", "(", "STATIONS_URI", ",", "params", "=", "{", "'appid'", ":", "self", ".", "API_key", "}", ",", "headers", "=", "{", "'Content-Type'", ...
Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects
[ "Retrieves", "all", "of", "the", "user", "s", "stations", "registered", "on", "the", "Stations", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L39-L51
train
206,821
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.get_station
def get_station(self, id): """ Retrieves a named station registered on the Stations API. :param id: the ID of the station :type id: str :returns: a *pyowm.stationsapi30.station.Station* object """ status, data = self.http_client.get_json( NAMED_STATION_URI % str(id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.stations_parser.parse_dict(data)
python
def get_station(self, id): """ Retrieves a named station registered on the Stations API. :param id: the ID of the station :type id: str :returns: a *pyowm.stationsapi30.station.Station* object """ status, data = self.http_client.get_json( NAMED_STATION_URI % str(id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return self.stations_parser.parse_dict(data)
[ "def", "get_station", "(", "self", ",", "id", ")", ":", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_json", "(", "NAMED_STATION_URI", "%", "str", "(", "id", ")", ",", "params", "=", "{", "'appid'", ":", "self", ".", "API_key", "}...
Retrieves a named station registered on the Stations API. :param id: the ID of the station :type id: str :returns: a *pyowm.stationsapi30.station.Station* object
[ "Retrieves", "a", "named", "station", "registered", "on", "the", "Stations", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L53-L66
train
206,822
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.create_station
def create_station(self, external_id, name, lat, lon, alt=None): """ Create a new station on the Station API with the given parameters :param external_id: the user-given ID of the station :type external_id: str :param name: the name of the station :type name: str :param lat: latitude of the station :type lat: float :param lon: longitude of the station :type lon: float :param alt: altitude of the station :type alt: float :returns: the new *pyowm.stationsapi30.station.Station* object """ assert external_id is not None assert name is not None assert lon is not None assert lat is not None if lon < -180.0 or lon > 180.0: raise ValueError("'lon' value must be between -180 and 180") if lat < -90.0 or lat > 90.0: raise ValueError("'lat' value must be between -90 and 90") if alt is not None: if alt < 0.0: raise ValueError("'alt' value must not be negative") status, payload = self.http_client.post( STATIONS_URI, params={'appid': self.API_key}, data=dict(external_id=external_id, name=name, lat=lat, lon=lon, alt=alt), headers={'Content-Type': 'application/json'}) return self.stations_parser.parse_dict(payload)
python
def create_station(self, external_id, name, lat, lon, alt=None): """ Create a new station on the Station API with the given parameters :param external_id: the user-given ID of the station :type external_id: str :param name: the name of the station :type name: str :param lat: latitude of the station :type lat: float :param lon: longitude of the station :type lon: float :param alt: altitude of the station :type alt: float :returns: the new *pyowm.stationsapi30.station.Station* object """ assert external_id is not None assert name is not None assert lon is not None assert lat is not None if lon < -180.0 or lon > 180.0: raise ValueError("'lon' value must be between -180 and 180") if lat < -90.0 or lat > 90.0: raise ValueError("'lat' value must be between -90 and 90") if alt is not None: if alt < 0.0: raise ValueError("'alt' value must not be negative") status, payload = self.http_client.post( STATIONS_URI, params={'appid': self.API_key}, data=dict(external_id=external_id, name=name, lat=lat, lon=lon, alt=alt), headers={'Content-Type': 'application/json'}) return self.stations_parser.parse_dict(payload)
[ "def", "create_station", "(", "self", ",", "external_id", ",", "name", ",", "lat", ",", "lon", ",", "alt", "=", "None", ")", ":", "assert", "external_id", "is", "not", "None", "assert", "name", "is", "not", "None", "assert", "lon", "is", "not", "None",...
Create a new station on the Station API with the given parameters :param external_id: the user-given ID of the station :type external_id: str :param name: the name of the station :type name: str :param lat: latitude of the station :type lat: float :param lon: longitude of the station :type lon: float :param alt: altitude of the station :type alt: float :returns: the new *pyowm.stationsapi30.station.Station* object
[ "Create", "a", "new", "station", "on", "the", "Station", "API", "with", "the", "given", "parameters" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L68-L101
train
206,823
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.send_measurement
def send_measurement(self, measurement): """ Posts the provided Measurement object's data to the Station API. :param measurement: the *pyowm.stationsapi30.measurement.Measurement* object to be posted :type measurement: *pyowm.stationsapi30.measurement.Measurement* instance :returns: `None` if creation is successful, an exception otherwise """ assert measurement is not None assert measurement.station_id is not None status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=[self._structure_dict(measurement)], headers={'Content-Type': 'application/json'})
python
def send_measurement(self, measurement): """ Posts the provided Measurement object's data to the Station API. :param measurement: the *pyowm.stationsapi30.measurement.Measurement* object to be posted :type measurement: *pyowm.stationsapi30.measurement.Measurement* instance :returns: `None` if creation is successful, an exception otherwise """ assert measurement is not None assert measurement.station_id is not None status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=[self._structure_dict(measurement)], headers={'Content-Type': 'application/json'})
[ "def", "send_measurement", "(", "self", ",", "measurement", ")", ":", "assert", "measurement", "is", "not", "None", "assert", "measurement", ".", "station_id", "is", "not", "None", "status", ",", "_", "=", "self", ".", "http_client", ".", "post", "(", "MEA...
Posts the provided Measurement object's data to the Station API. :param measurement: the *pyowm.stationsapi30.measurement.Measurement* object to be posted :type measurement: *pyowm.stationsapi30.measurement.Measurement* instance :returns: `None` if creation is successful, an exception otherwise
[ "Posts", "the", "provided", "Measurement", "object", "s", "data", "to", "the", "Station", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L138-L153
train
206,824
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.send_measurements
def send_measurements(self, list_of_measurements): """ Posts data about the provided list of Measurement objects to the Station API. The objects may be related to different station IDs. :param list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* objects to be posted :type list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* instances :returns: `None` if creation is successful, an exception otherwise """ assert list_of_measurements is not None assert all([m.station_id is not None for m in list_of_measurements]) msmts = [self._structure_dict(m) for m in list_of_measurements] status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=msmts, headers={'Content-Type': 'application/json'})
python
def send_measurements(self, list_of_measurements): """ Posts data about the provided list of Measurement objects to the Station API. The objects may be related to different station IDs. :param list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* objects to be posted :type list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* instances :returns: `None` if creation is successful, an exception otherwise """ assert list_of_measurements is not None assert all([m.station_id is not None for m in list_of_measurements]) msmts = [self._structure_dict(m) for m in list_of_measurements] status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=msmts, headers={'Content-Type': 'application/json'})
[ "def", "send_measurements", "(", "self", ",", "list_of_measurements", ")", ":", "assert", "list_of_measurements", "is", "not", "None", "assert", "all", "(", "[", "m", ".", "station_id", "is", "not", "None", "for", "m", "in", "list_of_measurements", "]", ")", ...
Posts data about the provided list of Measurement objects to the Station API. The objects may be related to different station IDs. :param list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* objects to be posted :type list_of_measurements: list of *pyowm.stationsapi30.measurement.Measurement* instances :returns: `None` if creation is successful, an exception otherwise
[ "Posts", "data", "about", "the", "provided", "list", "of", "Measurement", "objects", "to", "the", "Station", "API", ".", "The", "objects", "may", "be", "related", "to", "different", "station", "IDs", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L155-L173
train
206,825
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.get_measurements
def get_measurements(self, station_id, aggregated_on, from_timestamp, to_timestamp, limit=100): """ Reads measurements of a specified station recorded in the specified time window and aggregated on minute, hour or day. Optionally, the number of resulting measurements can be limited. :param station_id: unique station identifier :type station_id: str :param aggregated_on: aggregation time-frame for this measurement :type aggregated_on: string between 'm','h' and 'd' :param from_timestamp: Unix timestamp corresponding to the beginning of the time window :type from_timestamp: int :param to_timestamp: Unix timestamp corresponding to the end of the time window :type to_timestamp: int :param limit: max number of items to be returned. Defaults to 100 :type limit: int :returns: list of *pyowm.stationsapi30.measurement.AggregatedMeasurement* objects """ assert station_id is not None assert aggregated_on is not None assert from_timestamp is not None assert from_timestamp > 0 assert to_timestamp is not None assert to_timestamp > 0 if to_timestamp < from_timestamp: raise ValueError("End timestamp can't be earlier than begin timestamp") assert isinstance(limit, int) assert limit >= 0 query = {'appid': self.API_key, 'station_id': station_id, 'type': aggregated_on, 'from': from_timestamp, 'to': to_timestamp, 'limit': limit} status, data = self.http_client.get_json( MEASUREMENTS_URI, params=query, headers={'Content-Type': 'application/json'}) return [self.aggregated_measurements_parser.parse_dict(item) for item in data]
python
def get_measurements(self, station_id, aggregated_on, from_timestamp, to_timestamp, limit=100): """ Reads measurements of a specified station recorded in the specified time window and aggregated on minute, hour or day. Optionally, the number of resulting measurements can be limited. :param station_id: unique station identifier :type station_id: str :param aggregated_on: aggregation time-frame for this measurement :type aggregated_on: string between 'm','h' and 'd' :param from_timestamp: Unix timestamp corresponding to the beginning of the time window :type from_timestamp: int :param to_timestamp: Unix timestamp corresponding to the end of the time window :type to_timestamp: int :param limit: max number of items to be returned. Defaults to 100 :type limit: int :returns: list of *pyowm.stationsapi30.measurement.AggregatedMeasurement* objects """ assert station_id is not None assert aggregated_on is not None assert from_timestamp is not None assert from_timestamp > 0 assert to_timestamp is not None assert to_timestamp > 0 if to_timestamp < from_timestamp: raise ValueError("End timestamp can't be earlier than begin timestamp") assert isinstance(limit, int) assert limit >= 0 query = {'appid': self.API_key, 'station_id': station_id, 'type': aggregated_on, 'from': from_timestamp, 'to': to_timestamp, 'limit': limit} status, data = self.http_client.get_json( MEASUREMENTS_URI, params=query, headers={'Content-Type': 'application/json'}) return [self.aggregated_measurements_parser.parse_dict(item) for item in data]
[ "def", "get_measurements", "(", "self", ",", "station_id", ",", "aggregated_on", ",", "from_timestamp", ",", "to_timestamp", ",", "limit", "=", "100", ")", ":", "assert", "station_id", "is", "not", "None", "assert", "aggregated_on", "is", "not", "None", "asser...
Reads measurements of a specified station recorded in the specified time window and aggregated on minute, hour or day. Optionally, the number of resulting measurements can be limited. :param station_id: unique station identifier :type station_id: str :param aggregated_on: aggregation time-frame for this measurement :type aggregated_on: string between 'm','h' and 'd' :param from_timestamp: Unix timestamp corresponding to the beginning of the time window :type from_timestamp: int :param to_timestamp: Unix timestamp corresponding to the end of the time window :type to_timestamp: int :param limit: max number of items to be returned. Defaults to 100 :type limit: int :returns: list of *pyowm.stationsapi30.measurement.AggregatedMeasurement* objects
[ "Reads", "measurements", "of", "a", "specified", "station", "recorded", "in", "the", "specified", "time", "window", "and", "aggregated", "on", "minute", "hour", "or", "day", ".", "Optionally", "the", "number", "of", "resulting", "measurements", "can", "be", "l...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L175-L217
train
206,826
csparpa/pyowm
pyowm/stationsapi30/stations_manager.py
StationsManager.send_buffer
def send_buffer(self, buffer): """ Posts to the Stations API data about the Measurement objects contained into the provided Buffer instance. :param buffer: the *pyowm.stationsapi30.buffer.Buffer* instance whose measurements are to be posted :type buffer: *pyowm.stationsapi30.buffer.Buffer* instance :returns: `None` if creation is successful, an exception otherwise """ assert buffer is not None msmts = [self._structure_dict(m) for m in buffer.measurements] status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=msmts, headers={'Content-Type': 'application/json'})
python
def send_buffer(self, buffer): """ Posts to the Stations API data about the Measurement objects contained into the provided Buffer instance. :param buffer: the *pyowm.stationsapi30.buffer.Buffer* instance whose measurements are to be posted :type buffer: *pyowm.stationsapi30.buffer.Buffer* instance :returns: `None` if creation is successful, an exception otherwise """ assert buffer is not None msmts = [self._structure_dict(m) for m in buffer.measurements] status, _ = self.http_client.post( MEASUREMENTS_URI, params={'appid': self.API_key}, data=msmts, headers={'Content-Type': 'application/json'})
[ "def", "send_buffer", "(", "self", ",", "buffer", ")", ":", "assert", "buffer", "is", "not", "None", "msmts", "=", "[", "self", ".", "_structure_dict", "(", "m", ")", "for", "m", "in", "buffer", ".", "measurements", "]", "status", ",", "_", "=", "sel...
Posts to the Stations API data about the Measurement objects contained into the provided Buffer instance. :param buffer: the *pyowm.stationsapi30.buffer.Buffer* instance whose measurements are to be posted :type buffer: *pyowm.stationsapi30.buffer.Buffer* instance :returns: `None` if creation is successful, an exception otherwise
[ "Posts", "to", "the", "Stations", "API", "data", "about", "the", "Measurement", "objects", "contained", "into", "the", "provided", "Buffer", "instance", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/stations_manager.py#L219-L235
train
206,827
csparpa/pyowm
pyowm/utils/xmlutils.py
create_DOM_node_from_dict
def create_DOM_node_from_dict(d, name, parent_node): """ Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is created for it as well as no DOM subnodes are generated for eventual ``None`` values found inside the dict :param d: the input dictionary :type d: dict :param name: the name for the DOM subtree to be created :type name: str :param parent_node: the parent DOM node the newly created subtree must be attached to :type parent_node: ``xml.etree.ElementTree.Element`` or derivative objects :returns: ``xml.etree.ElementTree.SubElementTree`` object """ if d is not None: root_dict_node = ET.SubElement(parent_node, name) for key, value in d.items(): if value is not None: node = ET.SubElement(root_dict_node, key) node.text = str(value) return root_dict_node
python
def create_DOM_node_from_dict(d, name, parent_node): """ Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is created for it as well as no DOM subnodes are generated for eventual ``None`` values found inside the dict :param d: the input dictionary :type d: dict :param name: the name for the DOM subtree to be created :type name: str :param parent_node: the parent DOM node the newly created subtree must be attached to :type parent_node: ``xml.etree.ElementTree.Element`` or derivative objects :returns: ``xml.etree.ElementTree.SubElementTree`` object """ if d is not None: root_dict_node = ET.SubElement(parent_node, name) for key, value in d.items(): if value is not None: node = ET.SubElement(root_dict_node, key) node.text = str(value) return root_dict_node
[ "def", "create_DOM_node_from_dict", "(", "d", ",", "name", ",", "parent_node", ")", ":", "if", "d", "is", "not", "None", ":", "root_dict_node", "=", "ET", ".", "SubElement", "(", "parent_node", ",", "name", ")", "for", "key", ",", "value", "in", "d", "...
Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is created for it as well as no DOM subnodes are generated for eventual ``None`` values found inside the dict :param d: the input dictionary :type d: dict :param name: the name for the DOM subtree to be created :type name: str :param parent_node: the parent DOM node the newly created subtree must be attached to :type parent_node: ``xml.etree.ElementTree.Element`` or derivative objects :returns: ``xml.etree.ElementTree.SubElementTree`` object
[ "Dumps", "dict", "data", "to", "an", "xml", ".", "etree", ".", "ElementTree", ".", "SubElement", "DOM", "subtree", "object", "and", "attaches", "it", "to", "the", "specified", "DOM", "parent", "node", ".", "The", "created", "subtree", "object", "is", "name...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/xmlutils.py#L8-L32
train
206,828
csparpa/pyowm
pyowm/utils/xmlutils.py
DOM_node_to_XML
def DOM_node_to_XML(tree, xml_declaration=True): """ Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type xml_declaration: bool :returns: Unicode object """ result = ET.tostring(tree, encoding='utf8', method='xml').decode('utf-8') if not xml_declaration: result = result.split("<?xml version='1.0' encoding='utf8'?>\n")[1] return result
python
def DOM_node_to_XML(tree, xml_declaration=True): """ Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type xml_declaration: bool :returns: Unicode object """ result = ET.tostring(tree, encoding='utf8', method='xml').decode('utf-8') if not xml_declaration: result = result.split("<?xml version='1.0' encoding='utf8'?>\n")[1] return result
[ "def", "DOM_node_to_XML", "(", "tree", ",", "xml_declaration", "=", "True", ")", ":", "result", "=", "ET", ".", "tostring", "(", "tree", ",", "encoding", "=", "'utf8'", ",", "method", "=", "'xml'", ")", ".", "decode", "(", "'utf-8'", ")", "if", "not", ...
Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type xml_declaration: bool :returns: Unicode object
[ "Prints", "a", "DOM", "tree", "to", "its", "Unicode", "representation", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/xmlutils.py#L35-L50
train
206,829
csparpa/pyowm
pyowm/utils/xmlutils.py
annotate_with_XMLNS
def annotate_with_XMLNS(tree, prefix, URI): """ Annotates the provided DOM tree with XMLNS attributes and adds XMLNS prefixes to the tags of the tree nodes. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.ElementTree`` or ``xml.etree.ElementTree.Element`` object :param prefix: XMLNS prefix for tree nodes' tags :type prefix: str :param URI: the URI for the XMLNS definition file :type URI: str """ if not ET.iselement(tree): tree = tree.getroot() tree.attrib['xmlns:' + prefix] = URI iterator = tree.iter() next(iterator) # Don't add XMLNS prefix to the root node for e in iterator: e.tag = prefix + ":" + e.tag
python
def annotate_with_XMLNS(tree, prefix, URI): """ Annotates the provided DOM tree with XMLNS attributes and adds XMLNS prefixes to the tags of the tree nodes. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.ElementTree`` or ``xml.etree.ElementTree.Element`` object :param prefix: XMLNS prefix for tree nodes' tags :type prefix: str :param URI: the URI for the XMLNS definition file :type URI: str """ if not ET.iselement(tree): tree = tree.getroot() tree.attrib['xmlns:' + prefix] = URI iterator = tree.iter() next(iterator) # Don't add XMLNS prefix to the root node for e in iterator: e.tag = prefix + ":" + e.tag
[ "def", "annotate_with_XMLNS", "(", "tree", ",", "prefix", ",", "URI", ")", ":", "if", "not", "ET", ".", "iselement", "(", "tree", ")", ":", "tree", "=", "tree", ".", "getroot", "(", ")", "tree", ".", "attrib", "[", "'xmlns:'", "+", "prefix", "]", "...
Annotates the provided DOM tree with XMLNS attributes and adds XMLNS prefixes to the tags of the tree nodes. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.ElementTree`` or ``xml.etree.ElementTree.Element`` object :param prefix: XMLNS prefix for tree nodes' tags :type prefix: str :param URI: the URI for the XMLNS definition file :type URI: str
[ "Annotates", "the", "provided", "DOM", "tree", "with", "XMLNS", "attributes", "and", "adds", "XMLNS", "prefixes", "to", "the", "tags", "of", "the", "tree", "nodes", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/xmlutils.py#L53-L73
train
206,830
csparpa/pyowm
pyowm/agroapi10/search.py
SatelliteImagerySearchResultSet.with_img_type
def with_img_type(self, image_type): """ Returns the search results having the specified image type :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances """ assert isinstance(image_type, ImageType) return list(filter(lambda x: x.image_type == image_type, self.metaimages))
python
def with_img_type(self, image_type): """ Returns the search results having the specified image type :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances """ assert isinstance(image_type, ImageType) return list(filter(lambda x: x.image_type == image_type, self.metaimages))
[ "def", "with_img_type", "(", "self", ",", "image_type", ")", ":", "assert", "isinstance", "(", "image_type", ",", "ImageType", ")", "return", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "image_type", "==", "image_type", ",", "self", ".", "m...
Returns the search results having the specified image type :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances
[ "Returns", "the", "search", "results", "having", "the", "specified", "image", "type" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/search.py#L165-L176
train
206,831
csparpa/pyowm
pyowm/agroapi10/search.py
SatelliteImagerySearchResultSet.with_preset
def with_preset(self, preset): """ Returns the seach results having the specified preset :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances """ assert isinstance(preset, str) return list(filter(lambda x: x.preset == preset, self.metaimages))
python
def with_preset(self, preset): """ Returns the seach results having the specified preset :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances """ assert isinstance(preset, str) return list(filter(lambda x: x.preset == preset, self.metaimages))
[ "def", "with_preset", "(", "self", ",", "preset", ")", ":", "assert", "isinstance", "(", "preset", ",", "str", ")", "return", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "preset", "==", "preset", ",", "self", ".", "metaimages", ")", ")"...
Returns the seach results having the specified preset :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances
[ "Returns", "the", "seach", "results", "having", "the", "specified", "preset" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/search.py#L178-L189
train
206,832
csparpa/pyowm
pyowm/agroapi10/search.py
SatelliteImagerySearchResultSet.with_img_type_and_preset
def with_img_type_and_preset(self, image_type, preset): """ Returns the search results having both the specified image type and preset :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances """ assert isinstance(image_type, ImageType) assert isinstance(preset, str) return list(filter(lambda x: x.image_type == image_type and x.preset == preset, self.metaimages))
python
def with_img_type_and_preset(self, image_type, preset): """ Returns the search results having both the specified image type and preset :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances """ assert isinstance(image_type, ImageType) assert isinstance(preset, str) return list(filter(lambda x: x.image_type == image_type and x.preset == preset, self.metaimages))
[ "def", "with_img_type_and_preset", "(", "self", ",", "image_type", ",", "preset", ")", ":", "assert", "isinstance", "(", "image_type", ",", "ImageType", ")", "assert", "isinstance", "(", "preset", ",", "str", ")", "return", "list", "(", "filter", "(", "lambd...
Returns the search results having both the specified image type and preset :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` instance :param preset: the desired image preset (valid values are provided by the `pyowm.agroapi10.enums.PresetEnum` enum) :type preset: str :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances
[ "Returns", "the", "search", "results", "having", "both", "the", "specified", "image", "type", "and", "preset" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/search.py#L191-L206
train
206,833
csparpa/pyowm
pyowm/weatherapi25/weathercoderegistry.py
WeatherCodeRegistry.status_for
def status_for(self, code): """ Returns the weather status related to the specified weather status code, if any is stored, ``None`` otherwise. :param code: the weather status code whose status is to be looked up :type code: int :returns: the weather status str or ``None`` if the code is not mapped """ is_in = lambda start, end, n: True if start <= n <= end else False for status in self._code_ranges_dict: for _range in self._code_ranges_dict[status]: if is_in(_range['start'],_range['end'],code): return status return None
python
def status_for(self, code): """ Returns the weather status related to the specified weather status code, if any is stored, ``None`` otherwise. :param code: the weather status code whose status is to be looked up :type code: int :returns: the weather status str or ``None`` if the code is not mapped """ is_in = lambda start, end, n: True if start <= n <= end else False for status in self._code_ranges_dict: for _range in self._code_ranges_dict[status]: if is_in(_range['start'],_range['end'],code): return status return None
[ "def", "status_for", "(", "self", ",", "code", ")", ":", "is_in", "=", "lambda", "start", ",", "end", ",", "n", ":", "True", "if", "start", "<=", "n", "<=", "end", "else", "False", "for", "status", "in", "self", ".", "_code_ranges_dict", ":", "for", ...
Returns the weather status related to the specified weather status code, if any is stored, ``None`` otherwise. :param code: the weather status code whose status is to be looked up :type code: int :returns: the weather status str or ``None`` if the code is not mapped
[ "Returns", "the", "weather", "status", "related", "to", "the", "specified", "weather", "status", "code", "if", "any", "is", "stored", "None", "otherwise", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/weathercoderegistry.py#L20-L34
train
206,834
csparpa/pyowm
pyowm/stationsapi30/measurement.py
AggregatedMeasurement.creation_time
def creation_time(self, timeformat='unix'): """Returns the UTC time of creation of this aggregated measurement :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.timestamp is None: return None return timeformatutils.timeformat(self.timestamp, timeformat)
python
def creation_time(self, timeformat='unix'): """Returns the UTC time of creation of this aggregated measurement :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.timestamp is None: return None return timeformatutils.timeformat(self.timestamp, timeformat)
[ "def", "creation_time", "(", "self", ",", "timeformat", "=", "'unix'", ")", ":", "if", "self", ".", "timestamp", "is", "None", ":", "return", "None", "return", "timeformatutils", ".", "timeformat", "(", "self", ".", "timestamp", ",", "timeformat", ")" ]
Returns the UTC time of creation of this aggregated measurement :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
[ "Returns", "the", "UTC", "time", "of", "creation", "of", "this", "aggregated", "measurement" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/measurement.py#L48-L62
train
206,835
csparpa/pyowm
pyowm/stationsapi30/measurement.py
AggregatedMeasurement.to_dict
def to_dict(self): """Dumps object fields into a dict :returns: a dict """ return {'station_id': self.station_id, 'timestamp': self.timestamp, 'aggregated_on': self.aggregated_on, 'temp': self.temp, 'humidity': self.humidity, 'wind': self.wind, 'pressure': self.pressure, 'precipitation': self.precipitation}
python
def to_dict(self): """Dumps object fields into a dict :returns: a dict """ return {'station_id': self.station_id, 'timestamp': self.timestamp, 'aggregated_on': self.aggregated_on, 'temp': self.temp, 'humidity': self.humidity, 'wind': self.wind, 'pressure': self.pressure, 'precipitation': self.precipitation}
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'station_id'", ":", "self", ".", "station_id", ",", "'timestamp'", ":", "self", ".", "timestamp", ",", "'aggregated_on'", ":", "self", ".", "aggregated_on", ",", "'temp'", ":", "self", ".", "temp", ...
Dumps object fields into a dict :returns: a dict
[ "Dumps", "object", "fields", "into", "a", "dict" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/measurement.py#L64-L77
train
206,836
csparpa/pyowm
pyowm/stationsapi30/measurement.py
Measurement.to_dict
def to_dict(self): """Dumps object fields into a dictionary :returns: a dict """ return { 'station_id': self.station_id, 'timestamp': self.timestamp, 'temperature': self.temperature, 'wind_speed': self.wind_speed, 'wind_gust': self.wind_gust, 'wind_deg': self.wind_deg, 'pressure': self.pressure, 'humidity': self.humidity, 'rain_1h': self.rain_1h, 'rain_6h': self.rain_6h, 'rain_24h': self.rain_24h, 'snow_1h': self.snow_1h, 'snow_6h': self.snow_6h, 'snow_24h': self.snow_24h, 'dew_point': self.dew_point, 'humidex': self.humidex, 'heat_index': self.heat_index, 'visibility_distance': self.visibility_distance, 'visibility_prefix': self.visibility_prefix, 'clouds_distance': self.clouds_distance, 'clouds_condition': self.clouds_condition, 'clouds_cumulus': self.clouds_cumulus, 'weather_precipitation': self.weather_precipitation, 'weather_descriptor': self.weather_descriptor, 'weather_intensity': self.weather_intensity, 'weather_proximity': self.weather_proximity, 'weather_obscuration': self.weather_obscuration, 'weather_other': self.weather_other}
python
def to_dict(self): """Dumps object fields into a dictionary :returns: a dict """ return { 'station_id': self.station_id, 'timestamp': self.timestamp, 'temperature': self.temperature, 'wind_speed': self.wind_speed, 'wind_gust': self.wind_gust, 'wind_deg': self.wind_deg, 'pressure': self.pressure, 'humidity': self.humidity, 'rain_1h': self.rain_1h, 'rain_6h': self.rain_6h, 'rain_24h': self.rain_24h, 'snow_1h': self.snow_1h, 'snow_6h': self.snow_6h, 'snow_24h': self.snow_24h, 'dew_point': self.dew_point, 'humidex': self.humidex, 'heat_index': self.heat_index, 'visibility_distance': self.visibility_distance, 'visibility_prefix': self.visibility_prefix, 'clouds_distance': self.clouds_distance, 'clouds_condition': self.clouds_condition, 'clouds_cumulus': self.clouds_cumulus, 'weather_precipitation': self.weather_precipitation, 'weather_descriptor': self.weather_descriptor, 'weather_intensity': self.weather_intensity, 'weather_proximity': self.weather_proximity, 'weather_obscuration': self.weather_obscuration, 'weather_other': self.weather_other}
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'station_id'", ":", "self", ".", "station_id", ",", "'timestamp'", ":", "self", ".", "timestamp", ",", "'temperature'", ":", "self", ".", "temperature", ",", "'wind_speed'", ":", "self", ".", "wind_s...
Dumps object fields into a dictionary :returns: a dict
[ "Dumps", "object", "fields", "into", "a", "dictionary" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/measurement.py#L199-L233
train
206,837
csparpa/pyowm
pyowm/weatherapi25/location.py
Location.to_geopoint
def to_geopoint(self): """ Returns the geoJSON compliant representation of this location :returns: a ``pyowm.utils.geo.Point`` instance """ if self._lon is None or self._lat is None: return None return geo.Point(self._lon, self._lat)
python
def to_geopoint(self): """ Returns the geoJSON compliant representation of this location :returns: a ``pyowm.utils.geo.Point`` instance """ if self._lon is None or self._lat is None: return None return geo.Point(self._lon, self._lat)
[ "def", "to_geopoint", "(", "self", ")", ":", "if", "self", ".", "_lon", "is", "None", "or", "self", ".", "_lat", "is", "None", ":", "return", "None", "return", "geo", ".", "Point", "(", "self", ".", "_lon", ",", "self", ".", "_lat", ")" ]
Returns the geoJSON compliant representation of this location :returns: a ``pyowm.utils.geo.Point`` instance
[ "Returns", "the", "geoJSON", "compliant", "representation", "of", "this", "location" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/location.py#L93-L102
train
206,838
csparpa/pyowm
pyowm/caches/lrucache.py
LRUCache.get
def get(self, request_url): """ In case of a hit, returns the JSON string which represents the OWM web API response to the request being identified by a specific string URL and updates the recency of this request. :param request_url: an URL that uniquely identifies the request whose response is to be looked up :type request_url: str :returns: a JSON str in case of cache hit or ``None`` otherwise """ try: cached_item = self._table[request_url] cur_time = timeutils.now('unix') if cur_time - cached_item['insertion_time'] > self._item_lifetime: # Cache item has expired self._clean_item(request_url) return None cached_item['insertion_time'] = cur_time # Update insertion time self._promote(request_url) return cached_item['data'] except: return None
python
def get(self, request_url): """ In case of a hit, returns the JSON string which represents the OWM web API response to the request being identified by a specific string URL and updates the recency of this request. :param request_url: an URL that uniquely identifies the request whose response is to be looked up :type request_url: str :returns: a JSON str in case of cache hit or ``None`` otherwise """ try: cached_item = self._table[request_url] cur_time = timeutils.now('unix') if cur_time - cached_item['insertion_time'] > self._item_lifetime: # Cache item has expired self._clean_item(request_url) return None cached_item['insertion_time'] = cur_time # Update insertion time self._promote(request_url) return cached_item['data'] except: return None
[ "def", "get", "(", "self", ",", "request_url", ")", ":", "try", ":", "cached_item", "=", "self", ".", "_table", "[", "request_url", "]", "cur_time", "=", "timeutils", ".", "now", "(", "'unix'", ")", "if", "cur_time", "-", "cached_item", "[", "'insertion_...
In case of a hit, returns the JSON string which represents the OWM web API response to the request being identified by a specific string URL and updates the recency of this request. :param request_url: an URL that uniquely identifies the request whose response is to be looked up :type request_url: str :returns: a JSON str in case of cache hit or ``None`` otherwise
[ "In", "case", "of", "a", "hit", "returns", "the", "JSON", "string", "which", "represents", "the", "OWM", "web", "API", "response", "to", "the", "request", "being", "identified", "by", "a", "specific", "string", "URL", "and", "updates", "the", "recency", "o...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/caches/lrucache.py#L58-L81
train
206,839
csparpa/pyowm
pyowm/caches/lrucache.py
LRUCache.set
def set(self, request_url, response_json): """ Checks if the maximum size of the cache has been reached and in case discards the least recently used item from 'usage_recency' and 'table'; then adds the response_json to be cached to the 'table' dict using as a lookup key the request_url of the request that generated the value; finally adds it at the front of 'usage_recency' :param request_url: the request URL that uniquely identifies the request whose response is to be cached :type request_url: str :param response_json: the response JSON to be cached :type response_json: str """ if self.size() == self._max_size: popped = self._usage_recency.pop() del self._table[popped] current_time = timeutils.now('unix') if request_url not in self._table: self._table[request_url] = {'data': response_json, 'insertion_time': current_time} self._usage_recency.add(request_url) else: self._table[request_url]['insertion_time'] = current_time self._promote(request_url)
python
def set(self, request_url, response_json): """ Checks if the maximum size of the cache has been reached and in case discards the least recently used item from 'usage_recency' and 'table'; then adds the response_json to be cached to the 'table' dict using as a lookup key the request_url of the request that generated the value; finally adds it at the front of 'usage_recency' :param request_url: the request URL that uniquely identifies the request whose response is to be cached :type request_url: str :param response_json: the response JSON to be cached :type response_json: str """ if self.size() == self._max_size: popped = self._usage_recency.pop() del self._table[popped] current_time = timeutils.now('unix') if request_url not in self._table: self._table[request_url] = {'data': response_json, 'insertion_time': current_time} self._usage_recency.add(request_url) else: self._table[request_url]['insertion_time'] = current_time self._promote(request_url)
[ "def", "set", "(", "self", ",", "request_url", ",", "response_json", ")", ":", "if", "self", ".", "size", "(", ")", "==", "self", ".", "_max_size", ":", "popped", "=", "self", ".", "_usage_recency", ".", "pop", "(", ")", "del", "self", ".", "_table",...
Checks if the maximum size of the cache has been reached and in case discards the least recently used item from 'usage_recency' and 'table'; then adds the response_json to be cached to the 'table' dict using as a lookup key the request_url of the request that generated the value; finally adds it at the front of 'usage_recency' :param request_url: the request URL that uniquely identifies the request whose response is to be cached :type request_url: str :param response_json: the response JSON to be cached :type response_json: str
[ "Checks", "if", "the", "maximum", "size", "of", "the", "cache", "has", "been", "reached", "and", "in", "case", "discards", "the", "least", "recently", "used", "item", "from", "usage_recency", "and", "table", ";", "then", "adds", "the", "response_json", "to",...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/caches/lrucache.py#L83-L108
train
206,840
csparpa/pyowm
pyowm/caches/lrucache.py
LRUCache._promote
def _promote(self, request_url): """ Moves the cache item specified by request_url to the front of the 'usage_recency' list """ self._usage_recency.remove(request_url) self._usage_recency.add(request_url)
python
def _promote(self, request_url): """ Moves the cache item specified by request_url to the front of the 'usage_recency' list """ self._usage_recency.remove(request_url) self._usage_recency.add(request_url)
[ "def", "_promote", "(", "self", ",", "request_url", ")", ":", "self", ".", "_usage_recency", ".", "remove", "(", "request_url", ")", "self", ".", "_usage_recency", ".", "add", "(", "request_url", ")" ]
Moves the cache item specified by request_url to the front of the 'usage_recency' list
[ "Moves", "the", "cache", "item", "specified", "by", "request_url", "to", "the", "front", "of", "the", "usage_recency", "list" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/caches/lrucache.py#L110-L116
train
206,841
csparpa/pyowm
pyowm/caches/lrucache.py
LRUCache._clean_item
def _clean_item(self, request_url): """ Removes the specified item from the cache's datastructures :param request_url: the request URL :type request_url: str """ del self._table[request_url] self._usage_recency.remove(request_url)
python
def _clean_item(self, request_url): """ Removes the specified item from the cache's datastructures :param request_url: the request URL :type request_url: str """ del self._table[request_url] self._usage_recency.remove(request_url)
[ "def", "_clean_item", "(", "self", ",", "request_url", ")", ":", "del", "self", ".", "_table", "[", "request_url", "]", "self", ".", "_usage_recency", ".", "remove", "(", "request_url", ")" ]
Removes the specified item from the cache's datastructures :param request_url: the request URL :type request_url: str
[ "Removes", "the", "specified", "item", "from", "the", "cache", "s", "datastructures" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/caches/lrucache.py#L118-L127
train
206,842
csparpa/pyowm
pyowm/caches/lrucache.py
LRUCache.clean
def clean(self): """ Empties the cache """ self._table.clear() for item in self._usage_recency: self._usage_recency.remove(item)
python
def clean(self): """ Empties the cache """ self._table.clear() for item in self._usage_recency: self._usage_recency.remove(item)
[ "def", "clean", "(", "self", ")", ":", "self", ".", "_table", ".", "clear", "(", ")", "for", "item", "in", "self", ".", "_usage_recency", ":", "self", ".", "_usage_recency", ".", "remove", "(", "item", ")" ]
Empties the cache
[ "Empties", "the", "cache" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/caches/lrucache.py#L129-L136
train
206,843
csparpa/pyowm
pyowm/stationsapi30/buffer.py
Buffer.sort_reverse_chronologically
def sort_reverse_chronologically(self): """ Sorts the measurements of this buffer in reverse chronological order """ self.measurements.sort(key=lambda m: m.timestamp, reverse=True)
python
def sort_reverse_chronologically(self): """ Sorts the measurements of this buffer in reverse chronological order """ self.measurements.sort(key=lambda m: m.timestamp, reverse=True)
[ "def", "sort_reverse_chronologically", "(", "self", ")", ":", "self", ".", "measurements", ".", "sort", "(", "key", "=", "lambda", "m", ":", "m", ".", "timestamp", ",", "reverse", "=", "True", ")" ]
Sorts the measurements of this buffer in reverse chronological order
[ "Sorts", "the", "measurements", "of", "this", "buffer", "in", "reverse", "chronological", "order" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/stationsapi30/buffer.py#L79-L84
train
206,844
csparpa/pyowm
pyowm/agroapi10/soil.py
Soil.surface_temp
def surface_temp(self, unit='kelvin'): """Returns the soil surface temperature :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided """ if unit == 'kelvin': return self._surface_temp if unit == 'celsius': return temputils.kelvin_to_celsius(self._surface_temp) if unit == 'fahrenheit': return temputils.kelvin_to_fahrenheit(self._surface_temp) else: raise ValueError('Wrong temperature unit')
python
def surface_temp(self, unit='kelvin'): """Returns the soil surface temperature :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided """ if unit == 'kelvin': return self._surface_temp if unit == 'celsius': return temputils.kelvin_to_celsius(self._surface_temp) if unit == 'fahrenheit': return temputils.kelvin_to_fahrenheit(self._surface_temp) else: raise ValueError('Wrong temperature unit')
[ "def", "surface_temp", "(", "self", ",", "unit", "=", "'kelvin'", ")", ":", "if", "unit", "==", "'kelvin'", ":", "return", "self", ".", "_surface_temp", "if", "unit", "==", "'celsius'", ":", "return", "temputils", ".", "kelvin_to_celsius", "(", "self", "."...
Returns the soil surface temperature :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided
[ "Returns", "the", "soil", "surface", "temperature" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/soil.py#L55-L72
train
206,845
csparpa/pyowm
pyowm/agroapi10/soil.py
Soil.ten_cm_temp
def ten_cm_temp(self, unit='kelvin'): """Returns the soil temperature measured 10 cm below surface :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided """ if unit == 'kelvin': return self._ten_cm_temp if unit == 'celsius': return temputils.kelvin_to_celsius(self._ten_cm_temp) if unit == 'fahrenheit': return temputils.kelvin_to_fahrenheit(self._ten_cm_temp) else: raise ValueError('Wrong temperature unit')
python
def ten_cm_temp(self, unit='kelvin'): """Returns the soil temperature measured 10 cm below surface :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided """ if unit == 'kelvin': return self._ten_cm_temp if unit == 'celsius': return temputils.kelvin_to_celsius(self._ten_cm_temp) if unit == 'fahrenheit': return temputils.kelvin_to_fahrenheit(self._ten_cm_temp) else: raise ValueError('Wrong temperature unit')
[ "def", "ten_cm_temp", "(", "self", ",", "unit", "=", "'kelvin'", ")", ":", "if", "unit", "==", "'kelvin'", ":", "return", "self", ".", "_ten_cm_temp", "if", "unit", "==", "'celsius'", ":", "return", "temputils", ".", "kelvin_to_celsius", "(", "self", ".", ...
Returns the soil temperature measured 10 cm below surface :param unit: the unit of measure for the temperature value. May be: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a float :raises: ValueError when unknown temperature units are provided
[ "Returns", "the", "soil", "temperature", "measured", "10", "cm", "below", "surface" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/soil.py#L74-L91
train
206,846
csparpa/pyowm
pyowm/utils/geo.py
assert_is_lat
def assert_is_lat(val): """ Checks it the given value is a feasible decimal latitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong """ assert type(val) is float or type(val) is int, "Value must be a number" if val < -90.0 or val > 90.0: raise ValueError("Latitude value must be between -90 and 90")
python
def assert_is_lat(val): """ Checks it the given value is a feasible decimal latitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong """ assert type(val) is float or type(val) is int, "Value must be a number" if val < -90.0 or val > 90.0: raise ValueError("Latitude value must be between -90 and 90")
[ "def", "assert_is_lat", "(", "val", ")", ":", "assert", "type", "(", "val", ")", "is", "float", "or", "type", "(", "val", ")", "is", "int", ",", "\"Value must be a number\"", "if", "val", "<", "-", "90.0", "or", "val", ">", "90.0", ":", "raise", "Val...
Checks it the given value is a feasible decimal latitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong
[ "Checks", "it", "the", "given", "value", "is", "a", "feasible", "decimal", "latitude" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/geo.py#L12-L24
train
206,847
csparpa/pyowm
pyowm/utils/geo.py
assert_is_lon
def assert_is_lon(val): """ Checks it the given value is a feasible decimal longitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong """ assert type(val) is float or type(val) is int, "Value must be a number" if val < -180.0 or val > 180.0: raise ValueError("Longitude value must be between -180 and 180")
python
def assert_is_lon(val): """ Checks it the given value is a feasible decimal longitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong """ assert type(val) is float or type(val) is int, "Value must be a number" if val < -180.0 or val > 180.0: raise ValueError("Longitude value must be between -180 and 180")
[ "def", "assert_is_lon", "(", "val", ")", ":", "assert", "type", "(", "val", ")", "is", "float", "or", "type", "(", "val", ")", "is", "int", ",", "\"Value must be a number\"", "if", "val", "<", "-", "180.0", "or", "val", ">", "180.0", ":", "raise", "V...
Checks it the given value is a feasible decimal longitude :param val: value to be checked :type val: int of float :returns: `None` :raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong
[ "Checks", "it", "the", "given", "value", "is", "a", "feasible", "decimal", "longitude" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/geo.py#L27-L39
train
206,848
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.create_polygon
def create_polygon(self, geopolygon, name=None): """ Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new polygon :type name: str :return: a `pyowm.agro10.polygon.Polygon` instance """ assert geopolygon is not None assert isinstance(geopolygon, GeoPolygon) data = dict() data['geo_json'] = { "type": "Feature", "properties": {}, "geometry": geopolygon.as_dict() } if name is not None: data['name'] = name status, payload = self.http_client.post( POLYGONS_URI, params={'appid': self.API_key}, data=data, headers={'Content-Type': 'application/json'}) return Polygon.from_dict(payload)
python
def create_polygon(self, geopolygon, name=None): """ Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new polygon :type name: str :return: a `pyowm.agro10.polygon.Polygon` instance """ assert geopolygon is not None assert isinstance(geopolygon, GeoPolygon) data = dict() data['geo_json'] = { "type": "Feature", "properties": {}, "geometry": geopolygon.as_dict() } if name is not None: data['name'] = name status, payload = self.http_client.post( POLYGONS_URI, params={'appid': self.API_key}, data=data, headers={'Content-Type': 'application/json'}) return Polygon.from_dict(payload)
[ "def", "create_polygon", "(", "self", ",", "geopolygon", ",", "name", "=", "None", ")", ":", "assert", "geopolygon", "is", "not", "None", "assert", "isinstance", "(", "geopolygon", ",", "GeoPolygon", ")", "data", "=", "dict", "(", ")", "data", "[", "'geo...
Create a new polygon on the Agro API with the given parameters :param geopolygon: the geopolygon representing the new polygon :type geopolygon: `pyowm.utils.geo.Polygon` instance :param name: optional mnemonic name for the new polygon :type name: str :return: a `pyowm.agro10.polygon.Polygon` instance
[ "Create", "a", "new", "polygon", "on", "the", "Agro", "API", "with", "the", "given", "parameters" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L41-L66
train
206,849
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.get_polygons
def get_polygons(self): """ Retrieves all of the user's polygons registered on the Agro API. :returns: list of `pyowm.agro10.polygon.Polygon` objects """ status, data = self.http_client.get_json( POLYGONS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [Polygon.from_dict(item) for item in data]
python
def get_polygons(self): """ Retrieves all of the user's polygons registered on the Agro API. :returns: list of `pyowm.agro10.polygon.Polygon` objects """ status, data = self.http_client.get_json( POLYGONS_URI, params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return [Polygon.from_dict(item) for item in data]
[ "def", "get_polygons", "(", "self", ")", ":", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_json", "(", "POLYGONS_URI", ",", "params", "=", "{", "'appid'", ":", "self", ".", "API_key", "}", ",", "headers", "=", "{", "'Content-Type'", ...
Retrieves all of the user's polygons registered on the Agro API. :returns: list of `pyowm.agro10.polygon.Polygon` objects
[ "Retrieves", "all", "of", "the", "user", "s", "polygons", "registered", "on", "the", "Agro", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L68-L80
train
206,850
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.get_polygon
def get_polygon(self, polygon_id): """ Retrieves a named polygon registered on the Agro API. :param id: the ID of the polygon :type id: str :returns: a `pyowm.agro10.polygon.Polygon` object """ status, data = self.http_client.get_json( NAMED_POLYGON_URI % str(polygon_id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return Polygon.from_dict(data)
python
def get_polygon(self, polygon_id): """ Retrieves a named polygon registered on the Agro API. :param id: the ID of the polygon :type id: str :returns: a `pyowm.agro10.polygon.Polygon` object """ status, data = self.http_client.get_json( NAMED_POLYGON_URI % str(polygon_id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'}) return Polygon.from_dict(data)
[ "def", "get_polygon", "(", "self", ",", "polygon_id", ")", ":", "status", ",", "data", "=", "self", ".", "http_client", ".", "get_json", "(", "NAMED_POLYGON_URI", "%", "str", "(", "polygon_id", ")", ",", "params", "=", "{", "'appid'", ":", "self", ".", ...
Retrieves a named polygon registered on the Agro API. :param id: the ID of the polygon :type id: str :returns: a `pyowm.agro10.polygon.Polygon` object
[ "Retrieves", "a", "named", "polygon", "registered", "on", "the", "Agro", "API", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L82-L95
train
206,851
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.update_polygon
def update_polygon(self, polygon): """ Updates on the Agro API the Polygon identified by the ID of the provided polygon object. Currently this only changes the mnemonic name of the remote polygon :param polygon: the `pyowm.agro10.polygon.Polygon` object to be updated :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if update is successful, an exception otherwise """ assert polygon.id is not None status, _ = self.http_client.put( NAMED_POLYGON_URI % str(polygon.id), params={'appid': self.API_key}, data=dict(name=polygon.name), headers={'Content-Type': 'application/json'})
python
def update_polygon(self, polygon): """ Updates on the Agro API the Polygon identified by the ID of the provided polygon object. Currently this only changes the mnemonic name of the remote polygon :param polygon: the `pyowm.agro10.polygon.Polygon` object to be updated :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if update is successful, an exception otherwise """ assert polygon.id is not None status, _ = self.http_client.put( NAMED_POLYGON_URI % str(polygon.id), params={'appid': self.API_key}, data=dict(name=polygon.name), headers={'Content-Type': 'application/json'})
[ "def", "update_polygon", "(", "self", ",", "polygon", ")", ":", "assert", "polygon", ".", "id", "is", "not", "None", "status", ",", "_", "=", "self", ".", "http_client", ".", "put", "(", "NAMED_POLYGON_URI", "%", "str", "(", "polygon", ".", "id", ")", ...
Updates on the Agro API the Polygon identified by the ID of the provided polygon object. Currently this only changes the mnemonic name of the remote polygon :param polygon: the `pyowm.agro10.polygon.Polygon` object to be updated :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if update is successful, an exception otherwise
[ "Updates", "on", "the", "Agro", "API", "the", "Polygon", "identified", "by", "the", "ID", "of", "the", "provided", "polygon", "object", ".", "Currently", "this", "only", "changes", "the", "mnemonic", "name", "of", "the", "remote", "polygon" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L97-L111
train
206,852
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.delete_polygon
def delete_polygon(self, polygon): """ Deletes on the Agro API the Polygon identified by the ID of the provided polygon object. :param polygon: the `pyowm.agro10.polygon.Polygon` object to be deleted :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if deletion is successful, an exception otherwise """ assert polygon.id is not None status, _ = self.http_client.delete( NAMED_POLYGON_URI % str(polygon.id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
python
def delete_polygon(self, polygon): """ Deletes on the Agro API the Polygon identified by the ID of the provided polygon object. :param polygon: the `pyowm.agro10.polygon.Polygon` object to be deleted :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if deletion is successful, an exception otherwise """ assert polygon.id is not None status, _ = self.http_client.delete( NAMED_POLYGON_URI % str(polygon.id), params={'appid': self.API_key}, headers={'Content-Type': 'application/json'})
[ "def", "delete_polygon", "(", "self", ",", "polygon", ")", ":", "assert", "polygon", ".", "id", "is", "not", "None", "status", ",", "_", "=", "self", ".", "http_client", ".", "delete", "(", "NAMED_POLYGON_URI", "%", "str", "(", "polygon", ".", "id", ")...
Deletes on the Agro API the Polygon identified by the ID of the provided polygon object. :param polygon: the `pyowm.agro10.polygon.Polygon` object to be deleted :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: `None` if deletion is successful, an exception otherwise
[ "Deletes", "on", "the", "Agro", "API", "the", "Polygon", "identified", "by", "the", "ID", "of", "the", "provided", "polygon", "object", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L113-L125
train
206,853
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.soil_data
def soil_data(self, polygon): """ Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance """ assert polygon is not None assert isinstance(polygon, Polygon) polyd = polygon.id status, data = self.http_client.get_json( SOIL_URI, params={'appid': self.API_key, 'polyid': polyd}, headers={'Content-Type': 'application/json'}) the_dict = dict() the_dict['reference_time'] = data['dt'] the_dict['surface_temp'] = data['t0'] the_dict['ten_cm_temp'] = data['t10'] the_dict['moisture'] = data['moisture'] the_dict['polygon_id'] = polyd return Soil.from_dict(the_dict)
python
def soil_data(self, polygon): """ Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance """ assert polygon is not None assert isinstance(polygon, Polygon) polyd = polygon.id status, data = self.http_client.get_json( SOIL_URI, params={'appid': self.API_key, 'polyid': polyd}, headers={'Content-Type': 'application/json'}) the_dict = dict() the_dict['reference_time'] = data['dt'] the_dict['surface_temp'] = data['t0'] the_dict['ten_cm_temp'] = data['t10'] the_dict['moisture'] = data['moisture'] the_dict['polygon_id'] = polyd return Soil.from_dict(the_dict)
[ "def", "soil_data", "(", "self", ",", "polygon", ")", ":", "assert", "polygon", "is", "not", "None", "assert", "isinstance", "(", "polygon", ",", "Polygon", ")", "polyd", "=", "polygon", ".", "id", "status", ",", "data", "=", "self", ".", "http_client", ...
Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance
[ "Retrieves", "the", "latest", "soil", "data", "on", "the", "specified", "polygon" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L129-L152
train
206,854
csparpa/pyowm
pyowm/agroapi10/agro_manager.py
AgroManager.stats_for_satellite_image
def stats_for_satellite_image(self, metaimage): """ Retrieves statistics for the satellite image described by the provided metadata. This is currently only supported 'EVI' and 'NDVI' presets :param metaimage: the satellite image's metadata, in the form of a `MetaImage` subtype instance :type metaimage: a `pyowm.agroapi10.imagery.MetaImage` subtype :return: dict """ if metaimage.preset != PresetEnum.EVI and metaimage.preset != PresetEnum.NDVI: raise ValueError("Unsupported image preset: should be EVI or NDVI") if metaimage.stats_url is None: raise ValueError("URL for image statistics is not defined") status, data = self.http_client.get_json(metaimage.stats_url, params={}) return data
python
def stats_for_satellite_image(self, metaimage): """ Retrieves statistics for the satellite image described by the provided metadata. This is currently only supported 'EVI' and 'NDVI' presets :param metaimage: the satellite image's metadata, in the form of a `MetaImage` subtype instance :type metaimage: a `pyowm.agroapi10.imagery.MetaImage` subtype :return: dict """ if metaimage.preset != PresetEnum.EVI and metaimage.preset != PresetEnum.NDVI: raise ValueError("Unsupported image preset: should be EVI or NDVI") if metaimage.stats_url is None: raise ValueError("URL for image statistics is not defined") status, data = self.http_client.get_json(metaimage.stats_url, params={}) return data
[ "def", "stats_for_satellite_image", "(", "self", ",", "metaimage", ")", ":", "if", "metaimage", ".", "preset", "!=", "PresetEnum", ".", "EVI", "and", "metaimage", ".", "preset", "!=", "PresetEnum", ".", "NDVI", ":", "raise", "ValueError", "(", "\"Unsupported i...
Retrieves statistics for the satellite image described by the provided metadata. This is currently only supported 'EVI' and 'NDVI' presets :param metaimage: the satellite image's metadata, in the form of a `MetaImage` subtype instance :type metaimage: a `pyowm.agroapi10.imagery.MetaImage` subtype :return: dict
[ "Retrieves", "statistics", "for", "the", "satellite", "image", "described", "by", "the", "provided", "metadata", ".", "This", "is", "currently", "only", "supported", "EVI", "and", "NDVI", "presets" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/agroapi10/agro_manager.py#L302-L316
train
206,855
csparpa/pyowm
pyowm/weatherapi25/owm25.py
OWM25.is_API_online
def is_API_online(self): """ Returns True if the OWM Weather API is currently online. A short timeout is used to determine API service availability. :returns: bool """ params = {'q': 'London,GB'} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type) try: _1, _2 = self._wapi.cacheable_get_json(uri, params=params) return True except api_call_error.APICallTimeoutError: return False
python
def is_API_online(self): """ Returns True if the OWM Weather API is currently online. A short timeout is used to determine API service availability. :returns: bool """ params = {'q': 'London,GB'} uri = http_client.HttpClient.to_url(OBSERVATION_URL, self._API_key, self._subscription_type) try: _1, _2 = self._wapi.cacheable_get_json(uri, params=params) return True except api_call_error.APICallTimeoutError: return False
[ "def", "is_API_online", "(", "self", ")", ":", "params", "=", "{", "'q'", ":", "'London,GB'", "}", "uri", "=", "http_client", ".", "HttpClient", ".", "to_url", "(", "OBSERVATION_URL", ",", "self", ".", "_API_key", ",", "self", ".", "_subscription_type", ")...
Returns True if the OWM Weather API is currently online. A short timeout is used to determine API service availability. :returns: bool
[ "Returns", "True", "if", "the", "OWM", "Weather", "API", "is", "currently", "online", ".", "A", "short", "timeout", "is", "used", "to", "determine", "API", "service", "availability", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L190-L206
train
206,856
csparpa/pyowm
pyowm/weatherapi25/owm25.py
OWM25._retrieve_station_history
def _retrieve_station_history(self, station_ID, limit, interval): """ Helper method for station_X_history functions. """ params = {'id': station_ID, 'type': interval, 'lang': self._language} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(STATION_WEATHER_HISTORY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) station_history = \ self._parsers['station_history'].parse_JSON(json_data) if station_history is not None: station_history.set_station_ID(station_ID) station_history.set_interval(interval) return station_history
python
def _retrieve_station_history(self, station_ID, limit, interval): """ Helper method for station_X_history functions. """ params = {'id': station_ID, 'type': interval, 'lang': self._language} if limit is not None: params['cnt'] = limit uri = http_client.HttpClient.to_url(STATION_WEATHER_HISTORY_URL, self._API_key, self._subscription_type, self._use_ssl) _, json_data = self._wapi.cacheable_get_json(uri, params=params) station_history = \ self._parsers['station_history'].parse_JSON(json_data) if station_history is not None: station_history.set_station_ID(station_ID) station_history.set_interval(interval) return station_history
[ "def", "_retrieve_station_history", "(", "self", ",", "station_ID", ",", "limit", ",", "interval", ")", ":", "params", "=", "{", "'id'", ":", "station_ID", ",", "'type'", ":", "interval", ",", "'lang'", ":", "self", ".", "_language", "}", "if", "limit", ...
Helper method for station_X_history functions.
[ "Helper", "method", "for", "station_X_history", "functions", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L1069-L1086
train
206,857
csparpa/pyowm
pyowm/weatherapi25/owm25.py
OWM25.uvindex_forecast_around_coords
def uvindex_forecast_around_coords(self, lat, lon): """ Queries the OWM Weather API for forecast Ultra Violet values in the next 8 days in the surroundings of the provided geocoordinates. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values """ geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat} json_data = self._uvapi.get_uvi_forecast(params) uvindex_list = self._parsers['uvindex_list'].parse_JSON(json_data) return uvindex_list
python
def uvindex_forecast_around_coords(self, lat, lon): """ Queries the OWM Weather API for forecast Ultra Violet values in the next 8 days in the surroundings of the provided geocoordinates. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values """ geo.assert_is_lon(lon) geo.assert_is_lat(lat) params = {'lon': lon, 'lat': lat} json_data = self._uvapi.get_uvi_forecast(params) uvindex_list = self._parsers['uvindex_list'].parse_JSON(json_data) return uvindex_list
[ "def", "uvindex_forecast_around_coords", "(", "self", ",", "lat", ",", "lon", ")", ":", "geo", ".", "assert_is_lon", "(", "lon", ")", "geo", ".", "assert_is_lat", "(", "lat", ")", "params", "=", "{", "'lon'", ":", "lon", ",", "'lat'", ":", "lat", "}", ...
Queries the OWM Weather API for forecast Ultra Violet values in the next 8 days in the surroundings of the provided geocoordinates. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
[ "Queries", "the", "OWM", "Weather", "API", "for", "forecast", "Ultra", "Violet", "values", "in", "the", "next", "8", "days", "in", "the", "surroundings", "of", "the", "provided", "geocoordinates", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L1113-L1132
train
206,858
csparpa/pyowm
pyowm/weatherapi25/owm25.py
OWM25.uvindex_history_around_coords
def uvindex_history_around_coords(self, lat, lon, start, end=None): """ Queries the OWM Weather API for UV index historical values in the surroundings of the provided geocoordinates and in the specified time frame. If the end of the time frame is not provided, that is intended to be the current datetime. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the time value for the start query boundary :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``, in which case the current datetime will be used) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values """ geo.assert_is_lon(lon) geo.assert_is_lat(lat) assert start is not None start = timeformatutils.timeformat(start, 'unix') if end is None: end = timeutils.now(timeformat='unix') else: end = timeformatutils.timeformat(end, 'unix') params = {'lon': lon, 'lat': lat, 'start': start, 'end': end} json_data = self._uvapi.get_uvi_history(params) uvindex_list = self._parsers['uvindex_list'].parse_JSON(json_data) return uvindex_list
python
def uvindex_history_around_coords(self, lat, lon, start, end=None): """ Queries the OWM Weather API for UV index historical values in the surroundings of the provided geocoordinates and in the specified time frame. If the end of the time frame is not provided, that is intended to be the current datetime. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the time value for the start query boundary :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``, in which case the current datetime will be used) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values """ geo.assert_is_lon(lon) geo.assert_is_lat(lat) assert start is not None start = timeformatutils.timeformat(start, 'unix') if end is None: end = timeutils.now(timeformat='unix') else: end = timeformatutils.timeformat(end, 'unix') params = {'lon': lon, 'lat': lat, 'start': start, 'end': end} json_data = self._uvapi.get_uvi_history(params) uvindex_list = self._parsers['uvindex_list'].parse_JSON(json_data) return uvindex_list
[ "def", "uvindex_history_around_coords", "(", "self", ",", "lat", ",", "lon", ",", "start", ",", "end", "=", "None", ")", ":", "geo", ".", "assert_is_lon", "(", "lon", ")", "geo", ".", "assert_is_lat", "(", "lat", ")", "assert", "start", "is", "not", "N...
Queries the OWM Weather API for UV index historical values in the surroundings of the provided geocoordinates and in the specified time frame. If the end of the time frame is not provided, that is intended to be the current datetime. :param lat: the location's latitude, must be between -90.0 and 90.0 :type lat: int/float :param lon: the location's longitude, must be between -180.0 and 180.0 :type lon: int/float :param start: the object conveying the time value for the start query boundary :type start: int, ``datetime.datetime`` or ISO8601-formatted string :param end: the object conveying the time value for the end query boundary (defaults to ``None``, in which case the current datetime will be used) :type end: int, ``datetime.datetime`` or ISO8601-formatted string :return: a list of *UVIndex* instances or empty list if data is not available :raises: *ParseResponseException* when OWM Weather API responses' data cannot be parsed, *APICallException* when OWM Weather API can not be reached, *ValueError* for wrong input values
[ "Queries", "the", "OWM", "Weather", "API", "for", "UV", "index", "historical", "values", "in", "the", "surroundings", "of", "the", "provided", "geocoordinates", "and", "in", "the", "specified", "time", "frame", ".", "If", "the", "end", "of", "the", "time", ...
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L1134-L1167
train
206,859
csparpa/pyowm
pyowm/utils/temputils.py
kelvin_dict_to
def kelvin_dict_to(d, target_temperature_unit): """ Converts all the values in a dict from Kelvin temperatures to the specified temperature format. :param d: the dictionary containing Kelvin temperature values :type d: dict :param target_temperature_unit: the target temperature unit, may be: 'celsius' or 'fahrenheit' :type target_temperature_unit: str :returns: a dict with the same keys as the input dict and converted temperature values as values :raises: *ValueError* when unknown target temperature units are provided """ if target_temperature_unit == 'kelvin': return d elif target_temperature_unit == 'celsius': return {key: kelvin_to_celsius(d[key]) for key in d} elif target_temperature_unit == 'fahrenheit': return {key: kelvin_to_fahrenheit(d[key]) for key in d} else: raise ValueError("Invalid value for target temperature conversion \ unit")
python
def kelvin_dict_to(d, target_temperature_unit): """ Converts all the values in a dict from Kelvin temperatures to the specified temperature format. :param d: the dictionary containing Kelvin temperature values :type d: dict :param target_temperature_unit: the target temperature unit, may be: 'celsius' or 'fahrenheit' :type target_temperature_unit: str :returns: a dict with the same keys as the input dict and converted temperature values as values :raises: *ValueError* when unknown target temperature units are provided """ if target_temperature_unit == 'kelvin': return d elif target_temperature_unit == 'celsius': return {key: kelvin_to_celsius(d[key]) for key in d} elif target_temperature_unit == 'fahrenheit': return {key: kelvin_to_fahrenheit(d[key]) for key in d} else: raise ValueError("Invalid value for target temperature conversion \ unit")
[ "def", "kelvin_dict_to", "(", "d", ",", "target_temperature_unit", ")", ":", "if", "target_temperature_unit", "==", "'kelvin'", ":", "return", "d", "elif", "target_temperature_unit", "==", "'celsius'", ":", "return", "{", "key", ":", "kelvin_to_celsius", "(", "d",...
Converts all the values in a dict from Kelvin temperatures to the specified temperature format. :param d: the dictionary containing Kelvin temperature values :type d: dict :param target_temperature_unit: the target temperature unit, may be: 'celsius' or 'fahrenheit' :type target_temperature_unit: str :returns: a dict with the same keys as the input dict and converted temperature values as values :raises: *ValueError* when unknown target temperature units are provided
[ "Converts", "all", "the", "values", "in", "a", "dict", "from", "Kelvin", "temperatures", "to", "the", "specified", "temperature", "format", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/temputils.py#L14-L37
train
206,860
csparpa/pyowm
pyowm/utils/temputils.py
kelvin_to_celsius
def kelvin_to_celsius(kelvintemp): """ Converts a numeric temperature from Kelvin degrees to Celsius degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Celsius temperature :raises: *TypeError* when bad argument types are provided """ if kelvintemp < 0: raise ValueError(__name__ + \ ": negative temperature values not allowed") celsiustemp = kelvintemp - KELVIN_OFFSET return float("{0:.2f}".format(celsiustemp))
python
def kelvin_to_celsius(kelvintemp): """ Converts a numeric temperature from Kelvin degrees to Celsius degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Celsius temperature :raises: *TypeError* when bad argument types are provided """ if kelvintemp < 0: raise ValueError(__name__ + \ ": negative temperature values not allowed") celsiustemp = kelvintemp - KELVIN_OFFSET return float("{0:.2f}".format(celsiustemp))
[ "def", "kelvin_to_celsius", "(", "kelvintemp", ")", ":", "if", "kelvintemp", "<", "0", ":", "raise", "ValueError", "(", "__name__", "+", "\": negative temperature values not allowed\"", ")", "celsiustemp", "=", "kelvintemp", "-", "KELVIN_OFFSET", "return", "float", ...
Converts a numeric temperature from Kelvin degrees to Celsius degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Celsius temperature :raises: *TypeError* when bad argument types are provided
[ "Converts", "a", "numeric", "temperature", "from", "Kelvin", "degrees", "to", "Celsius", "degrees" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/temputils.py#L40-L54
train
206,861
csparpa/pyowm
pyowm/utils/temputils.py
kelvin_to_fahrenheit
def kelvin_to_fahrenheit(kelvintemp): """ Converts a numeric temperature from Kelvin degrees to Fahrenheit degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Fahrenheit temperature :raises: *TypeError* when bad argument types are provided """ if kelvintemp < 0: raise ValueError(__name__ + \ ": negative temperature values not allowed") fahrenheittemp = (kelvintemp - KELVIN_OFFSET) * \ FAHRENHEIT_DEGREE_SCALE + FAHRENHEIT_OFFSET return float("{0:.2f}".format(fahrenheittemp))
python
def kelvin_to_fahrenheit(kelvintemp): """ Converts a numeric temperature from Kelvin degrees to Fahrenheit degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Fahrenheit temperature :raises: *TypeError* when bad argument types are provided """ if kelvintemp < 0: raise ValueError(__name__ + \ ": negative temperature values not allowed") fahrenheittemp = (kelvintemp - KELVIN_OFFSET) * \ FAHRENHEIT_DEGREE_SCALE + FAHRENHEIT_OFFSET return float("{0:.2f}".format(fahrenheittemp))
[ "def", "kelvin_to_fahrenheit", "(", "kelvintemp", ")", ":", "if", "kelvintemp", "<", "0", ":", "raise", "ValueError", "(", "__name__", "+", "\": negative temperature values not allowed\"", ")", "fahrenheittemp", "=", "(", "kelvintemp", "-", "KELVIN_OFFSET", ")", "*"...
Converts a numeric temperature from Kelvin degrees to Fahrenheit degrees :param kelvintemp: the Kelvin temperature :type kelvintemp: int/long/float :returns: the float Fahrenheit temperature :raises: *TypeError* when bad argument types are provided
[ "Converts", "a", "numeric", "temperature", "from", "Kelvin", "degrees", "to", "Fahrenheit", "degrees" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/temputils.py#L57-L72
train
206,862
csparpa/pyowm
pyowm/weatherapi25/cityidregistry.py
CityIDRegistry.id_for
def id_for(self, city_name): """ Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up :type city_name: str :returns: a long or ``None`` if the lookup fails """ line = self._lookup_line_by_city_name(city_name) return int(line.split(",")[1]) if line is not None else None
python
def id_for(self, city_name): """ Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up :type city_name: str :returns: a long or ``None`` if the lookup fails """ line = self._lookup_line_by_city_name(city_name) return int(line.split(",")[1]) if line is not None else None
[ "def", "id_for", "(", "self", ",", "city_name", ")", ":", "line", "=", "self", ".", "_lookup_line_by_city_name", "(", "city_name", ")", "return", "int", "(", "line", ".", "split", "(", "\",\"", ")", "[", "1", "]", ")", "if", "line", "is", "not", "Non...
Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up :type city_name: str :returns: a long or ``None`` if the lookup fails
[ "Returns", "the", "long", "ID", "corresponding", "to", "the", "first", "city", "found", "that", "matches", "the", "provided", "city", "name", ".", "The", "lookup", "is", "case", "insensitive", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/cityidregistry.py#L33-L47
train
206,863
csparpa/pyowm
pyowm/utils/weatherutils.py
find_closest_weather
def find_closest_weather(weathers_list, unixtime): """ Extracts from the provided list of Weather objects the item which is closest in time to the provided UNIXtime. :param weathers_list: a list of *Weather* objects :type weathers_list: list :param unixtime: a UNIX time :type unixtime: int :returns: the *Weather* object which is closest in time or ``None`` if the list is empty """ if not weathers_list: return None if not is_in_coverage(unixtime, weathers_list): raise api_response_error.NotFoundError('Error: the specified time is ' + \ 'not included in the weather coverage range') closest_weather = weathers_list[0] time_distance = abs(closest_weather.get_reference_time() - unixtime) for weather in weathers_list: if abs(weather.get_reference_time() - unixtime) < time_distance: time_distance = abs(weather.get_reference_time() - unixtime) closest_weather = weather return closest_weather
python
def find_closest_weather(weathers_list, unixtime): """ Extracts from the provided list of Weather objects the item which is closest in time to the provided UNIXtime. :param weathers_list: a list of *Weather* objects :type weathers_list: list :param unixtime: a UNIX time :type unixtime: int :returns: the *Weather* object which is closest in time or ``None`` if the list is empty """ if not weathers_list: return None if not is_in_coverage(unixtime, weathers_list): raise api_response_error.NotFoundError('Error: the specified time is ' + \ 'not included in the weather coverage range') closest_weather = weathers_list[0] time_distance = abs(closest_weather.get_reference_time() - unixtime) for weather in weathers_list: if abs(weather.get_reference_time() - unixtime) < time_distance: time_distance = abs(weather.get_reference_time() - unixtime) closest_weather = weather return closest_weather
[ "def", "find_closest_weather", "(", "weathers_list", ",", "unixtime", ")", ":", "if", "not", "weathers_list", ":", "return", "None", "if", "not", "is_in_coverage", "(", "unixtime", ",", "weathers_list", ")", ":", "raise", "api_response_error", ".", "NotFoundError"...
Extracts from the provided list of Weather objects the item which is closest in time to the provided UNIXtime. :param weathers_list: a list of *Weather* objects :type weathers_list: list :param unixtime: a UNIX time :type unixtime: int :returns: the *Weather* object which is closest in time or ``None`` if the list is empty
[ "Extracts", "from", "the", "provided", "list", "of", "Weather", "objects", "the", "item", "which", "is", "closest", "in", "time", "to", "the", "provided", "UNIXtime", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/weatherutils.py#L96-L119
train
206,864
csparpa/pyowm
pyowm/commons/image.py
Image.persist
def persist(self, path_to_file): """ Saves the image to disk on a file :param path_to_file: path to the target file :type path_to_file: str :return: `None` """ with open(path_to_file, 'wb') as f: f.write(self.data)
python
def persist(self, path_to_file): """ Saves the image to disk on a file :param path_to_file: path to the target file :type path_to_file: str :return: `None` """ with open(path_to_file, 'wb') as f: f.write(self.data)
[ "def", "persist", "(", "self", ",", "path_to_file", ")", ":", "with", "open", "(", "path_to_file", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "data", ")" ]
Saves the image to disk on a file :param path_to_file: path to the target file :type path_to_file: str :return: `None`
[ "Saves", "the", "image", "to", "disk", "on", "a", "file" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/image.py#L22-L31
train
206,865
csparpa/pyowm
pyowm/commons/image.py
Image.load
def load(cls, path_to_file): """ Loads the image data from a file on disk and tries to guess the image MIME type :param path_to_file: path to the source file :type path_to_file: str :return: a `pyowm.image.Image` instance """ import mimetypes mimetypes.init() mime = mimetypes.guess_type('file://%s' % path_to_file)[0] img_type = ImageTypeEnum.lookup_by_mime_type(mime) with open(path_to_file, 'rb') as f: data = f.read() return Image(data, image_type=img_type)
python
def load(cls, path_to_file): """ Loads the image data from a file on disk and tries to guess the image MIME type :param path_to_file: path to the source file :type path_to_file: str :return: a `pyowm.image.Image` instance """ import mimetypes mimetypes.init() mime = mimetypes.guess_type('file://%s' % path_to_file)[0] img_type = ImageTypeEnum.lookup_by_mime_type(mime) with open(path_to_file, 'rb') as f: data = f.read() return Image(data, image_type=img_type)
[ "def", "load", "(", "cls", ",", "path_to_file", ")", ":", "import", "mimetypes", "mimetypes", ".", "init", "(", ")", "mime", "=", "mimetypes", ".", "guess_type", "(", "'file://%s'", "%", "path_to_file", ")", "[", "0", "]", "img_type", "=", "ImageTypeEnum",...
Loads the image data from a file on disk and tries to guess the image MIME type :param path_to_file: path to the source file :type path_to_file: str :return: a `pyowm.image.Image` instance
[ "Loads", "the", "image", "data", "from", "a", "file", "on", "disk", "and", "tries", "to", "guess", "the", "image", "MIME", "type" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/image.py#L34-L48
train
206,866
csparpa/pyowm
pyowm/utils/timeformatutils.py
timeformat
def timeformat(timeobject, timeformat): """ Formats the specified time object to the target format type. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00`` :param timeformat: the target format for the time conversion. May be: '*unix*' (outputs an int UNIXtime), '*date*' (outputs a ``datetime.datetime`` object) or '*iso*' (outputs an ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00``) :type timeformat: str :returns: the formatted time :raises: ValueError when unknown timeformat switches are provided or when negative time values are provided """ if timeformat == "unix": return to_UNIXtime(timeobject) elif timeformat == "iso": return to_ISO8601(timeobject) elif timeformat == "date": return to_date(timeobject) else: raise ValueError("Invalid value for timeformat parameter")
python
def timeformat(timeobject, timeformat): """ Formats the specified time object to the target format type. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00`` :param timeformat: the target format for the time conversion. May be: '*unix*' (outputs an int UNIXtime), '*date*' (outputs a ``datetime.datetime`` object) or '*iso*' (outputs an ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00``) :type timeformat: str :returns: the formatted time :raises: ValueError when unknown timeformat switches are provided or when negative time values are provided """ if timeformat == "unix": return to_UNIXtime(timeobject) elif timeformat == "iso": return to_ISO8601(timeobject) elif timeformat == "date": return to_date(timeobject) else: raise ValueError("Invalid value for timeformat parameter")
[ "def", "timeformat", "(", "timeobject", ",", "timeformat", ")", ":", "if", "timeformat", "==", "\"unix\"", ":", "return", "to_UNIXtime", "(", "timeobject", ")", "elif", "timeformat", "==", "\"iso\"", ":", "return", "to_ISO8601", "(", "timeobject", ")", "elif",...
Formats the specified time object to the target format type. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00`` :param timeformat: the target format for the time conversion. May be: '*unix*' (outputs an int UNIXtime), '*date*' (outputs a ``datetime.datetime`` object) or '*iso*' (outputs an ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00``) :type timeformat: str :returns: the formatted time :raises: ValueError when unknown timeformat switches are provided or when negative time values are provided
[ "Formats", "the", "specified", "time", "object", "to", "the", "target", "format", "type", "." ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/timeformatutils.py#L24-L47
train
206,867
csparpa/pyowm
pyowm/weatherapi25/historian.py
Historian.temperature_series
def temperature_series(self, unit='kelvin'): """Returns the temperature time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a list of tuples :raises: ValueError when invalid values are provided for the unit of measure """ if unit not in ('kelvin', 'celsius', 'fahrenheit'): raise ValueError("Invalid value for parameter 'unit'") result = [] for tstamp in self._station_history.get_measurements(): t = self._station_history.get_measurements()[tstamp]['temperature'] if unit == 'kelvin': temp = t if unit == 'celsius': temp = temputils.kelvin_to_celsius(t) if unit == 'fahrenheit': temp = temputils.kelvin_to_fahrenheit(t) result.append((tstamp, temp)) return result
python
def temperature_series(self, unit='kelvin'): """Returns the temperature time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a list of tuples :raises: ValueError when invalid values are provided for the unit of measure """ if unit not in ('kelvin', 'celsius', 'fahrenheit'): raise ValueError("Invalid value for parameter 'unit'") result = [] for tstamp in self._station_history.get_measurements(): t = self._station_history.get_measurements()[tstamp]['temperature'] if unit == 'kelvin': temp = t if unit == 'celsius': temp = temputils.kelvin_to_celsius(t) if unit == 'fahrenheit': temp = temputils.kelvin_to_fahrenheit(t) result.append((tstamp, temp)) return result
[ "def", "temperature_series", "(", "self", ",", "unit", "=", "'kelvin'", ")", ":", "if", "unit", "not", "in", "(", "'kelvin'", ",", "'celsius'", ",", "'fahrenheit'", ")", ":", "raise", "ValueError", "(", "\"Invalid value for parameter 'unit'\"", ")", "result", ...
Returns the temperature time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :type unit: str :returns: a list of tuples :raises: ValueError when invalid values are provided for the unit of measure
[ "Returns", "the", "temperature", "time", "series", "relative", "to", "the", "meteostation", "in", "the", "form", "of", "a", "list", "of", "tuples", "each", "one", "containing", "the", "couple", "timestamp", "-", "value" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L32-L56
train
206,868
csparpa/pyowm
pyowm/weatherapi25/historian.py
Historian.humidity_series
def humidity_series(self): """Returns the humidity time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(tstamp, \ self._station_history.get_measurements()[tstamp]['humidity']) \ for tstamp in self._station_history.get_measurements()]
python
def humidity_series(self): """Returns the humidity time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(tstamp, \ self._station_history.get_measurements()[tstamp]['humidity']) \ for tstamp in self._station_history.get_measurements()]
[ "def", "humidity_series", "(", "self", ")", ":", "return", "[", "(", "tstamp", ",", "self", ".", "_station_history", ".", "get_measurements", "(", ")", "[", "tstamp", "]", "[", "'humidity'", "]", ")", "for", "tstamp", "in", "self", ".", "_station_history",...
Returns the humidity time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
[ "Returns", "the", "humidity", "time", "series", "relative", "to", "the", "meteostation", "in", "the", "form", "of", "a", "list", "of", "tuples", "each", "one", "containing", "the", "couple", "timestamp", "-", "value" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L58-L67
train
206,869
csparpa/pyowm
pyowm/weatherapi25/historian.py
Historian.pressure_series
def pressure_series(self): """Returns the atmospheric pressure time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(tstamp, \ self._station_history.get_measurements()[tstamp]['pressure']) \ for tstamp in self._station_history.get_measurements()]
python
def pressure_series(self): """Returns the atmospheric pressure time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(tstamp, \ self._station_history.get_measurements()[tstamp]['pressure']) \ for tstamp in self._station_history.get_measurements()]
[ "def", "pressure_series", "(", "self", ")", ":", "return", "[", "(", "tstamp", ",", "self", ".", "_station_history", ".", "get_measurements", "(", ")", "[", "tstamp", "]", "[", "'pressure'", "]", ")", "for", "tstamp", "in", "self", ".", "_station_history",...
Returns the atmospheric pressure time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
[ "Returns", "the", "atmospheric", "pressure", "time", "series", "relative", "to", "the", "meteostation", "in", "the", "form", "of", "a", "list", "of", "tuples", "each", "one", "containing", "the", "couple", "timestamp", "-", "value" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L69-L78
train
206,870
csparpa/pyowm
pyowm/weatherapi25/historian.py
Historian.rain_series
def rain_series(self): """Returns the precipitation time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(tstamp, \ self._station_history.get_measurements()[tstamp]['rain']) \ for tstamp in self._station_history.get_measurements()]
python
def rain_series(self): """Returns the precipitation time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(tstamp, \ self._station_history.get_measurements()[tstamp]['rain']) \ for tstamp in self._station_history.get_measurements()]
[ "def", "rain_series", "(", "self", ")", ":", "return", "[", "(", "tstamp", ",", "self", ".", "_station_history", ".", "get_measurements", "(", ")", "[", "tstamp", "]", "[", "'rain'", "]", ")", "for", "tstamp", "in", "self", ".", "_station_history", ".", ...
Returns the precipitation time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
[ "Returns", "the", "precipitation", "time", "series", "relative", "to", "the", "meteostation", "in", "the", "form", "of", "a", "list", "of", "tuples", "each", "one", "containing", "the", "couple", "timestamp", "-", "value" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L80-L89
train
206,871
csparpa/pyowm
pyowm/weatherapi25/historian.py
Historian.wind_series
def wind_series(self): """Returns the wind speed time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(timestamp, \ self._station_history.get_measurements()[timestamp]['wind']) \ for timestamp in self._station_history.get_measurements()]
python
def wind_series(self): """Returns the wind speed time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(timestamp, \ self._station_history.get_measurements()[timestamp]['wind']) \ for timestamp in self._station_history.get_measurements()]
[ "def", "wind_series", "(", "self", ")", ":", "return", "[", "(", "timestamp", ",", "self", ".", "_station_history", ".", "get_measurements", "(", ")", "[", "timestamp", "]", "[", "'wind'", "]", ")", "for", "timestamp", "in", "self", ".", "_station_history"...
Returns the wind speed time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
[ "Returns", "the", "wind", "speed", "time", "series", "relative", "to", "the", "meteostation", "in", "the", "form", "of", "a", "list", "of", "tuples", "each", "one", "containing", "the", "couple", "timestamp", "-", "value" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L91-L100
train
206,872
csparpa/pyowm
pyowm/weatherapi25/historian.py
Historian.max_rain
def max_rain(self): """Returns a tuple containing the max value in the rain series preceeded by its timestamp :returns: a tuple :raises: ValueError when the measurement series is empty """ return max(self._purge_none_samples(self.rain_series()), key=lambda item:item[1])
python
def max_rain(self): """Returns a tuple containing the max value in the rain series preceeded by its timestamp :returns: a tuple :raises: ValueError when the measurement series is empty """ return max(self._purge_none_samples(self.rain_series()), key=lambda item:item[1])
[ "def", "max_rain", "(", "self", ")", ":", "return", "max", "(", "self", ".", "_purge_none_samples", "(", "self", ".", "rain_series", "(", ")", ")", ",", "key", "=", "lambda", "item", ":", "item", "[", "1", "]", ")" ]
Returns a tuple containing the max value in the rain series preceeded by its timestamp :returns: a tuple :raises: ValueError when the measurement series is empty
[ "Returns", "a", "tuple", "containing", "the", "max", "value", "in", "the", "rain", "series", "preceeded", "by", "its", "timestamp" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L228-L236
train
206,873
csparpa/pyowm
pyowm/uvindexapi30/uv_client.py
UltraVioletHttpClient.get_uvi
def get_uvi(self, params_dict): """ Invokes the UV Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) params = dict(lat=lat, lon=lon) # build request URL uri = http_client.HttpClient.to_url(UV_INDEX_URL, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri, params=params) return json_data
python
def get_uvi(self, params_dict): """ Invokes the UV Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) params = dict(lat=lat, lon=lon) # build request URL uri = http_client.HttpClient.to_url(UV_INDEX_URL, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri, params=params) return json_data
[ "def", "get_uvi", "(", "self", ",", "params_dict", ")", ":", "lat", "=", "str", "(", "params_dict", "[", "'lat'", "]", ")", "lon", "=", "str", "(", "params_dict", "[", "'lon'", "]", ")", "params", "=", "dict", "(", "lat", "=", "lat", ",", "lon", ...
Invokes the UV Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError*
[ "Invokes", "the", "UV", "Index", "endpoint" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/uvindexapi30/uv_client.py#L39-L55
train
206,874
csparpa/pyowm
pyowm/uvindexapi30/uv_client.py
UltraVioletHttpClient.get_uvi_history
def get_uvi_history(self, params_dict): """ Invokes the UV Index History endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) start = str(params_dict['start']) end = str(params_dict['end']) params = dict(lat=lat, lon=lon, start=start, end=end) # build request URL uri = http_client.HttpClient.to_url(UV_INDEX_HISTORY_URL, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri, params=params) return json_data
python
def get_uvi_history(self, params_dict): """ Invokes the UV Index History endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) start = str(params_dict['start']) end = str(params_dict['end']) params = dict(lat=lat, lon=lon, start=start, end=end) # build request URL uri = http_client.HttpClient.to_url(UV_INDEX_HISTORY_URL, self._API_key, None) _, json_data = self._client.cacheable_get_json(uri, params=params) return json_data
[ "def", "get_uvi_history", "(", "self", ",", "params_dict", ")", ":", "lat", "=", "str", "(", "params_dict", "[", "'lat'", "]", ")", "lon", "=", "str", "(", "params_dict", "[", "'lon'", "]", ")", "start", "=", "str", "(", "params_dict", "[", "'start'", ...
Invokes the UV Index History endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError*
[ "Invokes", "the", "UV", "Index", "History", "endpoint" ]
cdd59eb72f32f7238624ceef9b2e2329a5ebd472
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/uvindexapi30/uv_client.py#L77-L97
train
206,875
jonathf/chaospy
chaospy/poly/caller.py
call
def call(poly, args): """ Evaluate a polynomial along specified axes. Args: poly (Poly): Input polynomial. args (numpy.ndarray): Argument to be evaluated. Masked values keeps the variable intact. Returns: (Poly, numpy.ndarray): If masked values are used the Poly is returned. Else an numpy array matching the polynomial's shape is returned. """ args = list(args) # expand args to match dim if len(args) < poly.dim: args = args + [np.nan]*(poly.dim-len(args)) elif len(args) > poly.dim: raise ValueError("too many arguments") # Find and perform substitutions, if any x0, x1 = [], [] for idx, arg in enumerate(args): if isinstance(arg, Poly): poly_ = Poly({ tuple(np.eye(poly.dim)[idx]): np.array(1) }) x0.append(poly_) x1.append(arg) args[idx] = np.nan if x0: poly = call(poly, args) return substitute(poly, x0, x1) # Create masks masks = np.zeros(len(args), dtype=bool) for idx, arg in enumerate(args): if np.ma.is_masked(arg) or np.any(np.isnan(arg)): masks[idx] = True args[idx] = 0 shape = np.array( args[ np.argmax( [np.prod(np.array(arg).shape) for arg in args] ) ] ).shape args = np.array([np.ones(shape, dtype=int)*arg for arg in args]) A = {} for key in poly.keys: key_ = np.array(key)*(1-masks) val = np.outer(poly.A[key], np.prod((args.T**key_).T, \ axis=0)) val = np.reshape(val, poly.shape + tuple(shape)) val = np.where(val != val, 0, val) mkey = tuple(np.array(key)*(masks)) if not mkey in A: A[mkey] = val else: A[mkey] = A[mkey] + val out = Poly(A, poly.dim, None, None) if out.keys and not np.sum(out.keys): out = out.A[out.keys[0]] elif not out.keys: out = np.zeros(out.shape, dtype=out.dtype) return out
python
def call(poly, args): """ Evaluate a polynomial along specified axes. Args: poly (Poly): Input polynomial. args (numpy.ndarray): Argument to be evaluated. Masked values keeps the variable intact. Returns: (Poly, numpy.ndarray): If masked values are used the Poly is returned. Else an numpy array matching the polynomial's shape is returned. """ args = list(args) # expand args to match dim if len(args) < poly.dim: args = args + [np.nan]*(poly.dim-len(args)) elif len(args) > poly.dim: raise ValueError("too many arguments") # Find and perform substitutions, if any x0, x1 = [], [] for idx, arg in enumerate(args): if isinstance(arg, Poly): poly_ = Poly({ tuple(np.eye(poly.dim)[idx]): np.array(1) }) x0.append(poly_) x1.append(arg) args[idx] = np.nan if x0: poly = call(poly, args) return substitute(poly, x0, x1) # Create masks masks = np.zeros(len(args), dtype=bool) for idx, arg in enumerate(args): if np.ma.is_masked(arg) or np.any(np.isnan(arg)): masks[idx] = True args[idx] = 0 shape = np.array( args[ np.argmax( [np.prod(np.array(arg).shape) for arg in args] ) ] ).shape args = np.array([np.ones(shape, dtype=int)*arg for arg in args]) A = {} for key in poly.keys: key_ = np.array(key)*(1-masks) val = np.outer(poly.A[key], np.prod((args.T**key_).T, \ axis=0)) val = np.reshape(val, poly.shape + tuple(shape)) val = np.where(val != val, 0, val) mkey = tuple(np.array(key)*(masks)) if not mkey in A: A[mkey] = val else: A[mkey] = A[mkey] + val out = Poly(A, poly.dim, None, None) if out.keys and not np.sum(out.keys): out = out.A[out.keys[0]] elif not out.keys: out = np.zeros(out.shape, dtype=out.dtype) return out
[ "def", "call", "(", "poly", ",", "args", ")", ":", "args", "=", "list", "(", "args", ")", "# expand args to match dim", "if", "len", "(", "args", ")", "<", "poly", ".", "dim", ":", "args", "=", "args", "+", "[", "np", ".", "nan", "]", "*", "(", ...
Evaluate a polynomial along specified axes. Args: poly (Poly): Input polynomial. args (numpy.ndarray): Argument to be evaluated. Masked values keeps the variable intact. Returns: (Poly, numpy.ndarray): If masked values are used the Poly is returned. Else an numpy array matching the polynomial's shape is returned.
[ "Evaluate", "a", "polynomial", "along", "specified", "axes", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/caller.py#L7-L82
train
206,876
jonathf/chaospy
chaospy/poly/caller.py
substitute
def substitute(P, x0, x1, V=0): """ Substitute a variable in a polynomial array. Args: P (Poly) : Input data. x0 (Poly, int) : The variable to substitute. Indicated with either unit variable, e.g. `x`, `y`, `z`, etc. or through an integer matching the unit variables dimension, e.g. `x==0`, `y==1`, `z==2`, etc. x1 (Poly) : Simple polynomial to substitute `x0` in `P`. If `x1` is an polynomial array, an error will be raised. Returns: (Poly) : The resulting polynomial (array) where `x0` is replaced with `x1`. Examples: >>> x,y = cp.variable(2) >>> P = cp.Poly([y*y-1, y*x]) >>> print(cp.substitute(P, y, x+1)) [q0^2+2q0, q0^2+q0] With multiple substitutions: >>> print(cp.substitute(P, [x,y], [y,x])) [q0^2-1, q0q1] """ x0,x1 = map(Poly, [x0,x1]) dim = np.max([p.dim for p in [P,x0,x1]]) dtype = chaospy.poly.typing.dtyping(P.dtype, x0.dtype, x1.dtype) P, x0, x1 = [chaospy.poly.dimension.setdim(p, dim) for p in [P,x0,x1]] if x0.shape: x0 = [x for x in x0] else: x0 = [x0] if x1.shape: x1 = [x for x in x1] else: x1 = [x1] # Check if substitution is needed. valid = False C = [x.keys[0].index(1) for x in x0] for key in P.keys: if np.any([key[c] for c in C]): valid = True break if not valid: return P dims = [tuple(np.array(x.keys[0])!=0).index(True) for x in x0] dec = is_decomposed(P) if not dec: P = decompose(P) P = chaospy.poly.dimension.dimsplit(P) shape = P.shape P = [p for p in chaospy.poly.shaping.flatten(P)] for i in range(len(P)): for j in range(len(dims)): if P[i].keys and P[i].keys[0][dims[j]]: P[i] = x1[j].__pow__(P[i].keys[0][dims[j]]) break P = Poly(P, dim, None, dtype) P = chaospy.poly.shaping.reshape(P, shape) P = chaospy.poly.collection.prod(P, 0) if not dec: P = chaospy.poly.collection.sum(P, 0) return P
python
def substitute(P, x0, x1, V=0): """ Substitute a variable in a polynomial array. Args: P (Poly) : Input data. x0 (Poly, int) : The variable to substitute. Indicated with either unit variable, e.g. `x`, `y`, `z`, etc. or through an integer matching the unit variables dimension, e.g. `x==0`, `y==1`, `z==2`, etc. x1 (Poly) : Simple polynomial to substitute `x0` in `P`. If `x1` is an polynomial array, an error will be raised. Returns: (Poly) : The resulting polynomial (array) where `x0` is replaced with `x1`. Examples: >>> x,y = cp.variable(2) >>> P = cp.Poly([y*y-1, y*x]) >>> print(cp.substitute(P, y, x+1)) [q0^2+2q0, q0^2+q0] With multiple substitutions: >>> print(cp.substitute(P, [x,y], [y,x])) [q0^2-1, q0q1] """ x0,x1 = map(Poly, [x0,x1]) dim = np.max([p.dim for p in [P,x0,x1]]) dtype = chaospy.poly.typing.dtyping(P.dtype, x0.dtype, x1.dtype) P, x0, x1 = [chaospy.poly.dimension.setdim(p, dim) for p in [P,x0,x1]] if x0.shape: x0 = [x for x in x0] else: x0 = [x0] if x1.shape: x1 = [x for x in x1] else: x1 = [x1] # Check if substitution is needed. valid = False C = [x.keys[0].index(1) for x in x0] for key in P.keys: if np.any([key[c] for c in C]): valid = True break if not valid: return P dims = [tuple(np.array(x.keys[0])!=0).index(True) for x in x0] dec = is_decomposed(P) if not dec: P = decompose(P) P = chaospy.poly.dimension.dimsplit(P) shape = P.shape P = [p for p in chaospy.poly.shaping.flatten(P)] for i in range(len(P)): for j in range(len(dims)): if P[i].keys and P[i].keys[0][dims[j]]: P[i] = x1[j].__pow__(P[i].keys[0][dims[j]]) break P = Poly(P, dim, None, dtype) P = chaospy.poly.shaping.reshape(P, shape) P = chaospy.poly.collection.prod(P, 0) if not dec: P = chaospy.poly.collection.sum(P, 0) return P
[ "def", "substitute", "(", "P", ",", "x0", ",", "x1", ",", "V", "=", "0", ")", ":", "x0", ",", "x1", "=", "map", "(", "Poly", ",", "[", "x0", ",", "x1", "]", ")", "dim", "=", "np", ".", "max", "(", "[", "p", ".", "dim", "for", "p", "in",...
Substitute a variable in a polynomial array. Args: P (Poly) : Input data. x0 (Poly, int) : The variable to substitute. Indicated with either unit variable, e.g. `x`, `y`, `z`, etc. or through an integer matching the unit variables dimension, e.g. `x==0`, `y==1`, `z==2`, etc. x1 (Poly) : Simple polynomial to substitute `x0` in `P`. If `x1` is an polynomial array, an error will be raised. Returns: (Poly) : The resulting polynomial (array) where `x0` is replaced with `x1`. Examples: >>> x,y = cp.variable(2) >>> P = cp.Poly([y*y-1, y*x]) >>> print(cp.substitute(P, y, x+1)) [q0^2+2q0, q0^2+q0] With multiple substitutions: >>> print(cp.substitute(P, [x,y], [y,x])) [q0^2-1, q0q1]
[ "Substitute", "a", "variable", "in", "a", "polynomial", "array", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/caller.py#L85-L162
train
206,877
jonathf/chaospy
chaospy/poly/caller.py
decompose
def decompose(P): """ Decompose a polynomial to component form. In array missing values are padded with 0 to make decomposition compatible with ``chaospy.sum(Q, 0)``. Args: P (Poly) : Input data. Returns: (Poly) : Decomposed polynomial with `P.shape==(M,)+Q.shape` where `M` is the number of components in `P`. Examples: >>> q = cp.variable() >>> P = cp.Poly([q**2-1, 2]) >>> print(P) [q0^2-1, 2] >>> print(cp.decompose(P)) [[-1, 2], [q0^2, 0]] >>> print(cp.sum(cp.decompose(P), 0)) [q0^2-1, 2] """ P = P.copy() if not P: return P out = [Poly({key:P.A[key]}) for key in P.keys] return Poly(out, None, None, None)
python
def decompose(P): """ Decompose a polynomial to component form. In array missing values are padded with 0 to make decomposition compatible with ``chaospy.sum(Q, 0)``. Args: P (Poly) : Input data. Returns: (Poly) : Decomposed polynomial with `P.shape==(M,)+Q.shape` where `M` is the number of components in `P`. Examples: >>> q = cp.variable() >>> P = cp.Poly([q**2-1, 2]) >>> print(P) [q0^2-1, 2] >>> print(cp.decompose(P)) [[-1, 2], [q0^2, 0]] >>> print(cp.sum(cp.decompose(P), 0)) [q0^2-1, 2] """ P = P.copy() if not P: return P out = [Poly({key:P.A[key]}) for key in P.keys] return Poly(out, None, None, None)
[ "def", "decompose", "(", "P", ")", ":", "P", "=", "P", ".", "copy", "(", ")", "if", "not", "P", ":", "return", "P", "out", "=", "[", "Poly", "(", "{", "key", ":", "P", ".", "A", "[", "key", "]", "}", ")", "for", "key", "in", "P", ".", "...
Decompose a polynomial to component form. In array missing values are padded with 0 to make decomposition compatible with ``chaospy.sum(Q, 0)``. Args: P (Poly) : Input data. Returns: (Poly) : Decomposed polynomial with `P.shape==(M,)+Q.shape` where `M` is the number of components in `P`. Examples: >>> q = cp.variable() >>> P = cp.Poly([q**2-1, 2]) >>> print(P) [q0^2-1, 2] >>> print(cp.decompose(P)) [[-1, 2], [q0^2, 0]] >>> print(cp.sum(cp.decompose(P), 0)) [q0^2-1, 2]
[ "Decompose", "a", "polynomial", "to", "component", "form", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/caller.py#L189-L219
train
206,878
jonathf/chaospy
chaospy/distributions/evaluation/moment.py
evaluate_moment
def evaluate_moment( distribution, k_data, parameters=None, cache=None, ): """ Evaluate raw statistical moments. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate moment of. parameters (:py:data:typing.Any): Collection of parameters to override the default ones in the distribution. cache (:py:data:typing.Any): A collection of previous calculations in case the same distribution turns up on more than one occasion. Returns: The raw statistical moment of ``distribution`` at location ``x_data`` using parameters ``parameters``. """ logger = logging.getLogger(__name__) assert len(k_data) == len(distribution), ( "distribution %s is not of length %d" % (distribution, len(k_data))) assert len(k_data.shape) == 1 if numpy.all(k_data == 0): return 1. def cache_key(distribution): return (tuple(k_data), distribution) if cache is None: cache = {} else: if cache_key(distribution) in cache: return cache[cache_key(distribution)] from .. import baseclass try: parameters = load_parameters( distribution, "_mom", parameters, cache, cache_key) out = distribution._mom(k_data, **parameters) except baseclass.StochasticallyDependentError: logger.warning( "Distribution %s has stochastic dependencies; " "Approximating moments with quadrature.", distribution) from .. import approximation out = approximation.approximate_moment(distribution, k_data) if isinstance(out, numpy.ndarray): out = out.item() cache[cache_key(distribution)] = out return out
python
def evaluate_moment( distribution, k_data, parameters=None, cache=None, ): """ Evaluate raw statistical moments. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate moment of. parameters (:py:data:typing.Any): Collection of parameters to override the default ones in the distribution. cache (:py:data:typing.Any): A collection of previous calculations in case the same distribution turns up on more than one occasion. Returns: The raw statistical moment of ``distribution`` at location ``x_data`` using parameters ``parameters``. """ logger = logging.getLogger(__name__) assert len(k_data) == len(distribution), ( "distribution %s is not of length %d" % (distribution, len(k_data))) assert len(k_data.shape) == 1 if numpy.all(k_data == 0): return 1. def cache_key(distribution): return (tuple(k_data), distribution) if cache is None: cache = {} else: if cache_key(distribution) in cache: return cache[cache_key(distribution)] from .. import baseclass try: parameters = load_parameters( distribution, "_mom", parameters, cache, cache_key) out = distribution._mom(k_data, **parameters) except baseclass.StochasticallyDependentError: logger.warning( "Distribution %s has stochastic dependencies; " "Approximating moments with quadrature.", distribution) from .. import approximation out = approximation.approximate_moment(distribution, k_data) if isinstance(out, numpy.ndarray): out = out.item() cache[cache_key(distribution)] = out return out
[ "def", "evaluate_moment", "(", "distribution", ",", "k_data", ",", "parameters", "=", "None", ",", "cache", "=", "None", ",", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "assert", "len", "(", "k_data", ")", "==", "len", ...
Evaluate raw statistical moments. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate moment of. parameters (:py:data:typing.Any): Collection of parameters to override the default ones in the distribution. cache (:py:data:typing.Any): A collection of previous calculations in case the same distribution turns up on more than one occasion. Returns: The raw statistical moment of ``distribution`` at location ``x_data`` using parameters ``parameters``.
[ "Evaluate", "raw", "statistical", "moments", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/moment.py#L47-L108
train
206,879
jonathf/chaospy
chaospy/distributions/operators/multiply.py
mul
def mul(left, right): """ Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side. """ from .mv_mul import MvMul length = max(left, right) if length == 1: return Mul(left, right) return MvMul(left, right)
python
def mul(left, right): """ Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side. """ from .mv_mul import MvMul length = max(left, right) if length == 1: return Mul(left, right) return MvMul(left, right)
[ "def", "mul", "(", "left", ",", "right", ")", ":", "from", ".", "mv_mul", "import", "MvMul", "length", "=", "max", "(", "left", ",", "right", ")", "if", "length", "==", "1", ":", "return", "Mul", "(", "left", ",", "right", ")", "return", "MvMul", ...
Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side.
[ "Distribution", "multiplication", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/multiply.py#L501-L513
train
206,880
jonathf/chaospy
chaospy/distributions/evaluation/dependencies.py
sorted_dependencies
def sorted_dependencies(dist, reverse=False): """ Extract all underlying dependencies from a distribution sorted topologically. Uses depth-first algorithm. See more here: Args: dist (Dist): Distribution to extract dependencies from. reverse (bool): If True, place dependencies in reverse order. Returns: dependencies (List[Dist]): All distribution that ``dist`` is dependent on, sorted topologically, including itself. Examples: >>> dist1 = chaospy.Uniform() >>> dist2 = chaospy.Normal(dist1) >>> print(sorted_dependencies(dist1)) [Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform()] >>> print(sorted_dependencies(dist2)) # doctest: +NORMALIZE_WHITESPACE [Normal(mu=Uniform(lower=0, upper=1), sigma=1), Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform(), Mul(normal(), 1), normal()] >>> dist1 in sorted_dependencies(dist2) True >>> dist2 in sorted_dependencies(dist1) False Raises: DependencyError: If the dependency DAG is cyclic, dependency resolution is not possible. See also: Depth-first algorithm section: https://en.wikipedia.org/wiki/Topological_sorting """ from .. import baseclass collection = [dist] # create DAG as list of nodes and edges: nodes = [dist] edges = [] pool = [dist] while pool: dist = pool.pop() for key in sorted(dist.prm): value = dist.prm[key] if not isinstance(value, baseclass.Dist): continue if (dist, value) not in edges: edges.append((dist, value)) if value not in nodes: nodes.append(value) pool.append(value) # temporary stores used by depth first algorith. permanent_marks = set() temporary_marks = set() def visit(node): """Depth-first topological sort algorithm.""" if node in permanent_marks: return if node in temporary_marks: raise DependencyError("cycles in dependency structure.") nodes.remove(node) temporary_marks.add(node) for node1, node2 in edges: if node1 is node: visit(node2) temporary_marks.remove(node) permanent_marks.add(node) pool.append(node) # kickstart algorithm. while nodes: node = nodes[0] visit(node) if not reverse: pool = list(reversed(pool)) return pool
python
def sorted_dependencies(dist, reverse=False): """ Extract all underlying dependencies from a distribution sorted topologically. Uses depth-first algorithm. See more here: Args: dist (Dist): Distribution to extract dependencies from. reverse (bool): If True, place dependencies in reverse order. Returns: dependencies (List[Dist]): All distribution that ``dist`` is dependent on, sorted topologically, including itself. Examples: >>> dist1 = chaospy.Uniform() >>> dist2 = chaospy.Normal(dist1) >>> print(sorted_dependencies(dist1)) [Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform()] >>> print(sorted_dependencies(dist2)) # doctest: +NORMALIZE_WHITESPACE [Normal(mu=Uniform(lower=0, upper=1), sigma=1), Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform(), Mul(normal(), 1), normal()] >>> dist1 in sorted_dependencies(dist2) True >>> dist2 in sorted_dependencies(dist1) False Raises: DependencyError: If the dependency DAG is cyclic, dependency resolution is not possible. See also: Depth-first algorithm section: https://en.wikipedia.org/wiki/Topological_sorting """ from .. import baseclass collection = [dist] # create DAG as list of nodes and edges: nodes = [dist] edges = [] pool = [dist] while pool: dist = pool.pop() for key in sorted(dist.prm): value = dist.prm[key] if not isinstance(value, baseclass.Dist): continue if (dist, value) not in edges: edges.append((dist, value)) if value not in nodes: nodes.append(value) pool.append(value) # temporary stores used by depth first algorith. permanent_marks = set() temporary_marks = set() def visit(node): """Depth-first topological sort algorithm.""" if node in permanent_marks: return if node in temporary_marks: raise DependencyError("cycles in dependency structure.") nodes.remove(node) temporary_marks.add(node) for node1, node2 in edges: if node1 is node: visit(node2) temporary_marks.remove(node) permanent_marks.add(node) pool.append(node) # kickstart algorithm. while nodes: node = nodes[0] visit(node) if not reverse: pool = list(reversed(pool)) return pool
[ "def", "sorted_dependencies", "(", "dist", ",", "reverse", "=", "False", ")", ":", "from", ".", ".", "import", "baseclass", "collection", "=", "[", "dist", "]", "# create DAG as list of nodes and edges:", "nodes", "=", "[", "dist", "]", "edges", "=", "[", "]...
Extract all underlying dependencies from a distribution sorted topologically. Uses depth-first algorithm. See more here: Args: dist (Dist): Distribution to extract dependencies from. reverse (bool): If True, place dependencies in reverse order. Returns: dependencies (List[Dist]): All distribution that ``dist`` is dependent on, sorted topologically, including itself. Examples: >>> dist1 = chaospy.Uniform() >>> dist2 = chaospy.Normal(dist1) >>> print(sorted_dependencies(dist1)) [Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform()] >>> print(sorted_dependencies(dist2)) # doctest: +NORMALIZE_WHITESPACE [Normal(mu=Uniform(lower=0, upper=1), sigma=1), Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform(), Mul(normal(), 1), normal()] >>> dist1 in sorted_dependencies(dist2) True >>> dist2 in sorted_dependencies(dist1) False Raises: DependencyError: If the dependency DAG is cyclic, dependency resolution is not possible. See also: Depth-first algorithm section: https://en.wikipedia.org/wiki/Topological_sorting
[ "Extract", "all", "underlying", "dependencies", "from", "a", "distribution", "sorted", "topologically", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/dependencies.py#L5-L99
train
206,881
jonathf/chaospy
chaospy/distributions/evaluation/dependencies.py
get_dependencies
def get_dependencies(*distributions): """ Get underlying dependencies that are shared between distributions. If more than two distributions are provided, any pair-wise dependency between any two distributions are included, implying that an empty set is returned if and only if the distributions are i.i.d. Args: distributions: Distributions to check for dependencies. Returns: dependencies (List[Dist]): Distributions dependency shared at least between at least one pair from ``distributions``. Examples: >>> dist1 = chaospy.Uniform(1, 2) >>> dist2 = chaospy.Uniform(1, 2) * dist1 >>> dist3 = chaospy.Uniform(3, 5) >>> print(chaospy.get_dependencies(dist1, dist2)) [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)] >>> print(chaospy.get_dependencies(dist1, dist3)) [] >>> print(chaospy.get_dependencies(dist2, dist3)) [] >>> print(chaospy.get_dependencies(dist1, dist2, dist3)) [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)] """ from .. import baseclass distributions = [ sorted_dependencies(dist) for dist in distributions if isinstance(dist, baseclass.Dist) ] dependencies = list() for idx, dist1 in enumerate(distributions): for dist2 in distributions[idx+1:]: dependencies.extend([dist for dist in dist1 if dist in dist2]) return sorted(dependencies)
python
def get_dependencies(*distributions): """ Get underlying dependencies that are shared between distributions. If more than two distributions are provided, any pair-wise dependency between any two distributions are included, implying that an empty set is returned if and only if the distributions are i.i.d. Args: distributions: Distributions to check for dependencies. Returns: dependencies (List[Dist]): Distributions dependency shared at least between at least one pair from ``distributions``. Examples: >>> dist1 = chaospy.Uniform(1, 2) >>> dist2 = chaospy.Uniform(1, 2) * dist1 >>> dist3 = chaospy.Uniform(3, 5) >>> print(chaospy.get_dependencies(dist1, dist2)) [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)] >>> print(chaospy.get_dependencies(dist1, dist3)) [] >>> print(chaospy.get_dependencies(dist2, dist3)) [] >>> print(chaospy.get_dependencies(dist1, dist2, dist3)) [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)] """ from .. import baseclass distributions = [ sorted_dependencies(dist) for dist in distributions if isinstance(dist, baseclass.Dist) ] dependencies = list() for idx, dist1 in enumerate(distributions): for dist2 in distributions[idx+1:]: dependencies.extend([dist for dist in dist1 if dist in dist2]) return sorted(dependencies)
[ "def", "get_dependencies", "(", "*", "distributions", ")", ":", "from", ".", ".", "import", "baseclass", "distributions", "=", "[", "sorted_dependencies", "(", "dist", ")", "for", "dist", "in", "distributions", "if", "isinstance", "(", "dist", ",", "baseclass"...
Get underlying dependencies that are shared between distributions. If more than two distributions are provided, any pair-wise dependency between any two distributions are included, implying that an empty set is returned if and only if the distributions are i.i.d. Args: distributions: Distributions to check for dependencies. Returns: dependencies (List[Dist]): Distributions dependency shared at least between at least one pair from ``distributions``. Examples: >>> dist1 = chaospy.Uniform(1, 2) >>> dist2 = chaospy.Uniform(1, 2) * dist1 >>> dist3 = chaospy.Uniform(3, 5) >>> print(chaospy.get_dependencies(dist1, dist2)) [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)] >>> print(chaospy.get_dependencies(dist1, dist3)) [] >>> print(chaospy.get_dependencies(dist2, dist3)) [] >>> print(chaospy.get_dependencies(dist1, dist2, dist3)) [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)]
[ "Get", "underlying", "dependencies", "that", "are", "shared", "between", "distributions", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/dependencies.py#L102-L143
train
206,882
jonathf/chaospy
chaospy/orthogonal/three_terms_recursion.py
orth_ttr
def orth_ttr( order, dist, normed=False, sort="GR", retall=False, cross_truncation=1., **kws): """ Create orthogonal polynomial expansion from three terms recursion formula. Args: order (int): Order of polynomial expansion. dist (Dist): Distribution space where polynomials are orthogonal If dist.ttr exists, it will be used. Must be stochastically independent. normed (bool): If True orthonormal polynomials will be used. sort (str): Polynomial sorting. Same as in basis. retall (bool): If true return numerical stabilized norms as well. Roughly the same as ``cp.E(orth**2, dist)``. cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. only include terms where the exponents ``K`` satisfied the equation ``order >= sum(K**(1/cross_truncation))**cross_truncation``. Returns: (Poly, numpy.ndarray): Orthogonal polynomial expansion and norms of the orthogonal expansion on the form ``E(orth**2, dist)``. Calculated using recurrence coefficients for stability. Examples: >>> Z = chaospy.Normal() >>> print(chaospy.around(chaospy.orth_ttr(4, Z), 4)) [1.0, q0, q0^2-1.0, q0^3-3.0q0, q0^4-6.0q0^2+3.0] """ polynomials, norms, _, _ = chaospy.quad.generate_stieltjes( dist=dist, order=numpy.max(order), retall=True, **kws) if normed: for idx, poly in enumerate(polynomials): polynomials[idx] = poly / numpy.sqrt(norms[:, idx]) norms = norms**0 dim = len(dist) if dim > 1: mv_polynomials = [] mv_norms = [] indices = chaospy.bertran.bindex( start=0, stop=order, dim=dim, sort=sort, cross_truncation=cross_truncation, ) for index in indices: poly = polynomials[index[0]][0] for idx in range(1, dim): poly = poly * polynomials[index[idx]][idx] mv_polynomials.append(poly) if retall: for index in indices: mv_norms.append( numpy.prod([norms[idx, index[idx]] for idx in range(dim)])) else: mv_norms = norms[0] mv_polynomials = polynomials polynomials = chaospy.poly.flatten(chaospy.poly.Poly(mv_polynomials)) if retall: return polynomials, numpy.array(mv_norms) return polynomials
python
def orth_ttr( order, dist, normed=False, sort="GR", retall=False, cross_truncation=1., **kws): """ Create orthogonal polynomial expansion from three terms recursion formula. Args: order (int): Order of polynomial expansion. dist (Dist): Distribution space where polynomials are orthogonal If dist.ttr exists, it will be used. Must be stochastically independent. normed (bool): If True orthonormal polynomials will be used. sort (str): Polynomial sorting. Same as in basis. retall (bool): If true return numerical stabilized norms as well. Roughly the same as ``cp.E(orth**2, dist)``. cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. only include terms where the exponents ``K`` satisfied the equation ``order >= sum(K**(1/cross_truncation))**cross_truncation``. Returns: (Poly, numpy.ndarray): Orthogonal polynomial expansion and norms of the orthogonal expansion on the form ``E(orth**2, dist)``. Calculated using recurrence coefficients for stability. Examples: >>> Z = chaospy.Normal() >>> print(chaospy.around(chaospy.orth_ttr(4, Z), 4)) [1.0, q0, q0^2-1.0, q0^3-3.0q0, q0^4-6.0q0^2+3.0] """ polynomials, norms, _, _ = chaospy.quad.generate_stieltjes( dist=dist, order=numpy.max(order), retall=True, **kws) if normed: for idx, poly in enumerate(polynomials): polynomials[idx] = poly / numpy.sqrt(norms[:, idx]) norms = norms**0 dim = len(dist) if dim > 1: mv_polynomials = [] mv_norms = [] indices = chaospy.bertran.bindex( start=0, stop=order, dim=dim, sort=sort, cross_truncation=cross_truncation, ) for index in indices: poly = polynomials[index[0]][0] for idx in range(1, dim): poly = poly * polynomials[index[idx]][idx] mv_polynomials.append(poly) if retall: for index in indices: mv_norms.append( numpy.prod([norms[idx, index[idx]] for idx in range(dim)])) else: mv_norms = norms[0] mv_polynomials = polynomials polynomials = chaospy.poly.flatten(chaospy.poly.Poly(mv_polynomials)) if retall: return polynomials, numpy.array(mv_norms) return polynomials
[ "def", "orth_ttr", "(", "order", ",", "dist", ",", "normed", "=", "False", ",", "sort", "=", "\"GR\"", ",", "retall", "=", "False", ",", "cross_truncation", "=", "1.", ",", "*", "*", "kws", ")", ":", "polynomials", ",", "norms", ",", "_", ",", "_",...
Create orthogonal polynomial expansion from three terms recursion formula. Args: order (int): Order of polynomial expansion. dist (Dist): Distribution space where polynomials are orthogonal If dist.ttr exists, it will be used. Must be stochastically independent. normed (bool): If True orthonormal polynomials will be used. sort (str): Polynomial sorting. Same as in basis. retall (bool): If true return numerical stabilized norms as well. Roughly the same as ``cp.E(orth**2, dist)``. cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. only include terms where the exponents ``K`` satisfied the equation ``order >= sum(K**(1/cross_truncation))**cross_truncation``. Returns: (Poly, numpy.ndarray): Orthogonal polynomial expansion and norms of the orthogonal expansion on the form ``E(orth**2, dist)``. Calculated using recurrence coefficients for stability. Examples: >>> Z = chaospy.Normal() >>> print(chaospy.around(chaospy.orth_ttr(4, Z), 4)) [1.0, q0, q0^2-1.0, q0^3-3.0q0, q0^4-6.0q0^2+3.0]
[ "Create", "orthogonal", "polynomial", "expansion", "from", "three", "terms", "recursion", "formula", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/orthogonal/three_terms_recursion.py#L58-L130
train
206,883
jonathf/chaospy
chaospy/quad/collection/genz_keister/gk22.py
quad_genz_keister_22
def quad_genz_keister_22 ( order ): """ Hermite Genz-Keister 22 rule. Args: order (int): The quadrature order. Must be in the interval (0, 8). Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Abscissas and weights Examples: >>> abscissas, weights = quad_genz_keister_22(1) >>> print(numpy.around(abscissas, 4)) [-1.7321 0. 1.7321] >>> print(numpy.around(weights, 4)) [0.1667 0.6667 0.1667] """ order = sorted(GENZ_KEISTER_22.keys())[order] abscissas, weights = GENZ_KEISTER_22[order] abscissas = numpy.array(abscissas) weights = numpy.array(weights) weights /= numpy.sum(weights) abscissas *= numpy.sqrt(2) return abscissas, weights
python
def quad_genz_keister_22 ( order ): """ Hermite Genz-Keister 22 rule. Args: order (int): The quadrature order. Must be in the interval (0, 8). Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Abscissas and weights Examples: >>> abscissas, weights = quad_genz_keister_22(1) >>> print(numpy.around(abscissas, 4)) [-1.7321 0. 1.7321] >>> print(numpy.around(weights, 4)) [0.1667 0.6667 0.1667] """ order = sorted(GENZ_KEISTER_22.keys())[order] abscissas, weights = GENZ_KEISTER_22[order] abscissas = numpy.array(abscissas) weights = numpy.array(weights) weights /= numpy.sum(weights) abscissas *= numpy.sqrt(2) return abscissas, weights
[ "def", "quad_genz_keister_22", "(", "order", ")", ":", "order", "=", "sorted", "(", "GENZ_KEISTER_22", ".", "keys", "(", ")", ")", "[", "order", "]", "abscissas", ",", "weights", "=", "GENZ_KEISTER_22", "[", "order", "]", "abscissas", "=", "numpy", ".", ...
Hermite Genz-Keister 22 rule. Args: order (int): The quadrature order. Must be in the interval (0, 8). Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Abscissas and weights Examples: >>> abscissas, weights = quad_genz_keister_22(1) >>> print(numpy.around(abscissas, 4)) [-1.7321 0. 1.7321] >>> print(numpy.around(weights, 4)) [0.1667 0.6667 0.1667]
[ "Hermite", "Genz", "-", "Keister", "22", "rule", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/genz_keister/gk22.py#L7-L35
train
206,884
jonathf/chaospy
chaospy/poly/constructor/identifier.py
identify_core
def identify_core(core): """Identify the polynomial argument.""" for datatype, identifier in { int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, float: _identify_scaler, numpy.float16: _identify_scaler, numpy.float32: _identify_scaler, numpy.float64: _identify_scaler, chaospy.poly.base.Poly: _identify_poly, dict: _identify_dict, numpy.ndarray: _identify_iterable, list: _identify_iterable, tuple: _identify_iterable, }.items(): if isinstance(core, datatype): return identifier(core) raise TypeError( "Poly arg: 'core' is not a valid type " + repr(core))
python
def identify_core(core): """Identify the polynomial argument.""" for datatype, identifier in { int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, float: _identify_scaler, numpy.float16: _identify_scaler, numpy.float32: _identify_scaler, numpy.float64: _identify_scaler, chaospy.poly.base.Poly: _identify_poly, dict: _identify_dict, numpy.ndarray: _identify_iterable, list: _identify_iterable, tuple: _identify_iterable, }.items(): if isinstance(core, datatype): return identifier(core) raise TypeError( "Poly arg: 'core' is not a valid type " + repr(core))
[ "def", "identify_core", "(", "core", ")", ":", "for", "datatype", ",", "identifier", "in", "{", "int", ":", "_identify_scaler", ",", "numpy", ".", "int8", ":", "_identify_scaler", ",", "numpy", ".", "int16", ":", "_identify_scaler", ",", "numpy", ".", "int...
Identify the polynomial argument.
[ "Identify", "the", "polynomial", "argument", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/identifier.py#L11-L33
train
206,885
jonathf/chaospy
chaospy/poly/constructor/identifier.py
_identify_poly
def _identify_poly(core): """Specification for a polynomial.""" return core.A, core.dim, core.shape, core.dtype
python
def _identify_poly(core): """Specification for a polynomial.""" return core.A, core.dim, core.shape, core.dtype
[ "def", "_identify_poly", "(", "core", ")", ":", "return", "core", ".", "A", ",", "core", ".", "dim", ",", "core", ".", "shape", ",", "core", ".", "dtype" ]
Specification for a polynomial.
[ "Specification", "for", "a", "polynomial", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/identifier.py#L41-L43
train
206,886
jonathf/chaospy
chaospy/poly/constructor/identifier.py
_identify_dict
def _identify_dict(core): """Specification for a dictionary.""" if not core: return {}, 1, (), int core = core.copy() key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0] shape = numpy.array(core[key]).shape dtype = numpy.array(core[key]).dtype dim = len(key) return core, dim, shape, dtype
python
def _identify_dict(core): """Specification for a dictionary.""" if not core: return {}, 1, (), int core = core.copy() key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0] shape = numpy.array(core[key]).shape dtype = numpy.array(core[key]).dtype dim = len(key) return core, dim, shape, dtype
[ "def", "_identify_dict", "(", "core", ")", ":", "if", "not", "core", ":", "return", "{", "}", ",", "1", ",", "(", ")", ",", "int", "core", "=", "core", ".", "copy", "(", ")", "key", "=", "sorted", "(", "core", ".", "keys", "(", ")", ",", "key...
Specification for a dictionary.
[ "Specification", "for", "a", "dictionary", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/identifier.py#L46-L56
train
206,887
jonathf/chaospy
chaospy/poly/constructor/identifier.py
_identify_iterable
def _identify_iterable(core): """Specification for a list, tuple, numpy.ndarray.""" if isinstance(core, numpy.ndarray) and not core.shape: return {(0,):core}, 1, (), core.dtype core = [chaospy.poly.base.Poly(a) for a in core] shape = (len(core),) + core[0].shape dtype = chaospy.poly.typing.dtyping(*[_.dtype for _ in core]) dims = numpy.array([a.dim for a in core]) dim = numpy.max(dims) if dim != numpy.min(dims): core = [chaospy.poly.dimension.setdim(a, dim) for a in core] out = {} for idx, core_ in enumerate(core): for key in core_.keys: if not key in out: out[key] = numpy.zeros(shape, dtype=dtype) out[key][idx] = core_.A[key] return out, dim, shape, dtype
python
def _identify_iterable(core): """Specification for a list, tuple, numpy.ndarray.""" if isinstance(core, numpy.ndarray) and not core.shape: return {(0,):core}, 1, (), core.dtype core = [chaospy.poly.base.Poly(a) for a in core] shape = (len(core),) + core[0].shape dtype = chaospy.poly.typing.dtyping(*[_.dtype for _ in core]) dims = numpy.array([a.dim for a in core]) dim = numpy.max(dims) if dim != numpy.min(dims): core = [chaospy.poly.dimension.setdim(a, dim) for a in core] out = {} for idx, core_ in enumerate(core): for key in core_.keys: if not key in out: out[key] = numpy.zeros(shape, dtype=dtype) out[key][idx] = core_.A[key] return out, dim, shape, dtype
[ "def", "_identify_iterable", "(", "core", ")", ":", "if", "isinstance", "(", "core", ",", "numpy", ".", "ndarray", ")", "and", "not", "core", ".", "shape", ":", "return", "{", "(", "0", ",", ")", ":", "core", "}", ",", "1", ",", "(", ")", ",", ...
Specification for a list, tuple, numpy.ndarray.
[ "Specification", "for", "a", "list", "tuple", "numpy", ".", "ndarray", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/identifier.py#L59-L83
train
206,888
jonathf/chaospy
chaospy/descriptives/correlation/pearson.py
Corr
def Corr(poly, dist=None, **kws): """ Correlation matrix of a distribution or polynomial. Args: poly (Poly, Dist): Input to take correlation on. Must have ``len(poly)>=2``. dist (Dist): Defines the space the correlation is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Correlation matrix with ``correlation.shape == poly.shape+poly.shape``. Examples: >>> Z = chaospy.MvNormal([3, 4], [[2, .5], [.5, 1]]) >>> print(numpy.around(chaospy.Corr(Z), 4)) [[1. 0.3536] [0.3536 1. ]] >>> x = chaospy.variable() >>> Z = chaospy.Normal() >>> print(numpy.around(chaospy.Corr([x, x**2], Z), 4)) [[1. 0.] [0. 1.]] """ if isinstance(poly, distributions.Dist): poly, dist = polynomials.variable(len(poly)), poly else: poly = polynomials.Poly(poly) cov = Cov(poly, dist, **kws) var = numpy.diag(cov) vvar = numpy.sqrt(numpy.outer(var, var)) return numpy.where(vvar > 0, cov/vvar, 0)
python
def Corr(poly, dist=None, **kws): """ Correlation matrix of a distribution or polynomial. Args: poly (Poly, Dist): Input to take correlation on. Must have ``len(poly)>=2``. dist (Dist): Defines the space the correlation is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Correlation matrix with ``correlation.shape == poly.shape+poly.shape``. Examples: >>> Z = chaospy.MvNormal([3, 4], [[2, .5], [.5, 1]]) >>> print(numpy.around(chaospy.Corr(Z), 4)) [[1. 0.3536] [0.3536 1. ]] >>> x = chaospy.variable() >>> Z = chaospy.Normal() >>> print(numpy.around(chaospy.Corr([x, x**2], Z), 4)) [[1. 0.] [0. 1.]] """ if isinstance(poly, distributions.Dist): poly, dist = polynomials.variable(len(poly)), poly else: poly = polynomials.Poly(poly) cov = Cov(poly, dist, **kws) var = numpy.diag(cov) vvar = numpy.sqrt(numpy.outer(var, var)) return numpy.where(vvar > 0, cov/vvar, 0)
[ "def", "Corr", "(", "poly", ",", "dist", "=", "None", ",", "*", "*", "kws", ")", ":", "if", "isinstance", "(", "poly", ",", "distributions", ".", "Dist", ")", ":", "poly", ",", "dist", "=", "polynomials", ".", "variable", "(", "len", "(", "poly", ...
Correlation matrix of a distribution or polynomial. Args: poly (Poly, Dist): Input to take correlation on. Must have ``len(poly)>=2``. dist (Dist): Defines the space the correlation is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Correlation matrix with ``correlation.shape == poly.shape+poly.shape``. Examples: >>> Z = chaospy.MvNormal([3, 4], [[2, .5], [.5, 1]]) >>> print(numpy.around(chaospy.Corr(Z), 4)) [[1. 0.3536] [0.3536 1. ]] >>> x = chaospy.variable() >>> Z = chaospy.Normal() >>> print(numpy.around(chaospy.Corr([x, x**2], Z), 4)) [[1. 0.] [0. 1.]]
[ "Correlation", "matrix", "of", "a", "distribution", "or", "polynomial", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/correlation/pearson.py#L9-L45
train
206,889
jonathf/chaospy
chaospy/distributions/collection/triangle.py
tri_ttr
def tri_ttr(k, a): """ Custom TTR function. Triangle distribution does not have an analytical TTR function, but because of its non-smooth nature, a blind integration scheme will converge very slowly. However, by splitting the integration into two divided at the discontinuity in the derivative, TTR can be made operative. """ from ...quad import quad_clenshaw_curtis q1, w1 = quad_clenshaw_curtis(int(10**3*a), 0, a) q2, w2 = quad_clenshaw_curtis(int(10**3*(1-a)), a, 1) q = numpy.concatenate([q1,q2], 1) w = numpy.concatenate([w1,w2]) w = w*numpy.where(q<a, 2*q/a, 2*(1-q)/(1-a)) from chaospy.poly import variable x = variable() orth = [x*0, x**0] inner = numpy.sum(q*w, -1) norms = [1., 1.] A,B = [],[] for n in range(k): A.append(inner/norms[-1]) B.append(norms[-1]/norms[-2]) orth.append((x-A[-1])*orth[-1]-orth[-2]*B[-1]) y = orth[-1](*q)**2*w inner = numpy.sum(q*y, -1) norms.append(numpy.sum(y, -1)) A, B = numpy.array(A).T[0], numpy.array(B).T return A[-1], B[-1]
python
def tri_ttr(k, a): """ Custom TTR function. Triangle distribution does not have an analytical TTR function, but because of its non-smooth nature, a blind integration scheme will converge very slowly. However, by splitting the integration into two divided at the discontinuity in the derivative, TTR can be made operative. """ from ...quad import quad_clenshaw_curtis q1, w1 = quad_clenshaw_curtis(int(10**3*a), 0, a) q2, w2 = quad_clenshaw_curtis(int(10**3*(1-a)), a, 1) q = numpy.concatenate([q1,q2], 1) w = numpy.concatenate([w1,w2]) w = w*numpy.where(q<a, 2*q/a, 2*(1-q)/(1-a)) from chaospy.poly import variable x = variable() orth = [x*0, x**0] inner = numpy.sum(q*w, -1) norms = [1., 1.] A,B = [],[] for n in range(k): A.append(inner/norms[-1]) B.append(norms[-1]/norms[-2]) orth.append((x-A[-1])*orth[-1]-orth[-2]*B[-1]) y = orth[-1](*q)**2*w inner = numpy.sum(q*y, -1) norms.append(numpy.sum(y, -1)) A, B = numpy.array(A).T[0], numpy.array(B).T return A[-1], B[-1]
[ "def", "tri_ttr", "(", "k", ",", "a", ")", ":", "from", ".", ".", ".", "quad", "import", "quad_clenshaw_curtis", "q1", ",", "w1", "=", "quad_clenshaw_curtis", "(", "int", "(", "10", "**", "3", "*", "a", ")", ",", "0", ",", "a", ")", "q2", ",", ...
Custom TTR function. Triangle distribution does not have an analytical TTR function, but because of its non-smooth nature, a blind integration scheme will converge very slowly. However, by splitting the integration into two divided at the discontinuity in the derivative, TTR can be made operative.
[ "Custom", "TTR", "function", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/collection/triangle.py#L10-L44
train
206,890
jonathf/chaospy
chaospy/descriptives/skewness.py
Skew
def Skew(poly, dist=None, **kws): """ Skewness operator. Element by element 3rd order statistics of a distribution or polynomial. Args: poly (Poly, Dist): Input to take skewness on. dist (Dist): Defines the space the skewness is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Element for element variance along ``poly``, where ``skewness.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.Skew(dist)) [2. 0.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.Skew(poly, dist)) [nan 2. 0. 0.] """ if isinstance(poly, distributions.Dist): x = polynomials.variable(len(poly)) poly, dist = x, poly else: poly = polynomials.Poly(poly) if poly.dim < len(dist): polynomials.setdim(poly, len(dist)) shape = poly.shape poly = polynomials.flatten(poly) m1 = E(poly, dist) m2 = E(poly**2, dist) m3 = E(poly**3, dist) out = (m3-3*m2*m1+2*m1**3)/(m2-m1**2)**1.5 out = numpy.reshape(out, shape) return out
python
def Skew(poly, dist=None, **kws): """ Skewness operator. Element by element 3rd order statistics of a distribution or polynomial. Args: poly (Poly, Dist): Input to take skewness on. dist (Dist): Defines the space the skewness is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Element for element variance along ``poly``, where ``skewness.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.Skew(dist)) [2. 0.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.Skew(poly, dist)) [nan 2. 0. 0.] """ if isinstance(poly, distributions.Dist): x = polynomials.variable(len(poly)) poly, dist = x, poly else: poly = polynomials.Poly(poly) if poly.dim < len(dist): polynomials.setdim(poly, len(dist)) shape = poly.shape poly = polynomials.flatten(poly) m1 = E(poly, dist) m2 = E(poly**2, dist) m3 = E(poly**3, dist) out = (m3-3*m2*m1+2*m1**3)/(m2-m1**2)**1.5 out = numpy.reshape(out, shape) return out
[ "def", "Skew", "(", "poly", ",", "dist", "=", "None", ",", "*", "*", "kws", ")", ":", "if", "isinstance", "(", "poly", ",", "distributions", ".", "Dist", ")", ":", "x", "=", "polynomials", ".", "variable", "(", "len", "(", "poly", ")", ")", "poly...
Skewness operator. Element by element 3rd order statistics of a distribution or polynomial. Args: poly (Poly, Dist): Input to take skewness on. dist (Dist): Defines the space the skewness is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Element for element variance along ``poly``, where ``skewness.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.Skew(dist)) [2. 0.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.Skew(poly, dist)) [nan 2. 0. 0.]
[ "Skewness", "operator", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/skewness.py#L8-L53
train
206,891
jonathf/chaospy
chaospy/distributions/evaluation/forward.py
evaluate_forward
def evaluate_forward( distribution, x_data, parameters=None, cache=None, ): """ Evaluate forward Rosenblatt transformation. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate forward transformation at. parameters (:py:data:typing.Any): Collection of parameters to override the default ones in the distribution. cache (:py:data:typing.Any): A collection of previous calculations in case the same distribution turns up on more than one occasion. Returns: The cumulative distribution values of ``distribution`` at location ``x_data`` using parameters ``parameters``. """ assert len(x_data) == len(distribution), ( "distribution %s is not of length %d" % (distribution, len(x_data))) assert hasattr(distribution, "_cdf"), ( "distribution require the `_cdf` method to function.") cache = cache if cache is not None else {} parameters = load_parameters( distribution, "_cdf", parameters=parameters, cache=cache) # Store cache. cache[distribution] = x_data # Evaluate forward function. out = numpy.zeros(x_data.shape) out[:] = distribution._cdf(x_data, **parameters) return out
python
def evaluate_forward( distribution, x_data, parameters=None, cache=None, ): """ Evaluate forward Rosenblatt transformation. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate forward transformation at. parameters (:py:data:typing.Any): Collection of parameters to override the default ones in the distribution. cache (:py:data:typing.Any): A collection of previous calculations in case the same distribution turns up on more than one occasion. Returns: The cumulative distribution values of ``distribution`` at location ``x_data`` using parameters ``parameters``. """ assert len(x_data) == len(distribution), ( "distribution %s is not of length %d" % (distribution, len(x_data))) assert hasattr(distribution, "_cdf"), ( "distribution require the `_cdf` method to function.") cache = cache if cache is not None else {} parameters = load_parameters( distribution, "_cdf", parameters=parameters, cache=cache) # Store cache. cache[distribution] = x_data # Evaluate forward function. out = numpy.zeros(x_data.shape) out[:] = distribution._cdf(x_data, **parameters) return out
[ "def", "evaluate_forward", "(", "distribution", ",", "x_data", ",", "parameters", "=", "None", ",", "cache", "=", "None", ",", ")", ":", "assert", "len", "(", "x_data", ")", "==", "len", "(", "distribution", ")", ",", "(", "\"distribution %s is not of length...
Evaluate forward Rosenblatt transformation. Args: distribution (Dist): Distribution to evaluate. x_data (numpy.ndarray): Locations for where evaluate forward transformation at. parameters (:py:data:typing.Any): Collection of parameters to override the default ones in the distribution. cache (:py:data:typing.Any): A collection of previous calculations in case the same distribution turns up on more than one occasion. Returns: The cumulative distribution values of ``distribution`` at location ``x_data`` using parameters ``parameters``.
[ "Evaluate", "forward", "Rosenblatt", "transformation", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/forward.py#L32-L74
train
206,892
jonathf/chaospy
chaospy/descriptives/variance.py
Var
def Var(poly, dist=None, **kws): """ Element by element 2nd order statistics. Args: poly (Poly, Dist): Input to take variance on. dist (Dist): Defines the space the variance is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Element for element variance along ``poly``, where ``variation.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.Var(dist)) [1. 4.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.Var(poly, dist)) [ 0. 1. 4. 800.] """ if isinstance(poly, distributions.Dist): x = polynomials.variable(len(poly)) poly, dist = x, poly else: poly = polynomials.Poly(poly) dim = len(dist) if poly.dim<dim: polynomials.setdim(poly, dim) shape = poly.shape poly = polynomials.flatten(poly) keys = poly.keys N = len(keys) A = poly.A keys1 = numpy.array(keys).T if dim==1: keys1 = keys1[0] keys2 = sum(numpy.meshgrid(keys, keys)) else: keys2 = numpy.empty((dim, N, N)) for i in range(N): for j in range(N): keys2[:, i, j] = keys1[:, i]+keys1[:, j] m1 = numpy.outer(*[dist.mom(keys1, **kws)]*2) m2 = dist.mom(keys2, **kws) mom = m2-m1 out = numpy.zeros(poly.shape) for i in range(N): a = A[keys[i]] out += a*a*mom[i, i] for j in range(i+1, N): b = A[keys[j]] out += 2*a*b*mom[i, j] out = out.reshape(shape) return out
python
def Var(poly, dist=None, **kws): """ Element by element 2nd order statistics. Args: poly (Poly, Dist): Input to take variance on. dist (Dist): Defines the space the variance is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Element for element variance along ``poly``, where ``variation.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.Var(dist)) [1. 4.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.Var(poly, dist)) [ 0. 1. 4. 800.] """ if isinstance(poly, distributions.Dist): x = polynomials.variable(len(poly)) poly, dist = x, poly else: poly = polynomials.Poly(poly) dim = len(dist) if poly.dim<dim: polynomials.setdim(poly, dim) shape = poly.shape poly = polynomials.flatten(poly) keys = poly.keys N = len(keys) A = poly.A keys1 = numpy.array(keys).T if dim==1: keys1 = keys1[0] keys2 = sum(numpy.meshgrid(keys, keys)) else: keys2 = numpy.empty((dim, N, N)) for i in range(N): for j in range(N): keys2[:, i, j] = keys1[:, i]+keys1[:, j] m1 = numpy.outer(*[dist.mom(keys1, **kws)]*2) m2 = dist.mom(keys2, **kws) mom = m2-m1 out = numpy.zeros(poly.shape) for i in range(N): a = A[keys[i]] out += a*a*mom[i, i] for j in range(i+1, N): b = A[keys[j]] out += 2*a*b*mom[i, j] out = out.reshape(shape) return out
[ "def", "Var", "(", "poly", ",", "dist", "=", "None", ",", "*", "*", "kws", ")", ":", "if", "isinstance", "(", "poly", ",", "distributions", ".", "Dist", ")", ":", "x", "=", "polynomials", ".", "variable", "(", "len", "(", "poly", ")", ")", "poly"...
Element by element 2nd order statistics. Args: poly (Poly, Dist): Input to take variance on. dist (Dist): Defines the space the variance is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Element for element variance along ``poly``, where ``variation.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.Var(dist)) [1. 4.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.Var(poly, dist)) [ 0. 1. 4. 800.]
[ "Element", "by", "element", "2nd", "order", "statistics", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/variance.py#L7-L72
train
206,893
jonathf/chaospy
chaospy/descriptives/expected.py
E
def E(poly, dist=None, **kws): """ Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected value is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): The expected value of the polynomial or distribution, where ``expected.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.E(dist)) [1. 0.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.E(poly, dist)) [1. 1. 0. 0.] """ if not isinstance(poly, (distributions.Dist, polynomials.Poly)): print(type(poly)) print("Approximating expected value...") out = quadrature.quad(poly, dist, veceval=True, **kws) print("done") return out if isinstance(poly, distributions.Dist): dist, poly = poly, polynomials.variable(len(poly)) if not poly.keys: return numpy.zeros(poly.shape, dtype=int) if isinstance(poly, (list, tuple, numpy.ndarray)): return [E(_, dist, **kws) for _ in poly] if poly.dim < len(dist): poly = polynomials.setdim(poly, len(dist)) shape = poly.shape poly = polynomials.flatten(poly) keys = poly.keys mom = dist.mom(numpy.array(keys).T, **kws) A = poly.A if len(dist) == 1: mom = mom[0] out = numpy.zeros(poly.shape) for i in range(len(keys)): out += A[keys[i]]*mom[i] out = numpy.reshape(out, shape) return out
python
def E(poly, dist=None, **kws): """ Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected value is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): The expected value of the polynomial or distribution, where ``expected.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.E(dist)) [1. 0.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.E(poly, dist)) [1. 1. 0. 0.] """ if not isinstance(poly, (distributions.Dist, polynomials.Poly)): print(type(poly)) print("Approximating expected value...") out = quadrature.quad(poly, dist, veceval=True, **kws) print("done") return out if isinstance(poly, distributions.Dist): dist, poly = poly, polynomials.variable(len(poly)) if not poly.keys: return numpy.zeros(poly.shape, dtype=int) if isinstance(poly, (list, tuple, numpy.ndarray)): return [E(_, dist, **kws) for _ in poly] if poly.dim < len(dist): poly = polynomials.setdim(poly, len(dist)) shape = poly.shape poly = polynomials.flatten(poly) keys = poly.keys mom = dist.mom(numpy.array(keys).T, **kws) A = poly.A if len(dist) == 1: mom = mom[0] out = numpy.zeros(poly.shape) for i in range(len(keys)): out += A[keys[i]]*mom[i] out = numpy.reshape(out, shape) return out
[ "def", "E", "(", "poly", ",", "dist", "=", "None", ",", "*", "*", "kws", ")", ":", "if", "not", "isinstance", "(", "poly", ",", "(", "distributions", ".", "Dist", ",", "polynomials", ".", "Poly", ")", ")", ":", "print", "(", "type", "(", "poly", ...
Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected value is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): The expected value of the polynomial or distribution, where ``expected.shape == poly.shape``. Examples: >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2)) >>> print(chaospy.E(dist)) [1. 0.] >>> x, y = chaospy.variable(2) >>> poly = chaospy.Poly([1, x, y, 10*x*y]) >>> print(chaospy.E(poly, dist)) [1. 1. 0. 0.]
[ "Expected", "value", "operator", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/expected.py#L7-L69
train
206,894
jonathf/chaospy
chaospy/distributions/sampler/sequences/chebyshev.py
create_chebyshev_samples
def create_chebyshev_samples(order, dim=1): """ Chebyshev sampling function. Args: order (int): The number of samples to create along each axis. dim (int): The number of dimensions to create samples for. Returns: samples following Chebyshev sampling scheme mapped to the ``[0, 1]^dim`` hyper-cube and ``shape == (dim, order)``. """ x_data = .5*numpy.cos(numpy.arange(order, 0, -1)*numpy.pi/(order+1)) + .5 x_data = chaospy.quad.combine([x_data]*dim) return x_data.T
python
def create_chebyshev_samples(order, dim=1): """ Chebyshev sampling function. Args: order (int): The number of samples to create along each axis. dim (int): The number of dimensions to create samples for. Returns: samples following Chebyshev sampling scheme mapped to the ``[0, 1]^dim`` hyper-cube and ``shape == (dim, order)``. """ x_data = .5*numpy.cos(numpy.arange(order, 0, -1)*numpy.pi/(order+1)) + .5 x_data = chaospy.quad.combine([x_data]*dim) return x_data.T
[ "def", "create_chebyshev_samples", "(", "order", ",", "dim", "=", "1", ")", ":", "x_data", "=", ".5", "*", "numpy", ".", "cos", "(", "numpy", ".", "arange", "(", "order", ",", "0", ",", "-", "1", ")", "*", "numpy", ".", "pi", "/", "(", "order", ...
Chebyshev sampling function. Args: order (int): The number of samples to create along each axis. dim (int): The number of dimensions to create samples for. Returns: samples following Chebyshev sampling scheme mapped to the ``[0, 1]^dim`` hyper-cube and ``shape == (dim, order)``.
[ "Chebyshev", "sampling", "function", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/chebyshev.py#L48-L64
train
206,895
jonathf/chaospy
chaospy/orthogonal/cholesky.py
orth_chol
def orth_chol(order, dist, normed=True, sort="GR", cross_truncation=1., **kws): """ Create orthogonal polynomial expansion from Cholesky decomposition. Args: order (int): Order of polynomial expansion dist (Dist): Distribution space where polynomials are orthogonal normed (bool): If True orthonormal polynomials will be used instead of monic. sort (str): Ordering argument passed to poly.basis. If custom basis is used, argument is ignored. cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. Examples: >>> Z = chaospy.Normal() >>> print(chaospy.around(chaospy.orth_chol(3, Z), 4)) [1.0, q0, 0.7071q0^2-0.7071, 0.4082q0^3-1.2247q0] """ dim = len(dist) basis = chaospy.poly.basis( start=1, stop=order, dim=dim, sort=sort, cross_truncation=cross_truncation, ) length = len(basis) cholmat = chaospy.chol.gill_king(chaospy.descriptives.Cov(basis, dist)) cholmat_inv = numpy.linalg.inv(cholmat.T).T if not normed: diag_mesh = numpy.repeat(numpy.diag(cholmat_inv), len(cholmat_inv)) cholmat_inv /= diag_mesh.reshape(cholmat_inv.shape) coefs = numpy.empty((length+1, length+1)) coefs[1:, 1:] = cholmat_inv coefs[0, 0] = 1 coefs[0, 1:] = 0 expected = -numpy.sum( cholmat_inv*chaospy.descriptives.E(basis, dist, **kws), -1) coefs[1:, 0] = expected coefs = coefs.T out = {} out[(0,)*dim] = coefs[0] for idx in range(length): index = basis[idx].keys[0] out[index] = coefs[idx+1] polynomials = chaospy.poly.Poly(out, dim, coefs.shape[1:], float) return polynomials
python
def orth_chol(order, dist, normed=True, sort="GR", cross_truncation=1., **kws): """ Create orthogonal polynomial expansion from Cholesky decomposition. Args: order (int): Order of polynomial expansion dist (Dist): Distribution space where polynomials are orthogonal normed (bool): If True orthonormal polynomials will be used instead of monic. sort (str): Ordering argument passed to poly.basis. If custom basis is used, argument is ignored. cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. Examples: >>> Z = chaospy.Normal() >>> print(chaospy.around(chaospy.orth_chol(3, Z), 4)) [1.0, q0, 0.7071q0^2-0.7071, 0.4082q0^3-1.2247q0] """ dim = len(dist) basis = chaospy.poly.basis( start=1, stop=order, dim=dim, sort=sort, cross_truncation=cross_truncation, ) length = len(basis) cholmat = chaospy.chol.gill_king(chaospy.descriptives.Cov(basis, dist)) cholmat_inv = numpy.linalg.inv(cholmat.T).T if not normed: diag_mesh = numpy.repeat(numpy.diag(cholmat_inv), len(cholmat_inv)) cholmat_inv /= diag_mesh.reshape(cholmat_inv.shape) coefs = numpy.empty((length+1, length+1)) coefs[1:, 1:] = cholmat_inv coefs[0, 0] = 1 coefs[0, 1:] = 0 expected = -numpy.sum( cholmat_inv*chaospy.descriptives.E(basis, dist, **kws), -1) coefs[1:, 0] = expected coefs = coefs.T out = {} out[(0,)*dim] = coefs[0] for idx in range(length): index = basis[idx].keys[0] out[index] = coefs[idx+1] polynomials = chaospy.poly.Poly(out, dim, coefs.shape[1:], float) return polynomials
[ "def", "orth_chol", "(", "order", ",", "dist", ",", "normed", "=", "True", ",", "sort", "=", "\"GR\"", ",", "cross_truncation", "=", "1.", ",", "*", "*", "kws", ")", ":", "dim", "=", "len", "(", "dist", ")", "basis", "=", "chaospy", ".", "poly", ...
Create orthogonal polynomial expansion from Cholesky decomposition. Args: order (int): Order of polynomial expansion dist (Dist): Distribution space where polynomials are orthogonal normed (bool): If True orthonormal polynomials will be used instead of monic. sort (str): Ordering argument passed to poly.basis. If custom basis is used, argument is ignored. cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. Examples: >>> Z = chaospy.Normal() >>> print(chaospy.around(chaospy.orth_chol(3, Z), 4)) [1.0, q0, 0.7071q0^2-0.7071, 0.4082q0^3-1.2247q0]
[ "Create", "orthogonal", "polynomial", "expansion", "from", "Cholesky", "decomposition", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/orthogonal/cholesky.py#L30-L86
train
206,896
jonathf/chaospy
chaospy/poly/dimension.py
setdim
def setdim(P, dim=None): """ Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is smaller then P's dimensions, variables with cut components are all cut. Examples: >>> x,y = chaospy.variable(2) >>> P = x*x-x*y >>> print(chaospy.setdim(P, 1)) q0^2 """ P = P.copy() ldim = P.dim if not dim: dim = ldim+1 if dim==ldim: return P P.dim = dim if dim>ldim: key = numpy.zeros(dim, dtype=int) for lkey in P.keys: key[:ldim] = lkey P.A[tuple(key)] = P.A.pop(lkey) else: key = numpy.zeros(dim, dtype=int) for lkey in P.keys: if not sum(lkey[ldim-1:]) or not sum(lkey): P.A[lkey[:dim]] = P.A.pop(lkey) else: del P.A[lkey] P.keys = sorted(P.A.keys(), key=sort_key) return P
python
def setdim(P, dim=None): """ Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is smaller then P's dimensions, variables with cut components are all cut. Examples: >>> x,y = chaospy.variable(2) >>> P = x*x-x*y >>> print(chaospy.setdim(P, 1)) q0^2 """ P = P.copy() ldim = P.dim if not dim: dim = ldim+1 if dim==ldim: return P P.dim = dim if dim>ldim: key = numpy.zeros(dim, dtype=int) for lkey in P.keys: key[:ldim] = lkey P.A[tuple(key)] = P.A.pop(lkey) else: key = numpy.zeros(dim, dtype=int) for lkey in P.keys: if not sum(lkey[ldim-1:]) or not sum(lkey): P.A[lkey[:dim]] = P.A.pop(lkey) else: del P.A[lkey] P.keys = sorted(P.A.keys(), key=sort_key) return P
[ "def", "setdim", "(", "P", ",", "dim", "=", "None", ")", ":", "P", "=", "P", ".", "copy", "(", ")", "ldim", "=", "P", ".", "dim", "if", "not", "dim", ":", "dim", "=", "ldim", "+", "1", "if", "dim", "==", "ldim", ":", "return", "P", "P", "...
Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is smaller then P's dimensions, variables with cut components are all cut. Examples: >>> x,y = chaospy.variable(2) >>> P = x*x-x*y >>> print(chaospy.setdim(P, 1)) q0^2
[ "Adjust", "the", "dimensions", "of", "a", "polynomial", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/dimension.py#L79-L125
train
206,897
jonathf/chaospy
chaospy/chol/gill_murray_wright.py
gill_murray_wright
def gill_murray_wright(mat, eps=1e-16): """ Gill-Murray-Wright algorithm for pivoting modified Cholesky decomposition. Return ``(perm, lowtri, error)`` such that `perm.T*mat*perm = lowtri*lowtri.T` is approximately correct. Args: mat (numpy.ndarray): Must be a non-singular and symmetric matrix eps (float): Error tolerance used in algorithm. Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Permutation matrix used for pivoting and lower triangular factor. Examples: >>> mat = numpy.matrix([[4, 2, 1], [2, 6, 3], [1, 3, -.004]]) >>> perm, lowtri = gill_murray_wright(mat) >>> perm, lowtri = numpy.matrix(perm), numpy.matrix(lowtri) >>> print(perm) [[0 1 0] [1 0 0] [0 0 1]] >>> print(numpy.around(lowtri, 4)) [[ 2.4495 0. 0. ] [ 0.8165 1.8257 0. ] [ 1.2247 -0. 1.2264]] >>> print(numpy.around(perm*lowtri*lowtri.T*perm.T, 4)) [[4. 2. 1. ] [2. 6. 3. ] [1. 3. 3.004]] """ mat = numpy.asfarray(mat) size = mat.shape[0] # Calculate gamma(mat) and xi_(mat). gamma = 0.0 xi_ = 0.0 for idy in range(size): gamma = max(abs(mat[idy, idy]), gamma) for idx in range(idy+1, size): xi_ = max(abs(mat[idy, idx]), xi_) # Calculate delta and beta. delta = eps * max(gamma + xi_, 1.0) if size == 1: beta = numpy.sqrt(max(gamma, eps)) else: beta = numpy.sqrt(max(gamma, xi_ / numpy.sqrt(size*size - 1.0), eps)) # Initialise data structures. mat_a = 1.0 * mat mat_r = 0.0 * mat perm = numpy.eye(size, dtype=int) # Main loop. for idx in range(size): # Row and column swapping, find the index > idx of the largest # idzgonal element. idz = idx for idy in range(idx+1, size): if abs(mat_a[idy, idy]) >= abs(mat_a[idz, idz]): idz = idy if idz != idx: mat_a, mat_r, perm = swap_across(idz, idx, mat_a, mat_r, perm) # Calculate a_pred. theta_j = 0.0 if idx < size-1: for idy in range(idx+1, size): theta_j = max(theta_j, abs(mat_a[idx, idy])) a_pred = max(abs(mat_a[idx, idx]), (theta_j/beta)**2, delta) # Calculate row idx of r and update a. mat_r[idx, idx] = numpy.sqrt(a_pred) for idy in range(idx+1, size): mat_r[idx, idy] = mat_a[idx, idy] / mat_r[idx, idx] for idz in range(idx+1, idy+1): # Keep matrix a symmetric: mat_a[idy, idz] = mat_a[idz, idy] = \ mat_a[idz, idy] - mat_r[idx, idy] * mat_r[idx, idz] # The Cholesky factor of mat. return perm, mat_r.T
python
def gill_murray_wright(mat, eps=1e-16): """ Gill-Murray-Wright algorithm for pivoting modified Cholesky decomposition. Return ``(perm, lowtri, error)`` such that `perm.T*mat*perm = lowtri*lowtri.T` is approximately correct. Args: mat (numpy.ndarray): Must be a non-singular and symmetric matrix eps (float): Error tolerance used in algorithm. Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Permutation matrix used for pivoting and lower triangular factor. Examples: >>> mat = numpy.matrix([[4, 2, 1], [2, 6, 3], [1, 3, -.004]]) >>> perm, lowtri = gill_murray_wright(mat) >>> perm, lowtri = numpy.matrix(perm), numpy.matrix(lowtri) >>> print(perm) [[0 1 0] [1 0 0] [0 0 1]] >>> print(numpy.around(lowtri, 4)) [[ 2.4495 0. 0. ] [ 0.8165 1.8257 0. ] [ 1.2247 -0. 1.2264]] >>> print(numpy.around(perm*lowtri*lowtri.T*perm.T, 4)) [[4. 2. 1. ] [2. 6. 3. ] [1. 3. 3.004]] """ mat = numpy.asfarray(mat) size = mat.shape[0] # Calculate gamma(mat) and xi_(mat). gamma = 0.0 xi_ = 0.0 for idy in range(size): gamma = max(abs(mat[idy, idy]), gamma) for idx in range(idy+1, size): xi_ = max(abs(mat[idy, idx]), xi_) # Calculate delta and beta. delta = eps * max(gamma + xi_, 1.0) if size == 1: beta = numpy.sqrt(max(gamma, eps)) else: beta = numpy.sqrt(max(gamma, xi_ / numpy.sqrt(size*size - 1.0), eps)) # Initialise data structures. mat_a = 1.0 * mat mat_r = 0.0 * mat perm = numpy.eye(size, dtype=int) # Main loop. for idx in range(size): # Row and column swapping, find the index > idx of the largest # idzgonal element. idz = idx for idy in range(idx+1, size): if abs(mat_a[idy, idy]) >= abs(mat_a[idz, idz]): idz = idy if idz != idx: mat_a, mat_r, perm = swap_across(idz, idx, mat_a, mat_r, perm) # Calculate a_pred. theta_j = 0.0 if idx < size-1: for idy in range(idx+1, size): theta_j = max(theta_j, abs(mat_a[idx, idy])) a_pred = max(abs(mat_a[idx, idx]), (theta_j/beta)**2, delta) # Calculate row idx of r and update a. mat_r[idx, idx] = numpy.sqrt(a_pred) for idy in range(idx+1, size): mat_r[idx, idy] = mat_a[idx, idy] / mat_r[idx, idx] for idz in range(idx+1, idy+1): # Keep matrix a symmetric: mat_a[idy, idz] = mat_a[idz, idy] = \ mat_a[idz, idy] - mat_r[idx, idy] * mat_r[idx, idz] # The Cholesky factor of mat. return perm, mat_r.T
[ "def", "gill_murray_wright", "(", "mat", ",", "eps", "=", "1e-16", ")", ":", "mat", "=", "numpy", ".", "asfarray", "(", "mat", ")", "size", "=", "mat", ".", "shape", "[", "0", "]", "# Calculate gamma(mat) and xi_(mat).", "gamma", "=", "0.0", "xi_", "=", ...
Gill-Murray-Wright algorithm for pivoting modified Cholesky decomposition. Return ``(perm, lowtri, error)`` such that `perm.T*mat*perm = lowtri*lowtri.T` is approximately correct. Args: mat (numpy.ndarray): Must be a non-singular and symmetric matrix eps (float): Error tolerance used in algorithm. Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Permutation matrix used for pivoting and lower triangular factor. Examples: >>> mat = numpy.matrix([[4, 2, 1], [2, 6, 3], [1, 3, -.004]]) >>> perm, lowtri = gill_murray_wright(mat) >>> perm, lowtri = numpy.matrix(perm), numpy.matrix(lowtri) >>> print(perm) [[0 1 0] [1 0 0] [0 0 1]] >>> print(numpy.around(lowtri, 4)) [[ 2.4495 0. 0. ] [ 0.8165 1.8257 0. ] [ 1.2247 -0. 1.2264]] >>> print(numpy.around(perm*lowtri*lowtri.T*perm.T, 4)) [[4. 2. 1. ] [2. 6. 3. ] [1. 3. 3.004]]
[ "Gill", "-", "Murray", "-", "Wright", "algorithm", "for", "pivoting", "modified", "Cholesky", "decomposition", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/chol/gill_murray_wright.py#L10-L98
train
206,898
jonathf/chaospy
chaospy/chol/gill_murray_wright.py
swap_across
def swap_across(idx, idy, mat_a, mat_r, perm): """Interchange row and column idy and idx.""" # Temporary permutation matrix for swaping 2 rows or columns. size = mat_a.shape[0] perm_new = numpy.eye(size, dtype=int) # Modify the permutation matrix perm by swaping columns. perm_row = 1.0*perm[:, idx] perm[:, idx] = perm[:, idy] perm[:, idy] = perm_row # Modify the permutation matrix p by swaping rows (same as # columns because p = pT). row_p = 1.0 * perm_new[idx] perm_new[idx] = perm_new[idy] perm_new[idy] = row_p # Permute mat_a and r (p = pT). mat_a = numpy.dot(perm_new, numpy.dot(mat_a, perm_new)) mat_r = numpy.dot(mat_r, perm_new) return mat_a, mat_r, perm
python
def swap_across(idx, idy, mat_a, mat_r, perm): """Interchange row and column idy and idx.""" # Temporary permutation matrix for swaping 2 rows or columns. size = mat_a.shape[0] perm_new = numpy.eye(size, dtype=int) # Modify the permutation matrix perm by swaping columns. perm_row = 1.0*perm[:, idx] perm[:, idx] = perm[:, idy] perm[:, idy] = perm_row # Modify the permutation matrix p by swaping rows (same as # columns because p = pT). row_p = 1.0 * perm_new[idx] perm_new[idx] = perm_new[idy] perm_new[idy] = row_p # Permute mat_a and r (p = pT). mat_a = numpy.dot(perm_new, numpy.dot(mat_a, perm_new)) mat_r = numpy.dot(mat_r, perm_new) return mat_a, mat_r, perm
[ "def", "swap_across", "(", "idx", ",", "idy", ",", "mat_a", ",", "mat_r", ",", "perm", ")", ":", "# Temporary permutation matrix for swaping 2 rows or columns.", "size", "=", "mat_a", ".", "shape", "[", "0", "]", "perm_new", "=", "numpy", ".", "eye", "(", "s...
Interchange row and column idy and idx.
[ "Interchange", "row", "and", "column", "idy", "and", "idx", "." ]
25ecfa7bf5608dc10c0b31d142ded0e3755f5d74
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/chol/gill_murray_wright.py#L101-L121
train
206,899