text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self): """ Empties the cache """
self._table.clear() for item in self._usage_recency: self._usage_recency.remove(item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [q0^2+2q0, q0^2+q0] With multiple substitutions: [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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [q0^2-1, 2] [[-1, 2], [q0^2, 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform()] [Normal(mu=Uniform(lower=0, upper=1), sigma=1), Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform(), Mul(normal(), 1), normal()] True 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [uniform(), Mul(uniform(), 0.5), Uniform(lower=1, upper=2)] [] [] [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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [-1.7321 0. 1.7321] [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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _identify_poly(core): """Specification for a polynomial."""
return core.A, core.dim, core.shape, core.dtype
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [[1. 0.3536] [0.3536 1. ]] [[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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [2. 0.] [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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [1. 4.] [ 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [1. 0.] [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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: [[0 1 0] [1 0 0] [0 0 1]] [[ 2.4495 0. 0. ] [ 0.8165 1.8257 0. ] [ 1.2247 -0. 1.2264]] [[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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_halton_samples(order, dim=1, burnin=-1, primes=()): """ Create Halton sequence. For ``dim == 1`` the sequence falls back to Van Der Corput sequence. Args: order (int): The order of the Halton sequence. Defines the number of samples. dim (int): The number of dimensions in the Halton sequence. burnin (int): Skip the first ``burnin`` samples. If negative, the maximum of ``primes`` is used. primes (tuple): The (non-)prime base to calculate values along each axis. If empty, growing prime values starting from 2 will be used. Returns (numpy.ndarray): Halton sequence with ``shape == (dim, order)``. """
primes = list(primes) if not primes: prime_order = 10*dim while len(primes) < dim: primes = create_primes(prime_order) prime_order *= 2 primes = primes[:dim] assert len(primes) == dim, "not enough primes" if burnin < 0: burnin = max(primes) out = numpy.empty((dim, order)) indices = [idx+burnin for idx in range(order)] for dim_ in range(dim): out[dim_] = create_van_der_corput_samples( indices, number_base=primes[dim_]) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def range(self, x_data=None): """ Generate the upper and lower bounds of a distribution. Args: x_data (numpy.ndarray) : The bounds might vary over the sample space. By providing x_data you can specify where in the space the bound should be taken. If omitted, a (pseudo-)random sample is used. Returns: (numpy.ndarray): The lower (out[0]) and upper (out[1]) bound where out.shape=(2,)+x_data.shape """
if x_data is None: try: x_data = evaluation.evaluate_inverse( self, numpy.array([[0.5]]*len(self))) except StochasticallyDependentError: x_data = approximation.find_interior_point(self) shape = (len(self),) if hasattr(self, "_range"): return self._range(x_data, {}) else: x_data = numpy.asfarray(x_data) shape = x_data.shape x_data = x_data.reshape(len(self), -1) q_data = evaluation.evaluate_bound(self, x_data) q_data = q_data.reshape((2,)+shape) return q_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fwd(self, x_data): """ Forward Rosenblatt transformation. Args: x_data (numpy.ndarray): Location for the distribution function. ``x_data.shape`` must be compatible with distribution shape. Returns: (numpy.ndarray): Evaluated distribution function values, where ``out.shape==x_data.shape``. """
x_data = numpy.asfarray(x_data) shape = x_data.shape x_data = x_data.reshape(len(self), -1) lower, upper = evaluation.evaluate_bound(self, x_data) q_data = numpy.zeros(x_data.shape) indices = x_data > upper q_data[indices] = 1 indices = ~indices & (x_data >= lower) q_data[indices] = numpy.clip(evaluation.evaluate_forward( self, x_data), a_min=0, a_max=1)[indices] q_data = q_data.reshape(shape) return q_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inv(self, q_data, max_iterations=100, tollerance=1e-5): """ Inverse Rosenblatt transformation. If possible the transformation is done analytically. If not possible, transformation is approximated using an algorithm that alternates between Newton-Raphson and binary search. Args: q_data (numpy.ndarray): Probabilities to be inverse. If any values are outside ``[0, 1]``, error will be raised. ``q_data.shape`` must be compatible with distribution shape. max_iterations (int): If approximation is used, this sets the maximum number of allowed iterations in the Newton-Raphson algorithm. tollerance (float): If approximation is used, this set the error tolerance level required to define a sample as converged. Returns: (numpy.ndarray): Inverted probability values where ``out.shape == q_data.shape``. """
q_data = numpy.asfarray(q_data) assert numpy.all((q_data >= 0) & (q_data <= 1)), "sanitize your inputs!" shape = q_data.shape q_data = q_data.reshape(len(self), -1) x_data = evaluation.evaluate_inverse(self, q_data) lower, upper = evaluation.evaluate_bound(self, x_data) x_data = numpy.clip(x_data, a_min=lower, a_max=upper) x_data = x_data.reshape(shape) return x_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, size=(), rule="R", antithetic=None): """ Create pseudo-random generated samples. By default, the samples are created using standard (pseudo-)random samples. However, if needed, the samples can also be created by either low-discrepancy sequences, and/or variance reduction techniques. Changing the sampling scheme, use the following ``rule`` flag: | key | Description | +=======+=================================================+ | ``C`` | Roots of the first order Chebyshev polynomials. | | ``NC``| Chebyshev nodes adjusted to ensure nested. | | ``K`` | Korobov lattice. | | ``R`` | Classical (Pseudo-)Random samples. | | ``RG``| Regular spaced grid. | | ``NG``| Nested regular spaced grid. | | ``L`` | Latin hypercube samples. | | ``S`` | Sobol low-discrepancy sequence. | | ``H`` | Halton low-discrepancy sequence. | | ``M`` | Hammersley low-discrepancy sequence. | All samples are created on the ``[0, 1]``-hypercube, which then is mapped into the domain of the distribution using the inverse Rosenblatt transformation. Args: size (numpy.ndarray): The size of the samples to generate. rule (str): Indicator defining the sampling scheme. antithetic (bool, numpy.ndarray): If provided, will be used to setup antithetic variables. If array, defines the axes to mirror. Returns: (numpy.ndarray): Random samples with shape ``(len(self),)+self.shape``. """
size_ = numpy.prod(size, dtype=int) dim = len(self) if dim > 1: if isinstance(size, (tuple, list, numpy.ndarray)): shape = (dim,) + tuple(size) else: shape = (dim, size) else: shape = size from . import sampler out = sampler.generator.generate_samples( order=size_, domain=self, rule=rule, antithetic=antithetic) try: out = out.reshape(shape) except: if len(self) == 1: out = out.flatten() else: out = out.reshape(dim, int(out.size/dim)) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mom(self, K, **kws): """ Raw statistical moments. Creates non-centralized raw moments from the random variable. If analytical options can not be utilized, Monte Carlo integration will be used. Args: K (numpy.ndarray): Index of the raw moments. k.shape must be compatible with distribution shape. Sampling scheme when performing Monte Carlo rule (str): rule for estimating the moment if the analytical method fails. composite (numpy.ndarray): If provided, composit quadrature will be used. Ignored in the case if gaussian=True. If int provided, determines number of even domain splits. If array of ints, determines number of even domain splits along each axis. If array of arrays/floats, determines location of splits. antithetic (numpy.ndarray): List of bool. Represents the axes to mirror using antithetic variable during MCI. Returns: (numpy.ndarray): Shapes are related through the identity ``k.shape == dist.shape+k.shape``. """
K = numpy.asarray(K, dtype=int) shape = K.shape dim = len(self) if dim > 1: shape = shape[1:] size = int(K.size/dim) K = K.reshape(dim, size) cache = {} out = [evaluation.evaluate_moment(self, kdata, cache) for kdata in K.T] out = numpy.array(out) return out.reshape(shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ttr(self, kloc, acc=10**3, verbose=1): """ Three terms relation's coefficient generator Args: k (numpy.ndarray, int): The order of the coefficients. acc (int): Accuracy of discretized Stieltjes if analytical methods are unavailable. Returns: (Recurrence coefficients): Where out[0] is the first (A) and out[1] is the second coefficient With ``out.shape==(2,)+k.shape``. """
kloc = numpy.asarray(kloc, dtype=int) shape = kloc.shape kloc = kloc.reshape(len(self), -1) cache = {} out = [evaluation.evaluate_recurrence_coefficients(self, k) for k in kloc.T] out = numpy.array(out).T return out.reshape((2,)+shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Acf(poly, dist, N=None, **kws): """ Auto-correlation function. Args: poly (Poly): Polynomial of interest. Must have ``len(poly) > N``. dist (Dist): Defines the space the correlation is taken on. N (int): The number of time steps appart included. If omited set to ``len(poly)/2+1``. Returns: (numpy.ndarray) : Auto-correlation of ``poly`` with shape ``(N,)``. Note that by definition ``Q[0]=1``. Examples: [1. 0.9915 0.9722 0.9457 0.9127] """
if N is None: N = len(poly)/2 + 1 corr = Corr(poly, dist, **kws) out = numpy.empty(N) for n in range(N): out[n] = numpy.mean(corr.diagonal(n), 0) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_figures(): """Plot figures for multivariate distribution section."""
rc("figure", figsize=[8.,4.]) rc("figure.subplot", left=.08, top=.95, right=.98) rc("image", cmap="gray") seed(1000) Q1 = cp.Gamma(2) Q2 = cp.Normal(0, Q1) Q = cp.J(Q1, Q2) #end subplot(121) s,t = meshgrid(linspace(0,5,200), linspace(-6,6,200)) contourf(s,t,Q.pdf([s,t]),50) xlabel("$q_1$") ylabel("$q_2$") subplot(122) Qr = Q.sample(500) scatter(*Qr, s=10, c="k", marker="s") xlabel("$Q_1$") ylabel("$Q_2$") axis([0,5,-6,6]) savefig("multivariate.png"); clf() Q2 = cp.Gamma(1) Q1 = cp.Normal(Q2**2, Q2+1) Q = cp.J(Q1, Q2) #end subplot(121) s,t = meshgrid(linspace(-4,7,200), linspace(0,3,200)) contourf(s,t,Q.pdf([s,t]),30) xlabel("$q_1$") ylabel("$q_2$") subplot(122) Qr = Q.sample(500) scatter(*Qr) xlabel("$Q_1$") ylabel("$Q_2$") axis([-4,7,0,3]) savefig("multivariate2.png"); clf()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(vari): """ Flatten a shapeable quantity. Args: vari (chaospy.poly.base.Poly, numpy.ndarray): Shapeable input quantity. Returns: (chaospy.poly.base.Poly, numpy.ndarray): Same type as ``vari`` with `len(Q.shape)==1`. Examples: [[1, q0], [q0^2, q0^3]] [1, q0, q0^2, q0^3] """
if isinstance(vari, Poly): shape = int(numpy.prod(vari.shape)) return reshape(vari, (shape,)) return numpy.array(vari).flatten()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshape(vari, shape): """ Reshape the shape of a shapeable quantity. Args: vari (chaospy.poly.base.Poly, numpy.ndarray): Shapeable input quantity. shape (tuple): The polynomials new shape. Must be compatible with the number of elements in ``vari``. Returns: (chaospy.poly.base.Poly, numpy.ndarray): Same type as ``vari``. Examples: [1, q0, q0^2, q0^3, q0^4, q0^5] [[1, q0, q0^2], [q0^3, q0^4, q0^5]] """
if isinstance(vari, Poly): core = vari.A.copy() for key in vari.keys: core[key] = reshape(core[key], shape) out = Poly(core, vari.dim, shape, vari.dtype) return out return numpy.asarray(vari).reshape(shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollaxis(vari, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. Args: vari (chaospy.poly.base.Poly, numpy.ndarray): Input array or polynomial. axis (int): The axis to roll backwards. The positions of the other axes do not change relative to one another. start (int): The axis is rolled until it lies before thes position. """
if isinstance(vari, Poly): core_old = vari.A.copy() core_new = {} for key in vari.keys: core_new[key] = rollaxis(core_old[key], axis, start) return Poly(core_new, vari.dim, None, vari.dtype) return numpy.rollaxis(vari, axis, start)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swapaxes(vari, ax1, ax2): """Interchange two axes of a polynomial."""
if isinstance(vari, Poly): core = vari.A.copy() for key in vari.keys: core[key] = swapaxes(core[key], ax1, ax2) return Poly(core, vari.dim, None, vari.dtype) return numpy.swapaxes(vari, ax1, ax2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roll(vari, shift, axis=None): """Roll array elements along a given axis."""
if isinstance(vari, Poly): core = vari.A.copy() for key in vari.keys: core[key] = roll(core[key], shift, axis) return Poly(core, vari.dim, None, vari.dtype) return numpy.roll(vari, shift, axis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transpose(vari): """ Transpose a shapeable quantety. Args: vari (chaospy.poly.base.Poly, numpy.ndarray): Quantety of interest. Returns: (chaospy.poly.base.Poly, numpy.ndarray): Same type as ``vari``. Examples: [[1, q0], [q0^2, q0^3]] [[1, q0^2], [q0, q0^3]] """
if isinstance(vari, Poly): core = vari.A.copy() for key in vari.keys: core[key] = transpose(core[key]) return Poly(core, vari.dim, vari.shape[::-1], vari.dtype) return numpy.transpose(vari)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_antithetic_variates(samples, axes=()): """ Generate antithetic variables. Args: samples (numpy.ndarray): The samples, assumed to be on the [0, 1]^D hyper-cube, to be reflected. axes (tuple): Boolean array of which axes to reflect. If This to limit the number of points created in higher dimensions by reflecting all axes at once. Returns (numpy.ndarray): Same as ``samples``, but with samples internally reflected. roughly equivalent to ``numpy.vstack([samples, 1-samples])`` in one dimensions. """
samples = numpy.asfarray(samples) assert numpy.all(samples <= 1) and numpy.all(samples >= 0), ( "all samples assumed on interval [0, 1].") if len(samples.shape) == 1: samples = samples.reshape(1, -1) inverse_samples = 1-samples dims = len(samples) if not len(axes): axes = (True,) axes = numpy.asarray(axes, dtype=bool).flatten() indices = {tuple(axes*idx) for idx in numpy.ndindex((2,)*dims)} indices = sorted(indices, reverse=True) indices = sorted(indices, key=lambda idx: sum(idx)) out = [numpy.where(idx, inverse_samples.T, samples.T).T for idx in indices] out = numpy.dstack(out).reshape(dims, -1) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preprocess(core, dim, shape, dtype): """Constructor function for the Poly class."""
core, dim_, shape_, dtype_ = chaospy.poly.constructor.identify_core(core) core, shape = chaospy.poly.constructor.ensure_shape(core, shape, shape_) core, dtype = chaospy.poly.constructor.ensure_dtype(core, dtype, dtype_) core, dim = chaospy.poly.constructor.ensure_dim(core, dim, dim_) # Remove empty elements for key in list(core.keys()): if np.all(core[key] == 0): del core[key] assert isinstance(dim, int), \ "not recognised type for dim: '%s'" % repr(type(dim)) assert isinstance(shape, tuple), str(shape) assert dtype is not None, str(dtype) # assert non-empty container if not core: core = {(0,)*dim: np.zeros(shape, dtype=dtype)} else: core = {key: np.asarray(value, dtype) for key, value in core.items()} return core, dim, shape, dtype
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine(args, part=None): """ All linear combination of a list of list. Args: args (numpy.ndarray) : List of input arrays. Components to take linear combination of with `args[i].shape=(N[i], M[i])` where N is to be taken linear combination of and M is static. M[i] is set to 1 if missing. Returns: (numpy.array) : matrix of combinations with shape (numpy.prod(N), numpy.sum(M)). Examples: [[1. 4. 4.] [1. 5. 6.] [2. 4. 4.] [2. 5. 6.]] """
args = [cleanup(arg) for arg in args] if part is not None: parts, orders = part if numpy.array(orders).size == 1: orders = [int(numpy.array(orders).item())]*len(args) parts = numpy.array(parts).flatten() for i, arg in enumerate(args): m, n = float(parts[i]), float(orders[i]) l = len(arg) args[i] = arg[int(m/n*l):int((m+1)/n*l)] shapes = [arg.shape for arg in args] size = numpy.prod(shapes, 0)[0]*numpy.sum(shapes, 0)[1] if size > 10**9: raise MemoryError("Too large sets") if len(args) == 1: out = args[0] elif len(args) == 2: out = combine_two(*args) else: arg1 = combine_two(*args[:2]) out = combine([arg1,]+args[2:]) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup(arg): """Clean up the input variable."""
arg = numpy.asarray(arg) if len(arg.shape) <= 1: arg = arg.reshape(arg.size, 1) elif len(arg.shape) > 2: raise ValueError("shapes must be smaller than 3") return arg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_grid_samples(order, dim=1): """ Create samples from a regular grid. Args: order (int): The order of the grid. Defines the number of samples. dim (int): The number of dimensions in the grid Returns (numpy.ndarray): Regular grid with ``shape == (dim, order)``. """
x_data = numpy.arange(1, order+1)/(order+1.) x_data = chaospy.quad.combine([x_data]*dim) return x_data.T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(idxi, idxj, dim): """ Bertran addition. Example ------- 6 10 """
idxm = numpy.array(multi_index(idxi, dim)) idxn = numpy.array(multi_index(idxj, dim)) out = single_index(idxm + idxn) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terms(order, dim): """ Count the number of polynomials in an expansion. Parameters order : int The upper order for the expansion. dim : int The number of dimensions of the expansion. Returns ------- N : int The number of terms in an expansion of upper order `M` and number of dimensions `dim`. """
return int(scipy.special.comb(order+dim, dim, 1))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_index(idx, dim): """ Single to multi-index using graded reverse lexicographical notation. Parameters idx : int Index in interger notation dim : int The number of dimensions in the multi-index notation Returns ------- out : tuple Multi-index of `idx` with `len(out)=dim` Examples -------- (0, 0, 0) (1, 0, 0) (0, 1, 0) (0, 0, 1) (2, 0, 0) See Also -------- single_index """
def _rec(idx, dim): idxn = idxm = 0 if not dim: return () if idx == 0: return (0, )*dim while terms(idxn, dim) <= idx: idxn += 1 idx -= terms(idxn-1, dim) if idx == 0: return (idxn,) + (0,)*(dim-1) while terms(idxm, dim-1) <= idx: idxm += 1 return (int(idxn-idxm),) + _rec(idx, dim-1) return _rec(idx, dim)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bindex(start, stop=None, dim=1, sort="G", cross_truncation=1.): """ Generator for creating multi-indices. Args: start (int): The lower order of the indices stop (:py:data:typing.Optional[int]): the maximum shape included. If omitted: stop <- start; start <- 0 If int is provided, set as largest total order. If array of int, set as largest order along each axis. dim (int): The number of dimensions in the expansion cross_truncation (float): Use hyperbolic cross truncation scheme to reduce the number of terms in expansion. Returns: list: Order list of indices. Examples: [[2, 0], [1, 1], [0, 2], [3, 0], [2, 1], [1, 2], [0, 3]] [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]] """
if stop is None: start, stop = 0, start start = numpy.array(start, dtype=int).flatten() stop = numpy.array(stop, dtype=int).flatten() sort = sort.upper() total = numpy.mgrid[(slice(numpy.max(stop), -1, -1),)*dim] total = numpy.array(total).reshape(dim, -1) if start.size > 1: for idx, start_ in enumerate(start): total = total[:, total[idx] >= start_] else: total = total[:, total.sum(0) >= start] if stop.size > 1: for idx, stop_ in enumerate(stop): total = total[:, total[idx] <= stop_] total = total.T.tolist() if "G" in sort: total = sorted(total, key=sum) else: def cmp_(idxi, idxj): """Old style compare method.""" if not numpy.any(idxi): return 0 if idxi[0] == idxj[0]: return cmp(idxi[:-1], idxj[:-1]) return (idxi[-1] > idxj[-1]) - (idxi[-1] < idxj[-1]) key = functools.cmp_to_key(cmp_) total = sorted(total, key=key) if "I" in sort: total = total[::-1] if "R" in sort: total = [idx[::-1] for idx in total] for pos, idx in reversed(list(enumerate(total))): idx = numpy.array(idx) cross_truncation = numpy.asfarray(cross_truncation) try: if numpy.any(numpy.sum(idx**(1./cross_truncation)) > numpy.max(stop)**(1./cross_truncation)): del total[pos] except (OverflowError, ZeroDivisionError): pass return total
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def single_index(idxm): """ Multi-index to single integer notation. Uses graded reverse lexicographical notation. Parameters idxm : numpy.ndarray Index in multi-index notation Returns ------- idx : int Integer index of `idxm` Examples -------- 1 2 3 """
if -1 in idxm: return 0 order = int(sum(idxm)) dim = len(idxm) if order == 0: return 0 return terms(order-1, dim) + single_index(idxm[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank(idx, dim): """Calculate the index rank according to Bertran's notation."""
idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(idx, dim, axis=None): """ Parent node according to Bertran's notation. Parameters idx : int Index of the child node. dim : int Dimensionality of the problem. axis : int Assume axis direction. Returns ------- out : int Index of parent node with `j<=i`, and `j==i` iff `i==0`. axis : int Dimension direction the parent was found. """
idxm = multi_index(idx, dim) if axis is None: axis = dim - numpy.argmin(1*(numpy.array(idxm)[::-1] == 0))-1 if not idx: return idx, axis if idxm[axis] == 0: idxi = parent(parent(idx, dim)[0], dim)[0] while child(idxi+1, dim, axis) < idx: idxi += 1 return idxi, axis out = numpy.array(idxm) - 1*(numpy.eye(dim)[axis]) return single_index(out), axis
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child(idx, dim, axis): """ Child node according to Bertran's notation. Parameters idx : int Index of the parent node. dim : int Dimensionality of the problem. axis : int Dimension direction to define a child. Must have `0<=axis<dim` Returns ------- out : int Index of child node with `out > idx`. Examples -------- 5 8 """
idxm = multi_index(idx, dim) out = numpy.array(idxm) + 1*(numpy.eye(len(idxm))[axis]) return single_index(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_shape(core, shape, shape_): """Ensure shape is correct."""
core = core.copy() if shape is None: shape = shape_ elif isinstance(shape, int): shape = (shape,) if tuple(shape) == tuple(shape_): return core, shape ones = np.ones(shape, dtype=int) for key, val in core.items(): core[key] = val*ones return core, shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_dtype(core, dtype, dtype_): """Ensure dtype is correct."""
core = core.copy() if dtype is None: dtype = dtype_ if dtype_ == dtype: return core, dtype for key, val in { int: chaospy.poly.typing.asint, float: chaospy.poly.typing.asfloat, np.float32: chaospy.poly.typing.asfloat, np.float64: chaospy.poly.typing.asfloat, }.items(): if dtype == key: converter = val break else: raise ValueError("dtype not recognised (%s)" % str(dtype)) for key, val in core.items(): core[key] = converter(val) return core, dtype