Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def pool_list(self, name_matches=None, pool_ids=None, category=None, description_matches=None, creator_name=None, creator_id=None, is_deleted=None, is_active=None, order=None): params = { 'search[name_matches]': name_matches, 'search[id]': pool_ids, 'search[description_matches]': description_matches, 'search[creator_name]': creator_name, 'search[creator_id]': creator_id, 'search[is_active]': is_active, 'search[is_deleted]': is_deleted, 'search[order]': order, 'search[category]': category } return self._get('pools.json', params)
[ "Get a list of pools.\n\n Parameters:\n name_matches (str):\n pool_ids (str): Can search for multiple ID's at once, separated by\n commas.\n description_matches (str):\n creator_name (str):\n creator_id (int):\n is_active (bool): Can be: true, false.\n is_deleted (bool): Can be: True, False.\n order (str): Can be: name, created_at, post_count, date.\n category (str): Can be: series, collection.\n " ]
Please provide a description of the function:def pool_create(self, name, description, category): params = { 'pool[name]': name, 'pool[description]': description, 'pool[category]': category } return self._get('pools.json', params, method='POST', auth=True)
[ "Function to create a pool (Requires login) (UNTESTED).\n\n Parameters:\n name (str): Pool name.\n description (str): Pool description.\n category (str): Can be: series, collection.\n " ]
Please provide a description of the function:def pool_update(self, pool_id, name=None, description=None, post_ids=None, is_active=None, category=None): params = { 'pool[name]': name, 'pool[description]': description, 'pool[post_ids]': post_ids, 'pool[is_active]': is_active, 'pool[category]': category } return self._get('pools/{0}.json'.format(pool_id), params, method='PUT', auth=True)
[ "Update a pool (Requires login) (UNTESTED).\n\n Parameters:\n pool_id (int): Where pool_id is the pool id.\n name (str):\n description (str):\n post_ids (str): List of space delimited post ids.\n is_active (int): Can be: 1, 0.\n category (str): Can be: series, collection.\n " ]
Please provide a description of the function:def pool_delete(self, pool_id): return self._get('pools/{0}.json'.format(pool_id), method='DELETE', auth=True)
[ "Delete a pool (Requires login) (UNTESTED) (Moderator+).\n\n Parameters:\n pool_id (int): Where pool_id is the pool id.\n " ]
Please provide a description of the function:def pool_undelete(self, pool_id): return self._get('pools/{0}/undelete.json'.format(pool_id), method='POST', auth=True)
[ "Undelete a specific poool (Requires login) (UNTESTED) (Moderator+).\n\n Parameters:\n pool_id (int): Where pool_id is the pool id.\n " ]
Please provide a description of the function:def pool_revert(self, pool_id, version_id): return self._get('pools/{0}/revert.json'.format(pool_id), {'version_id': version_id}, method='PUT', auth=True)
[ "Function to revert a specific pool (Requires login) (UNTESTED).\n\n Parameters:\n pool_id (int): Where pool_id is the pool id.\n version_id (int):\n " ]
Please provide a description of the function:def pool_versions(self, updater_id=None, updater_name=None, pool_id=None): params = { 'search[updater_id]': updater_id, 'search[updater_name]': updater_name, 'search[pool_id]': pool_id } return self._get('pool_versions.json', params)
[ "Get list of pool versions.\n\n Parameters:\n updater_id (int):\n updater_name (str):\n pool_id (int):\n " ]
Please provide a description of the function:def tag_list(self, name_matches=None, name=None, category=None, hide_empty=None, has_wiki=None, has_artist=None, order=None): params = { 'search[name_matches]': name_matches, 'search[name]': name, 'search[category]': category, 'search[hide_empty]': hide_empty, 'search[has_wiki]': has_wiki, 'search[has_artist]': has_artist, 'search[order]': order } return self._get('tags.json', params)
[ "Get a list of tags.\n\n Parameters:\n name_matches (str): Can be: part or full name.\n name (str): Allows searching for multiple tags with exact given\n names, separated by commas. e.g.\n search[name]=touhou,original,k-on! would return the\n three listed tags.\n category (str): Can be: 0, 1, 3, 4 (general, artist, copyright,\n character respectively).\n hide_empty (str): Can be: yes, no. Excludes tags with 0 posts\n when \"yes\".\n has_wiki (str): Can be: yes, no.\n has_artist (str): Can be: yes, no.\n order (str): Can be: name, date, count.\n " ]
Please provide a description of the function:def tag_update(self, tag_id, category): param = {'tag[category]': category} return self._get('pools/{0}.json'.format(tag_id), param, method='PUT', auth=True)
[ "Lets you update a tag (Requires login) (UNTESTED).\n\n Parameters:\n tag_id (int):\n category (str): Can be: 0, 1, 3, 4 (general, artist, copyright,\n character respectively).\n " ]
Please provide a description of the function:def tag_aliases(self, name_matches=None, antecedent_name=None, tag_id=None): params = { 'search[name_matches]': name_matches, 'search[antecedent_name]': antecedent_name, 'search[id]': tag_id } return self._get('tag_aliases.json', params)
[ "Get tags aliases.\n\n Parameters:\n name_matches (str): Match antecedent or consequent name.\n antecedent_name (str): Match antecedent name (exact match).\n tag_id (int): The tag alias id.\n " ]
Please provide a description of the function:def tag_implications(self, name_matches=None, antecedent_name=None, tag_id=None): params = { 'search[name_matches]': name_matches, 'search[antecedent_name]': antecedent_name, 'search[id]': tag_id } return self._get('tag_implications.json', params)
[ "Get tags implications.\n\n Parameters:\n name_matches (str): Match antecedent or consequent name.\n antecedent_name (str): Match antecedent name (exact match).\n tag_id (int): Tag implication id.\n " ]
Please provide a description of the function:def tag_related(self, query, category=None): params = {'query': query, 'category': category} return self._get('related_tag.json', params)
[ "Get related tags.\n\n Parameters:\n query (str): The tag to find the related tags for.\n category (str): If specified, show only tags of a specific\n category. Can be: General 0, Artist 1, Copyright\n 3 and Character 4.\n " ]
Please provide a description of the function:def wiki_list(self, title=None, creator_id=None, body_matches=None, other_names_match=None, creator_name=None, hide_deleted=None, other_names_present=None, order=None): params = { 'search[title]': title, 'search[creator_id]': creator_id, 'search[body_matches]': body_matches, 'search[other_names_match]': other_names_match, 'search[creator_name]': creator_name, 'search[hide_deleted]': hide_deleted, 'search[other_names_present]': other_names_present, 'search[order]': order } return self._get('wiki_pages.json', params)
[ "Function to retrieves a list of every wiki page.\n\n Parameters:\n title (str): Page title.\n creator_id (int): Creator id.\n body_matches (str): Page content.\n other_names_match (str): Other names.\n creator_name (str): Creator name.\n hide_deleted (str): Can be: yes, no.\n other_names_present (str): Can be: yes, no.\n order (str): Can be: date, title.\n " ]
Please provide a description of the function:def wiki_create(self, title, body, other_names=None): params = { 'wiki_page[title]': title, 'wiki_page[body]': body, 'wiki_page[other_names]': other_names } return self._get('wiki_pages.json', params, method='POST', auth=True)
[ "Action to lets you create a wiki page (Requires login) (UNTESTED).\n\n Parameters:\n title (str): Page title.\n body (str): Page content.\n other_names (str): Other names.\n " ]
Please provide a description of the function:def wiki_update(self, page_id, title=None, body=None, other_names=None, is_locked=None, is_deleted=None): params = { 'wiki_page[title]': title, 'wiki_page[body]': body, 'wiki_page[other_names]': other_names } return self._get('wiki_pages/{0}.json'.format(page_id), params, method='PUT', auth=True)
[ "Action to lets you update a wiki page (Requires login) (UNTESTED).\n\n Parameters:\n page_id (int): Whre page_id is the wiki page id.\n title (str): Page title.\n body (str): Page content.\n other_names (str): Other names.\n is_locked (int): Can be: 0, 1 (Builder+).\n is_deleted (int): Can be: 0, 1 (Builder+).\n " ]
Please provide a description of the function:def wiki_delete(self, page_id): return self._get('wiki_pages/{0}.json'.format(page_id), auth=True, method='DELETE')
[ "Delete a specific page wiki (Requires login) (UNTESTED) (Builder+).\n\n Parameters:\n page_id (int):\n " ]
Please provide a description of the function:def wiki_revert(self, wiki_page_id, version_id): return self._get('wiki_pages/{0}/revert.json'.format(wiki_page_id), {'version_id': version_id}, method='PUT', auth=True)
[ "Revert page to a previeous version (Requires login) (UNTESTED).\n\n Parameters:\n wiki_page_id (int): Where page_id is the wiki page id.\n version_id (int):\n " ]
Please provide a description of the function:def wiki_versions_list(self, page_id, updater_id): params = { 'earch[updater_id]': updater_id, 'search[wiki_page_id]': page_id } return self._get('wiki_page_versions.json', params)
[ "Return a list of wiki page version.\n\n Parameters:\n page_id (int):\n updater_id (int):\n " ]
Please provide a description of the function:def forum_topic_list(self, title_matches=None, title=None, category_id=None): params = { 'search[title_matches]': title_matches, 'search[title]': title, 'search[category_id]': category_id } return self._get('forum_topics.json', params)
[ "Function to get forum topics.\n\n Parameters:\n title_matches (str): Search body for the given terms.\n title (str): Exact title match.\n category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features\n respectively).\n " ]
Please provide a description of the function:def forum_topic_create(self, title, body, category=None): params = { 'forum_topic[title]': title, 'forum_topic[original_post_attributes][body]': body, 'forum_topic[category_id]': category } return self._get('forum_topics.json', params, method='POST', auth=True)
[ "Function to create topic (Requires login) (UNTESTED).\n\n Parameters:\n title (str): topic title.\n body (str): Message of the initial post.\n category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features\n respectively).\n " ]
Please provide a description of the function:def forum_topic_update(self, topic_id, title=None, category=None): params = { 'forum_topic[title]': title, 'forum_topic[category_id]': category } return self._get('forum_topics/{0}.json'.format(topic_id), params, method='PUT', auth=True)
[ "Update a specific topic (Login Requires) (UNTESTED).\n\n Parameters:\n topic_id (int): Where topic_id is the topic id.\n title (str): Topic title.\n category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features\n respectively).\n " ]
Please provide a description of the function:def forum_topic_delete(self, topic_id): return self._get('forum_topics/{0}.json'.format(topic_id), method='DELETE', auth=True)
[ "Delete a topic (Login Requires) (Moderator+) (UNTESTED).\n\n Parameters:\n topic_id (int): Where topic_id is the topic id.\n " ]
Please provide a description of the function:def forum_topic_undelete(self, topic_id): return self._get('forum_topics/{0}/undelete.json'.format(topic_id), method='POST', auth=True)
[ "Un delete a topic (Login requries) (Moderator+) (UNTESTED).\n\n Parameters:\n topic_id (int): Where topic_id is the topic id.\n " ]
Please provide a description of the function:def forum_post_list(self, creator_id=None, creator_name=None, topic_id=None, topic_title_matches=None, topic_category_id=None, body_matches=None): params = { 'search[creator_id]': creator_id, 'search[creator_name]': creator_name, 'search[topic_id]': topic_id, 'search[topic_title_matches]': topic_title_matches, 'search[topic_category_id]': topic_category_id, 'search[body_matches]': body_matches } return self._get('forum_posts.json', params)
[ "Return a list of forum posts.\n\n Parameters:\n creator_id (int):\n creator_name (str):\n topic_id (int):\n topic_title_matches (str):\n topic_category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs &\n Features respectively).\n body_matches (str): Can be part of the post content.\n " ]
Please provide a description of the function:def forum_post_create(self, topic_id, body): params = {'forum_post[topic_id]': topic_id, 'forum_post[body]': body} return self._get('forum_posts.json', params, method='POST', auth=True)
[ "Create a forum post (Requires login).\n\n Parameters:\n topic_id (int):\n body (str): Post content.\n " ]
Please provide a description of the function:def forum_post_update(self, topic_id, body): params = {'forum_post[body]': body} return self._get('forum_posts/{0}.json'.format(topic_id), params, method='PUT', auth=True)
[ "Update a specific forum post (Requries login)(Moderator+)(UNTESTED).\n\n Parameters:\n post_id (int): Forum topic id.\n body (str): Post content.\n " ]
Please provide a description of the function:def forum_post_delete(self, post_id): return self._get('forum_posts/{0}.json'.format(post_id), method='DELETE', auth=True)
[ "Delete a specific forum post (Requires login)(Moderator+)(UNTESTED).\n\n Parameters:\n post_id (int): Forum post id.\n " ]
Please provide a description of the function:def forum_post_undelete(self, post_id): return self._get('forum_posts/{0}/undelete.json'.format(post_id), method='POST', auth=True)
[ "Undelete a specific forum post (Requires login)(Moderator+)(UNTESTED).\n\n Parameters:\n post_id (int): Forum post id.\n " ]
Please provide a description of the function:def site_name(self, site_name): if site_name in SITE_LIST: self.__site_name = site_name self.__site_url = SITE_LIST[site_name]['url'] else: raise PybooruError( "The 'site_name' is not valid, specify a valid 'site_name'.")
[ "Function that sets and checks the site name and set url.\n\n Parameters:\n site_name (str): The site name in 'SITE_LIST', default sites.\n\n Raises:\n PybooruError: When 'site_name' isn't valid.\n " ]
Please provide a description of the function:def site_url(self, url): # Regular expression to URL validate regex = re.compile( r'^(?:http|https)://' # Scheme only HTTP/HTTPS r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?| \ [A-Z0-9-]{2,}(?<!-)\.?)|' # Domain r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # or ipv6 r'(?::\d+)?' # Port r'(?:/?|[/?]\S+)$', re.IGNORECASE) # Validate URL if re.match('^(?:http|https)://', url): if re.search(regex, url): self.__site_url = url else: raise PybooruError("Invalid URL: {0}".format(url)) else: raise PybooruError( "Invalid URL scheme, use HTTP or HTTPS: {0}".format(url))
[ "URL setter and validator for site_url property.\n\n Parameters:\n url (str): URL of on Moebooru/Danbooru based sites.\n\n Raises:\n PybooruError: When URL scheme or URL are invalid.\n " ]
Please provide a description of the function:def _request(self, url, api_call, request_args, method='GET'): try: if method != 'GET': # Reset content-type for data encoded as a multipart form self.client.headers.update({'content-type': None}) response = self.client.request(method, url, **request_args) self.last_call.update({ 'API': api_call, 'url': response.url, 'status_code': response.status_code, 'status': self._get_status(response.status_code), 'headers': response.headers }) if response.status_code in (200, 201, 202, 204): return response.json() raise PybooruHTTPError("In _request", response.status_code, response.url) except requests.exceptions.Timeout: raise PybooruError("Timeout! url: {0}".format(response.url)) except ValueError as e: raise PybooruError("JSON Error: {0} in line {1} column {2}".format( e.msg, e.lineno, e.colno))
[ "Function to request and returning JSON data.\n\n Parameters:\n url (str): Base url call.\n api_call (str): API function to be called.\n request_args (dict): All requests parameters.\n method (str): (Defauld: GET) HTTP method 'GET' or 'POST'\n\n Raises:\n PybooruHTTPError: HTTP Error.\n requests.exceptions.Timeout: When HTTP Timeout.\n ValueError: When can't decode JSON response.\n " ]
Please provide a description of the function:def _get(self, api_call, params=None, method='GET', auth=False, file_=None): url = "{0}/{1}".format(self.site_url, api_call) if method == 'GET': request_args = {'params': params} else: request_args = {'data': params, 'files': file_} # Adds auth. Also adds auth if username and api_key are specified # Members+ have less restrictions if auth or (self.username and self.api_key): if self.username and self.api_key: request_args['auth'] = (self.username, self.api_key) else: raise PybooruError("'username' and 'api_key' attribute of " "Danbooru are required.") # Do call return self._request(url, api_call, request_args, method)
[ "Function to preapre API call.\n\n Parameters:\n api_call (str): API function to be called.\n params (str): API function parameters.\n method (str): (Defauld: GET) HTTP method (GET, POST, PUT or\n DELETE)\n file_ (file): File to upload (only uploads).\n\n Raise:\n PybooruError: When 'username' or 'api_key' are not set.\n " ]
Please provide a description of the function:def post_create(self, tags, file_=None, rating=None, source=None, rating_locked=None, note_locked=None, parent_id=None, md5=None): if file_ or source is not None: params = { 'post[tags]': tags, 'post[source]': source, 'post[rating]': rating, 'post[is_rating_locked]': rating_locked, 'post[is_note_locked]': note_locked, 'post[parent_id]': parent_id, 'md5': md5} file_ = {'post[file]': open(file_, 'rb')} return self._get('post/create', params, 'POST', file_) else: raise PybooruAPIError("'file_' or 'source' is required.")
[ "Function to create a new post (Requires login).\n\n There are only two mandatory fields: you need to supply the\n 'tags', and you need to supply the 'file_', either through a\n multipart form or through a source URL (Requires login) (UNTESTED).\n\n Parameters:\n tags (str): A space delimited list of tags.\n file_ (str): The file data encoded as a multipart form. Path of\n content.\n rating (str): The rating for the post. Can be: safe, questionable,\n or explicit.\n source (str): If this is a URL, Moebooru will download the file.\n rating_locked (bool): Set to True to prevent others from changing\n the rating.\n note_locked (bool): Set to True to prevent others from adding notes.\n parent_id (int): The ID of the parent post.\n md5 (str): Supply an MD5 if you want Moebooru to verify the file\n after uploading. If the MD5 doesn't match, the post is\n destroyed.\n\n Raises:\n PybooruAPIError: When file or source are empty.\n " ]
Please provide a description of the function:def post_update(self, post_id, tags=None, file_=None, rating=None, source=None, is_rating_locked=None, is_note_locked=None, parent_id=None): params = { 'id': post_id, 'post[tags]': tags, 'post[rating]': rating, 'post[source]': source, 'post[is_rating_locked]': is_rating_locked, 'post[is_note_locked]': is_note_locked, 'post[parent_id]': parent_id } if file_ is not None: file_ = {'post[file]': open(file_, 'rb')} return self._get('post/update', params, 'PUT', file_) else: return self._get('post/update', params, 'PUT')
[ "Update a specific post.\n\n Only the 'post_id' parameter is required. Leave the other parameters\n blank if you don't want to change them (Requires login).\n\n Parameters:\n post_id (int): The id number of the post to update.\n tags (str): A space delimited list of tags. Specify previous tags.\n file_ (str): The file data ENCODED as a multipart form.\n rating (str): The rating for the post. Can be: safe, questionable,\n or explicit.\n source (str): If this is a URL, Moebooru will download the file.\n rating_locked (bool): Set to True to prevent others from changing\n the rating.\n note_locked (bool): Set to True to prevent others from adding\n notes.\n parent_id (int): The ID of the parent post.\n " ]
Please provide a description of the function:def post_vote(self, post_id, score): if score <= 3 and score >= 0: params = {'id': post_id, 'score': score} return self._get('post/vote', params, 'POST') else: raise PybooruAPIError("Value of 'score' only can be 0, 1, 2 or 3.")
[ "Action lets you vote for a post (Requires login).\n\n Parameters:\n post_id (int): The post id.\n score (int):\n * 0: No voted or Remove vote.\n * 1: Good.\n * 2: Great.\n * 3: Favorite, add post to favorites.\n\n Raises:\n PybooruAPIError: When score is > 3.\n " ]
Please provide a description of the function:def tag_update(self, name=None, tag_type=None, is_ambiguous=None): params = { 'name': name, 'tag[tag_type]': tag_type, 'tag[is_ambiguous]': is_ambiguous } return self._get('tag/update', params, 'PUT')
[ "Action to lets you update tag (Requires login) (UNTESTED).\n\n Parameters:\n name (str): The name of the tag to update.\n tag_type (int):\n * General: 0.\n * artist: 1.\n * copyright: 3.\n * character: 4.\n is_ambiguous (int): Whether or not this tag is ambiguous. Use 1\n for True and 0 for False.\n " ]
Please provide a description of the function:def artist_create(self, name, urls=None, alias=None, group=None): params = { 'artist[name]': name, 'artist[urls]': urls, 'artist[alias]': alias, 'artist[group]': group } return self._get('artist/create', params, method='POST')
[ "Function to create an artist (Requires login) (UNTESTED).\n\n Parameters:\n name (str): The artist's name.\n urls (str): A list of URLs associated with the artist, whitespace\n delimited.\n alias (str): The artist that this artist is an alias for. Simply\n enter the alias artist's name.\n group (str): The group or cicle that this artist is a member of.\n Simply:param enter the group's name.\n " ]
Please provide a description of the function:def artist_update(self, artist_id, name=None, urls=None, alias=None, group=None): params = { 'id': artist_id, 'artist[name]': name, 'artist[urls]': urls, 'artist[alias]': alias, 'artist[group]': group } return self._get('artist/update', params, method='PUT')
[ "Function to update artists (Requires Login) (UNTESTED).\n\n Only the artist_id parameter is required. The other parameters are\n optional.\n\n Parameters:\n artist_id (int): The id of thr artist to update (Type: INT).\n name (str): The artist's name.\n urls (str): A list of URLs associated with the artist, whitespace\n delimited.\n alias (str): The artist that this artist is an alias for. Simply\n enter the alias artist's name.\n group (str): The group or cicle that this artist is a member of.\n Simply enter the group's name.\n " ]
Please provide a description of the function:def comment_create(self, post_id, comment_body, anonymous=None): params = { 'comment[post_id]': post_id, 'comment[body]': comment_body, 'comment[anonymous]': anonymous } return self._get('comment/create', params, method='POST')
[ "Action to lets you create a comment (Requires login).\n\n Parameters:\n post_id (int): The post id number to which you are responding.\n comment_body (str): The body of the comment.\n anonymous (int): Set to 1 if you want to post this comment\n anonymously.\n " ]
Please provide a description of the function:def wiki_create(self, title, body): params = {'wiki_page[title]': title, 'wiki_page[body]': body} return self._get('wiki/create', params, method='POST')
[ "Action to lets you create a wiki page (Requires login) (UNTESTED).\n\n Parameters:\n title (str): The title of the wiki page.\n body (str): The body of the wiki page.\n " ]
Please provide a description of the function:def wiki_update(self, title, new_title=None, page_body=None): params = { 'title': title, 'wiki_page[title]': new_title, 'wiki_page[body]': page_body } return self._get('wiki/update', params, method='PUT')
[ "Action to lets you update a wiki page (Requires login) (UNTESTED).\n\n Parameters:\n title (str): The title of the wiki page to update.\n new_title (str): The new title of the wiki page.\n page_body (str): The new body of the wiki page.\n " ]
Please provide a description of the function:def note_revert(self, note_id, version): params = {'id': note_id, 'version': version} return self._get('note/revert', params, method='PUT')
[ "Function to revert a specific note (Requires login) (UNTESTED).\n\n Parameters:\n note_id (int): The note id to update.\n version (int): The version to revert to.\n " ]
Please provide a description of the function:def pool_update(self, pool_id, name=None, is_public=None, description=None): params = { 'id': pool_id, 'pool[name]': name, 'pool[is_public]': is_public, 'pool[description]': description } return self._get('pool/update', params, method='PUT')
[ "Function to update a pool (Requires login) (UNTESTED).\n\n Parameters:\n pool_id (int): The pool id number.\n name (str): The name.\n is_public (int): 1 or 0, whether or not the pool is public.\n description (str): A description of the pool.\n " ]
Please provide a description of the function:def pool_create(self, name, description, is_public): params = {'pool[name]': name, 'pool[description]': description, 'pool[is_public]': is_public} return self._get('pool/create', params, method='POST')
[ "Function to create a pool (Require login) (UNTESTED).\n\n Parameters:\n name (str): The name.\n description (str): A description of the pool.\n is_public (int): 1 or 0, whether or not the pool is public.\n " ]
Please provide a description of the function:def site_name(self, site_name): # Set base class property site_name _Pybooru.site_name.fset(self, site_name) if ('api_version' and 'hashed_string') in SITE_LIST[site_name]: self.api_version = SITE_LIST[site_name]['api_version'] self.hash_string = SITE_LIST[site_name]['hashed_string']
[ "Sets api_version and hash_string.\n\n Parameters:\n site_name (str): The site name in 'SITE_LIST', default sites.\n\n Raises:\n PybooruError: When 'site_name' isn't valid.\n " ]
Please provide a description of the function:def _build_url(self, api_call): if self.api_version in ('1.13.0', '1.13.0+update.1', '1.13.0+update.2'): if '/' not in api_call: return "{0}/{1}/index.json".format(self.site_url, api_call) return "{0}/{1}.json".format(self.site_url, api_call)
[ "Build request url.\n\n Parameters:\n api_call (str): Base API Call.\n\n Returns:\n Complete url (str).\n " ]
Please provide a description of the function:def _build_hash_string(self): # Build AUTENTICATION hash_string # Check if hash_string exists if self.site_name in SITE_LIST or self.hash_string: if self.username and self.password: try: hash_string = self.hash_string.format(self.password) except TypeError: raise PybooruError("Pybooru can't add 'password' " "to 'hash_string'") # encrypt hashed_string to SHA1 and return hexdigest string self.password_hash = hashlib.sha1( hash_string.encode('utf-8')).hexdigest() else: raise PybooruError("Specify the 'username' and 'password' " "parameters of the Pybooru object, for " "setting 'password_hash' attribute.") else: raise PybooruError( "Specify the 'hash_string' parameter of the Pybooru" " object, for the functions that requires login.")
[ "Function for build password hash string.\n\n Raises:\n PybooruError: When isn't provide hash string.\n PybooruError: When aren't provide username or password.\n PybooruError: When Pybooru can't add password to hash strring.\n " ]
Please provide a description of the function:def _get(self, api_call, params, method='GET', file_=None): url = self._build_url(api_call) if method == 'GET': request_args = {'params': params} else: if self.password_hash is None: self._build_hash_string() # Set login params['login'] = self.username params['password_hash'] = self.password_hash request_args = {'data': params, 'files': file_} # Do call return self._request(url, api_call, request_args, method)
[ "Function to preapre API call.\n\n Parameters:\n api_call (str): API function to be called.\n params (dict): API function parameters.\n method (str): (Defauld: GET) HTTP method 'GET' or 'POST'\n file_ (file): File to upload.\n " ]
Please provide a description of the function:def _is_autonomous(indep, exprs): if indep is None: return True for expr in exprs: try: in_there = indep in expr.free_symbols except: in_there = expr.has(indep) if in_there: return False return True
[ " Whether the expressions for the dependent variables are autonomous.\n\n Note that the system may still behave as an autonomous system on the interface\n of :meth:`integrate` due to use of pre-/post-processors.\n " ]
Please provide a description of the function:def symmetricsys(dep_tr=None, indep_tr=None, SuperClass=TransformedSys, **kwargs): if dep_tr is not None: if not callable(dep_tr[0]) or not callable(dep_tr[1]): raise ValueError("Exceptected dep_tr to be a pair of callables") if indep_tr is not None: if not callable(indep_tr[0]) or not callable(indep_tr[1]): raise ValueError("Exceptected indep_tr to be a pair of callables") class _SymmetricSys(SuperClass): def __init__(self, dep_exprs, indep=None, **inner_kwargs): new_kwargs = kwargs.copy() new_kwargs.update(inner_kwargs) dep, exprs = zip(*dep_exprs) super(_SymmetricSys, self).__init__( zip(dep, exprs), indep, dep_transf=list(zip( list(map(dep_tr[0], dep)), list(map(dep_tr[1], dep)) )) if dep_tr is not None else None, indep_transf=((indep_tr[0](indep), indep_tr[1](indep)) if indep_tr is not None else None), **new_kwargs) @classmethod def from_callback(cls, cb, ny=None, nparams=None, **inner_kwargs): new_kwargs = kwargs.copy() new_kwargs.update(inner_kwargs) return SuperClass.from_callback( cb, ny, nparams, dep_transf_cbs=repeat(dep_tr) if dep_tr is not None else None, indep_transf_cbs=indep_tr, **new_kwargs) return _SymmetricSys
[ " A factory function for creating symmetrically transformed systems.\n\n Creates a new subclass which applies the same transformation for each dependent variable.\n\n Parameters\n ----------\n dep_tr : pair of callables (default: None)\n Forward and backward transformation callbacks to be applied to the\n dependent variables.\n indep_tr : pair of callables (default: None)\n Forward and backward transformation to be applied to the\n independent variable.\n SuperClass : class\n \\*\\*kwargs :\n Default keyword arguments for the TransformedSys subclass.\n\n Returns\n -------\n Subclass of SuperClass (by default :class:`TransformedSys`).\n\n Examples\n --------\n >>> import sympy\n >>> logexp = (sympy.log, sympy.exp)\n >>> def psimp(exprs):\n ... return [sympy.powsimp(expr.expand(), force=True) for expr in exprs]\n ...\n >>> LogLogSys = symmetricsys(logexp, logexp, exprs_process_cb=psimp)\n >>> mysys = LogLogSys.from_callback(lambda x, y, p: [-y[0], y[0] - y[1]], 2, 0)\n >>> mysys.exprs\n (-exp(x_0), -exp(x_0) + exp(x_0 + y_0 - y_1))\n\n " ]
Please provide a description of the function:def get_logexp(a=1, b=0, a2=None, b2=None, backend=None): if a2 is None: a2 = a if b2 is None: b2 = b if backend is None: import sympy as backend return (lambda x: backend.log(a*x + b), lambda x: (backend.exp(x) - b2)/a2)
[ " Utility function for use with :func:symmetricsys.\n\n Creates a pair of callbacks for logarithmic transformation\n (including scaling and shifting): ``u = ln(a*x + b)``.\n\n Parameters\n ----------\n a : number\n Scaling (forward).\n b : number\n Shift (forward).\n a2 : number\n Scaling (backward).\n b2 : number\n Shift (backward).\n\n Returns\n -------\n Pair of callbacks.\n\n " ]
Please provide a description of the function:def from_callback(cls, rhs, ny=None, nparams=None, first_step_factory=None, roots_cb=None, indep_name=None, **kwargs): ny, nparams = _get_ny_nparams_from_kw(ny, nparams, kwargs) be = Backend(kwargs.pop('backend', None)) names = tuple(kwargs.pop('names', '')) indep_name = indep_name or _get_indep_name(names) try: x = be.Symbol(indep_name, real=True) except TypeError: x = be.Symbol(indep_name) y = be.real_symarray('y', ny) p = be.real_symarray('p', nparams) _y = dict(zip(names, y)) if kwargs.get('dep_by_name', False) else y _p = dict(zip(kwargs['param_names'], p)) if kwargs.get('par_by_name', False) else p try: exprs = rhs(x, _y, _p, be) except TypeError: exprs = _ensure_4args(rhs)(x, _y, _p, be) try: if len(exprs) != ny: raise ValueError("Callback returned unexpected (%d) number of expressions: %d" % (ny, len(exprs))) except TypeError: raise ValueError("Callback did not return an array_like of expressions: %s" % str(exprs)) cls._kwargs_roots_from_roots_cb(roots_cb, kwargs, x, _y, _p, be) if first_step_factory is not None: if 'first_step_exprs' in kwargs: raise ValueError("Cannot override first_step_exprs.") try: kwargs['first_step_expr'] = first_step_factory(x, _y, _p, be) except TypeError: kwargs['first_step_expr'] = _ensure_4args(first_step_factory)(x, _y, _p, be) if kwargs.get('dep_by_name', False): exprs = [exprs[k] for k in names] return cls(zip(y, exprs), x, kwargs.pop('params', None) if len(p) == 0 else p, backend=be, names=names, **kwargs)
[ " Create an instance from a callback.\n\n Parameters\n ----------\n rhs : callbable\n Signature ``rhs(x, y[:], p[:], backend=math) -> f[:]``.\n ny : int\n Length of ``y`` in ``rhs``.\n nparams : int\n Length of ``p`` in ``rhs``.\n first_step_factory : callabble\n Signature ``step1st(x, y[:], p[:]) -> dx0``.\n roots_cb : callable\n Callback with signature ``roots(x, y[:], p[:], backend=math) -> r[:]``.\n indep_name : str\n Default 'x' if not already in ``names``, otherwise indep0, or indep1, or ...\n dep_by_name : bool\n Make ``y`` passed to ``rhs`` a dict (keys from :attr:`names`) and convert\n its return value from dict to array.\n par_by_name : bool\n Make ``p`` passed to ``rhs`` a dict (keys from :attr:`param_names`).\n \\*\\*kwargs :\n Keyword arguments passed onto :class:`SymbolicSys`.\n\n Examples\n --------\n >>> def decay(x, y, p, backend=None):\n ... rate = y['Po-210']*p[0]\n ... return {'Po-210': -rate, 'Pb-206': rate}\n ...\n >>> odesys = SymbolicSys.from_callback(decay, dep_by_name=True, names=('Po-210', 'Pb-206'), nparams=1)\n >>> xout, yout, info = odesys.integrate([0, 138.4*24*3600], {'Po-210': 1.0, 'Pb-206': 0.0}, [5.798e-8])\n >>> import numpy as np; np.allclose(yout[-1, :], [0.5, 0.5], rtol=1e-3, atol=1e-3)\n True\n\n\n Returns\n -------\n An instance of :class:`SymbolicSys`.\n " ]
Please provide a description of the function:def from_other(cls, ori, **kwargs): for k in cls._attrs_to_copy + ('params', 'roots', 'init_indep', 'init_dep'): if k not in kwargs: val = getattr(ori, k) if val is not None: kwargs[k] = val if 'lower_bounds' not in kwargs and getattr(ori, 'lower_bounds') is not None: kwargs['lower_bounds'] = ori.lower_bounds if 'upper_bounds' not in kwargs and getattr(ori, 'upper_bounds') is not None: kwargs['upper_bounds'] = ori.upper_bounds if len(ori.pre_processors) > 0: if 'pre_processors' not in kwargs: kwargs['pre_processors'] = [] kwargs['pre_processors'] = kwargs['pre_processors'] + ori.pre_processors if len(ori.post_processors) > 0: if 'post_processors' not in kwargs: kwargs['post_processors'] = [] kwargs['post_processors'] = ori.post_processors + kwargs['post_processors'] if 'dep_exprs' not in kwargs: kwargs['dep_exprs'] = zip(ori.dep, ori.exprs) if 'indep' not in kwargs: kwargs['indep'] = ori.indep instance = cls(**kwargs) for attr in ori._attrs_to_copy: if attr not in cls._attrs_to_copy: setattr(instance, attr, getattr(ori, attr)) return instance
[ " Creates a new instance with an existing one as a template.\n\n Parameters\n ----------\n ori : SymbolicSys instance\n \\\\*\\\\*kwargs:\n Keyword arguments used to create the new instance.\n\n Returns\n -------\n A new instance of the class.\n\n " ]
Please provide a description of the function:def from_other_new_params(cls, ori, par_subs, new_pars, new_par_names=None, new_latex_par_names=None, **kwargs): new_exprs = [expr.subs(par_subs) for expr in ori.exprs] drop_idxs = [ori.params.index(par) for par in par_subs] params = _skip(drop_idxs, ori.params, False) + list(new_pars) back_substitute = _Callback(ori.indep, ori.dep, params, list(par_subs.values()), Lambdify=ori.be.Lambdify) def recalc_params(t, y, p): rev = back_substitute(t, y, p) return _reinsert(drop_idxs, np.repeat(np.atleast_2d(p), rev.shape[0], axis=0), rev)[..., :len(ori.params)] return cls.from_other( ori, dep_exprs=zip(ori.dep, new_exprs), params=params, param_names=_skip(drop_idxs, ori.param_names, False) + list(new_par_names or []), latex_param_names=_skip(drop_idxs, ori.latex_param_names, False) + list(new_latex_par_names or []), **kwargs ), {'recalc_params': recalc_params}
[ " Creates a new instance with an existing one as a template (with new parameters)\n\n Calls ``.from_other`` but first it replaces some parameters according to ``par_subs``\n and (optionally) introduces new parameters given in ``new_pars``.\n\n Parameters\n ----------\n ori : SymbolicSys instance\n par_subs : dict\n Dictionary with substitutions (mapping symbols to new expressions) for parameters.\n Parameters appearing in this instance will be omitted in the new instance.\n new_pars : iterable (optional)\n Iterable of symbols for new parameters.\n new_par_names : iterable of str\n Names of the new parameters given in ``new_pars``.\n new_latex_par_names : iterable of str\n TeX formatted names of the new parameters given in ``new_pars``.\n \\\\*\\\\*kwargs:\n Keyword arguments passed to ``.from_other``.\n\n Returns\n -------\n Intance of the class\n extra : dict with keys:\n - recalc_params : ``f(t, y, p1) -> p0``\n\n " ]
Please provide a description of the function:def from_other_new_params_by_name(cls, ori, par_subs, new_par_names=(), **kwargs): if not ori.dep_by_name: warnings.warn('dep_by_name is not True') if not ori.par_by_name: warnings.warn('par_by_name is not True') dep = dict(zip(ori.names, ori.dep)) new_pars = ori.be.real_symarray( 'p', len(ori.params) + len(new_par_names))[len(ori.params):] par = dict(chain(zip(ori.param_names, ori.params), zip(new_par_names, new_pars))) par_symb_subs = OrderedDict([(ori.params[ori.param_names.index(pk)], cb( ori.indep, dep, par, backend=ori.be)) for pk, cb in par_subs.items()]) return cls.from_other_new_params( ori, par_symb_subs, new_pars, new_par_names=new_par_names, **kwargs)
[ " Creates a new instance with an existing one as a template (with new parameters)\n\n Calls ``.from_other_new_params`` but first it creates the new instances from user provided\n callbacks generating the expressions the parameter substitutions.\n\n Parameters\n ----------\n ori : SymbolicSys instance\n par_subs : dict mapping str to ``f(t, y{}, p{}) -> expr``\n User provided callbacks for parameter names in ``ori``.\n new_par_names : iterable of str\n \\\\*\\\\*kwargs:\n Keyword arguments passed to ``.from_other_new_params``.\n\n " ]
Please provide a description of the function:def get_jac(self): if self._jac is True: if self.sparse is True: self._jac, self._colptrs, self._rowvals = self.be.sparse_jacobian_csc(self.exprs, self.dep) elif self.band is not None: # Banded self._jac = self.be.banded_jacobian(self.exprs, self.dep, *self.band) else: f = self.be.Matrix(1, self.ny, self.exprs) self._jac = f.jacobian(self.be.Matrix(1, self.ny, self.dep)) elif self._jac is False: return False return self._jac
[ " Derives the jacobian from ``self.exprs`` and ``self.dep``. " ]
Please provide a description of the function:def get_jtimes(self): if self._jtimes is False: return False if self._jtimes is True: r = self.be.Dummy('r') v = tuple(self.be.Dummy('v_{0}'.format(i)) for i in range(self.ny)) f = self.be.Matrix(1, self.ny, self.exprs) f = f.subs([(x_i, x_i + r * v_i) for x_i, v_i in zip(self.dep, v)]) return v, self.be.flatten(f.diff(r).subs(r, 0)) else: return tuple(zip(*self._jtimes))
[ " Derive the jacobian-vector product from ``self.exprs`` and ``self.dep``" ]
Please provide a description of the function:def jacobian_singular(self): cses, (jac_in_cses,) = self.be.cse(self.get_jac()) if jac_in_cses.nullspace(): return True else: return False
[ " Returns True if Jacobian is singular, else False. " ]
Please provide a description of the function:def get_dfdx(self): if self._dfdx is True: if self.indep is None: zero = 0*self.be.Dummy()**0 self._dfdx = self.be.Matrix(1, self.ny, [zero]*self.ny) else: self._dfdx = self.be.Matrix(1, self.ny, [expr.diff(self.indep) for expr in self.exprs]) elif self._dfdx is False: return False return self._dfdx
[ " Calculates 2nd derivatives of ``self.exprs`` " ]
Please provide a description of the function:def get_f_ty_callback(self): cb = self._callback_factory(self.exprs) lb = self.lower_bounds ub = self.upper_bounds if lb is not None or ub is not None: def _bounds_wrapper(t, y, p=(), be=None): if lb is not None: if np.any(y < lb - 10*self._current_integration_kwargs['atol']): raise RecoverableError y = np.array(y) y[y < lb] = lb[y < lb] if ub is not None: if np.any(y > ub + 10*self._current_integration_kwargs['atol']): raise RecoverableError y = np.array(y) y[y > ub] = ub[y > ub] return cb(t, y, p, be) return _bounds_wrapper else: return cb
[ " Generates a callback for evaluating ``self.exprs``. " ]
Please provide a description of the function:def get_j_ty_callback(self): j_exprs = self.get_jac() if j_exprs is False: return None cb = self._callback_factory(j_exprs) if self.sparse: from scipy.sparse import csc_matrix def sparse_cb(x, y, p=()): data = cb(x, y, p).flatten() return csc_matrix((data, self._rowvals, self._colptrs)) return sparse_cb else: return cb
[ " Generates a callback for evaluating the jacobian. " ]
Please provide a description of the function:def get_dfdx_callback(self): dfdx_exprs = self.get_dfdx() if dfdx_exprs is False: return None return self._callback_factory(dfdx_exprs)
[ " Generate a callback for evaluating derivative of ``self.exprs`` " ]
Please provide a description of the function:def get_jtimes_callback(self): jtimes = self.get_jtimes() if jtimes is False: return None v, jtimes_exprs = jtimes return _Callback(self.indep, tuple(self.dep) + tuple(v), self.params, jtimes_exprs, Lambdify=self.be.Lambdify)
[ " Generate a callback fro evaluating the jacobian-vector product." ]
Please provide a description of the function:def from_callback(cls, cb, ny=None, nparams=None, dep_transf_cbs=None, indep_transf_cbs=None, roots_cb=None, **kwargs): ny, nparams = _get_ny_nparams_from_kw(ny, nparams, kwargs) be = Backend(kwargs.pop('backend', None)) x, = be.real_symarray('x', 1) y = be.real_symarray('y', ny) p = be.real_symarray('p', nparams) _y = dict(zip(kwargs['names'], y)) if kwargs.get('dep_by_name', False) else y _p = dict(zip(kwargs['param_names'], p)) if kwargs.get('par_by_name', False) else p exprs = _ensure_4args(cb)(x, _y, _p, be) if dep_transf_cbs is not None: dep_transf = [(fw(yi), bw(yi)) for (fw, bw), yi in zip(dep_transf_cbs, y)] else: dep_transf = None if indep_transf_cbs is not None: indep_transf = indep_transf_cbs[0](x), indep_transf_cbs[1](x) else: indep_transf = None if kwargs.get('dep_by_name', False): exprs = [exprs[k] for k in kwargs['names']] cls._kwargs_roots_from_roots_cb(roots_cb, kwargs, x, _y, _p, be) return cls(list(zip(y, exprs)), x, dep_transf, indep_transf, p, backend=be, **kwargs)
[ "\n Create an instance from a callback.\n\n Analogous to :func:`SymbolicSys.from_callback`.\n\n Parameters\n ----------\n cb : callable\n Signature ``rhs(x, y[:], p[:]) -> f[:]``\n ny : int\n length of y\n nparams : int\n length of p\n dep_transf_cbs : iterable of pairs callables\n callables should have the signature ``f(yi) -> expression`` in yi\n indep_transf_cbs : pair of callbacks\n callables should have the signature ``f(x) -> expression`` in x\n roots_cb : callable\n Callback with signature ``roots(x, y[:], p[:], backend=math) -> r[:]``.\n Callback should return untransformed roots.\n \\*\\*kwargs :\n Keyword arguments passed onto :class:`TransformedSys`.\n\n " ]
Please provide a description of the function:def from_callback(cls, cb, ny=None, nparams=None, dep_scaling=1, indep_scaling=1, **kwargs): return TransformedSys.from_callback( cb, ny, nparams, dep_transf_cbs=repeat(cls._scale_fw_bw(dep_scaling)), indep_transf_cbs=cls._scale_fw_bw(indep_scaling), **kwargs )
[ "\n Create an instance from a callback.\n\n Analogous to :func:`SymbolicSys.from_callback`.\n\n Parameters\n ----------\n cb : callable\n Signature rhs(x, y[:], p[:]) -> f[:]\n ny : int\n length of y\n nparams : int\n length of p\n dep_scaling : number (>0) or iterable of numbers\n scaling of the dependent variables (default: 1)\n indep_scaling: number (>0)\n scaling of the independent variable (default: 1)\n \\*\\*kwargs :\n Keyword arguments passed onto :class:`ScaledSys`.\n\n Examples\n --------\n >>> def f(x, y, p):\n ... return [p[0]*y[0]**2]\n >>> odesys = ScaledSys.from_callback(f, 1, 1, dep_scaling=10)\n >>> odesys.exprs\n (p_0*y_0**2/10,)\n\n " ]
Please provide a description of the function:def from_linear_invariants(cls, ori_sys, preferred=None, **kwargs): _be = ori_sys.be A = _be.Matrix(ori_sys.linear_invariants) rA, pivots = A.rref() if len(pivots) < A.shape[0]: # If the linear system contains rows which a linearly dependent these could be removed. # The criterion for removal could be dictated by a user provided callback. # # An alternative would be to write the matrix in reduced row echelon form, however, # this would cause the invariants to become linear combinations of each other and # their intuitive meaning (original principles they were formulated from) will be lost. # Hence that is not the default behaviour. However, the user may choose to rewrite the # equations in reduced row echelon form if they choose to before calling this method. raise NotImplementedError("Linear invariants contain linear dependencies.") per_row_cols = [(ri, [ci for ci in range(A.cols) if A[ri, ci] != 0]) for ri in range(A.rows)] if preferred is None: preferred = ori_sys.names[:A.rows] if ori_sys.dep_by_name else list(range(A.rows)) targets = [ ori_sys.names.index(dep) if ori_sys.dep_by_name else ( dep if isinstance(dep, int) else ori_sys.dep.index(dep)) for dep in preferred] row_tgt = [] for ri, colids in sorted(per_row_cols, key=lambda k: len(k[1])): for tgt in targets: if tgt in colids: row_tgt.append((ri, tgt)) targets.remove(tgt) break if len(targets) == 0: break else: raise ValueError("Could not find a solutions for: %s" % targets) def analytic_factory(x0, y0, p0, be): return { ori_sys.dep[tgt]: y0[ori_sys.dep[tgt] if ori_sys.dep_by_name else tgt] - sum( [A[ri, ci]*(ori_sys.dep[ci] - y0[ori_sys.dep[ci] if ori_sys.dep_by_name else ci]) for ci in range(A.cols) if ci != tgt])/A[ri, tgt] for ri, tgt in row_tgt } ori_li_nms = ori_sys.linear_invariant_names or () new_lin_invar = [[cell for ci, cell in enumerate(row) if ci not in list(zip(*row_tgt))[1]] for ri, row in enumerate(A.tolist()) if ri not in list(zip(*row_tgt))[0]] new_lin_i_nms = [nam for ri, nam in enumerate(ori_li_nms) if ri not in list(zip(*row_tgt))[0]] return cls(ori_sys, analytic_factory, linear_invariants=new_lin_invar, linear_invariant_names=new_lin_i_nms, **kwargs)
[ " Reformulates the ODE system in fewer variables.\n\n Given linear invariant equations one can always reduce the number\n of dependent variables in the system by the rank of the matrix describing\n this linear system.\n\n Parameters\n ----------\n ori_sys : :class:`SymbolicSys` instance\n preferred : iterable of preferred dependent variables\n Due to numerical rounding it is preferable to choose the variables\n which are expected to be of the largest magnitude during integration.\n \\*\\*kwargs :\n Keyword arguments passed on to constructor.\n " ]
Please provide a description of the function:def integrate_auto_switch(odes, kw, x, y0, params=(), **kwargs): x_arr = np.asarray(x) if x_arr.shape[-1] > 2: raise NotImplementedError("Only adaptive support return_on_error for now") multimode = False if x_arr.ndim < 2 else x_arr.shape[0] nfo_keys = ('nfev', 'njev', 'time_cpu', 'time_wall') next_autonomous = getattr(odes[0], 'autonomous_interface', False) == True # noqa (np.True_) if multimode: tot_x = [np.array([0] if next_autonomous else [x[_][0]]) for _ in range(multimode)] tot_y = [np.asarray([y0[_]]) for _ in range(multimode)] tot_nfo = [defaultdict(int) for _ in range(multimode)] glob_x = [_[0] for _ in x] if next_autonomous else [0.0]*multimode else: tot_x, tot_y, tot_nfo = np.array([0 if next_autonomous else x[0]]), np.asarray([y0]), defaultdict(int) glob_x = x[0] if next_autonomous else 0.0 for oi in range(len(odes)): if oi < len(odes) - 1: next_autonomous = getattr(odes[oi+1], 'autonomous_interface', False) == True # noqa (np.True_) _int_kw = kwargs.copy() for k, v in kw.items(): _int_kw[k] = v[oi] res = odes[oi].integrate(x, y0, params, **_int_kw) if multimode: for idx in range(multimode): tot_x[idx] = np.concatenate((tot_x[idx], res[idx].xout[1:] + glob_x[idx])) tot_y[idx] = np.concatenate((tot_y[idx], res[idx].yout[1:, :])) for k in nfo_keys: if k in res[idx].info: tot_nfo[idx][k] += res[idx].info[k] tot_nfo[idx]['success'] = res[idx].info['success'] else: tot_x = np.concatenate((tot_x, res.xout[1:] + glob_x)) tot_y = np.concatenate((tot_y, res.yout[1:, :])) for k in nfo_keys: if k in res.info: tot_nfo[k] += res.info[k] tot_nfo['success'] = res.info['success'] if multimode: if all([r.info['success'] for r in res]): break else: if res.info['success']: break if oi < len(odes) - 1: if multimode: _x, y0 = [], [] for idx in range(multimode): _x.append(_new_x(res[idx].xout, x[idx], next_autonomous)) y0.append(res[idx].yout[-1, :]) if next_autonomous: glob_x[idx] += res[idx].xout[-1] x = _x else: x = _new_x(res.xout, x, next_autonomous) y0 = res.yout[-1, :] if next_autonomous: glob_x += res.xout[-1] if multimode: # don't return defaultdict tot_nfo = [dict(nsys=oi+1, **_nfo) for _nfo in tot_nfo] return [Result(tot_x[idx], tot_y[idx], res[idx].params, tot_nfo[idx], odes[0]) for idx in range(len(res))] else: tot_nfo = dict(nsys=oi+1, **tot_nfo) return Result(tot_x, tot_y, res.params, tot_nfo, odes[0])
[ " Auto-switching between formulations of ODE system.\n\n In case one has a formulation of a system of ODEs which is preferential in\n the beginning of the integration, this function allows the user to run the\n integration with this system where it takes a user-specified maximum number\n of steps before switching to another formulation (unless final value of the\n independent variables has been reached). Number of systems used i returned\n as ``nsys`` in info dict.\n\n Parameters\n ----------\n odes : iterable of :class:`OdeSy` instances\n kw : dict mapping kwarg to iterables of same legnth as ``odes``\n x : array_like\n y0 : array_like\n params : array_like\n \\*\\*kwargs:\n See :meth:`ODESys.integrate`\n\n Notes\n -----\n Plays particularly well with :class:`symbolic.TransformedSys`.\n\n " ]
Please provide a description of the function:def chained_parameter_variation(subject, durations, y0, varied_params, default_params=None, integrate_kwargs=None, x0=None, npoints=1, numpy=None): assert len(durations) > 0, 'need at least 1 duration (preferably many)' assert npoints > 0, 'need at least 1 point per duration' for k, v in varied_params.items(): if len(v) != len(durations): raise ValueError("Mismathced lengths of durations and varied_params") if isinstance(subject, ODESys): integrate = subject.integrate numpy = numpy or subject.numpy else: integrate = subject numpy = numpy or np default_params = default_params or {} integrate_kwargs = integrate_kwargs or {} def _get_idx(cont, idx): if isinstance(cont, dict): return {k: (v[idx] if hasattr(v, '__len__') and getattr(v, 'ndim', 1) > 0 else v) for k, v in cont.items()} else: return cont[idx] durations = numpy.cumsum(durations) for idx_dur in range(len(durations)): params = copy.copy(default_params) for k, v in varied_params.items(): params[k] = v[idx_dur] if idx_dur == 0: if x0 is None: x0 = durations[0]*0 out = integrate(numpy.linspace(x0, durations[0], npoints + 1), y0, params, **integrate_kwargs) else: if isinstance(out, Result): out.extend_by_integration(durations[idx_dur], params, npoints=npoints, **integrate_kwargs) else: for idx_res, r in enumerate(out): r.extend_by_integration(durations[idx_dur], _get_idx(params, idx_res), npoints=npoints, **integrate_kwargs) return out
[ " Integrate an ODE-system for a serie of durations with some parameters changed in-between\n\n Parameters\n ----------\n subject : function or ODESys instance\n If a function: should have the signature of :meth:`pyodesys.ODESys.integrate`\n (and resturn a :class:`pyodesys.results.Result` object).\n If a ODESys instance: the ``integrate`` method will be used.\n durations : iterable of floats\n Spans of the independent variable.\n y0 : dict or array_like\n varied_params : dict mapping parameter name (or index) to array_like\n Each array_like need to be of same length as durations.\n default_params : dict or array_like\n Default values for the parameters of the ODE system.\n integrate_kwargs : dict\n Keyword arguments passed on to ``integrate``.\n x0 : float-like\n First value of independent variable. default: 0.\n npoints : int\n Number of points per sub-interval.\n\n Examples\n --------\n >>> odesys = ODESys(lambda t, y, p: [-p[0]*y[0]])\n >>> int_kw = dict(integrator='cvode', method='adams', atol=1e-12, rtol=1e-12)\n >>> kwargs = dict(default_params=[0], integrate_kwargs=int_kw)\n >>> res = chained_parameter_variation(odesys, [2, 3], [42], {0: [.7, .1]}, **kwargs)\n >>> mask1 = res.xout <= 2\n >>> import numpy as np\n >>> np.allclose(res.yout[mask1, 0], 42*np.exp(-.7*res.xout[mask1]))\n True\n >>> mask2 = 2 <= res.xout\n >>> np.allclose(res.yout[mask2, 0], res.yout[mask2, 0][0]*np.exp(-.1*(res.xout[mask2] - res.xout[mask2][0])))\n True\n\n " ]
Please provide a description of the function:def pre_process(self, xout, y0, params=()): for pre_processor in self.pre_processors: xout, y0, params = pre_processor(xout, y0, params) return [self.numpy.atleast_1d(arr) for arr in (xout, y0, params)]
[ " Transforms input to internal values, used internally. " ]
Please provide a description of the function:def post_process(self, xout, yout, params): for post_processor in self.post_processors: xout, yout, params = post_processor(xout, yout, params) return xout, yout, params
[ " Transforms internal values to output, used internally. " ]
Please provide a description of the function:def adaptive(self, y0, x0, xend, params=(), **kwargs): return self.integrate((x0, xend), y0, params=params, **kwargs)
[ " Integrate with integrator chosen output.\n\n Parameters\n ----------\n integrator : str\n See :meth:`integrate`.\n y0 : array_like\n See :meth:`integrate`.\n x0 : float\n Initial value of the independent variable.\n xend : float\n Final value of the independent variable.\n params : array_like\n See :meth:`integrate`.\n \\*\\*kwargs :\n See :meth:`integrate`.\n\n Returns\n -------\n Same as :meth:`integrate`\n " ]
Please provide a description of the function:def predefined(self, y0, xout, params=(), **kwargs): xout, yout, info = self.integrate(xout, y0, params=params, force_predefined=True, **kwargs) return yout, info
[ " Integrate with user chosen output.\n\n Parameters\n ----------\n integrator : str\n See :meth:`integrate`.\n y0 : array_like\n See :meth:`integrate`.\n xout : array_like\n params : array_like\n See :meth:`integrate`.\n \\*\\*kwargs:\n See :meth:`integrate`\n\n Returns\n -------\n Length 2 tuple : (yout, info)\n See :meth:`integrate`.\n " ]
Please provide a description of the function:def integrate(self, x, y0, params=(), atol=1e-8, rtol=1e-8, **kwargs): arrs = self.to_arrays(x, y0, params) _x, _y, _p = _arrs = self.pre_process(*arrs) ndims = [a.ndim for a in _arrs] if ndims == [1, 1, 1]: twodim = False elif ndims == [2, 2, 2]: twodim = True else: raise ValueError("Pre-processor made ndims inconsistent?") if self.append_iv: _p = self.numpy.concatenate((_p, _y), axis=-1) if hasattr(self, 'ny'): if _y.shape[-1] != self.ny: raise ValueError("Incorrect shape of intern_y0") if isinstance(atol, dict): kwargs['atol'] = [atol[k] for k in self.names] else: kwargs['atol'] = atol kwargs['rtol'] = rtol integrator = kwargs.pop('integrator', None) if integrator is None: integrator = os.environ.get('PYODESYS_INTEGRATOR', 'scipy') args = tuple(map(self.numpy.atleast_2d, (_x, _y, _p))) self._current_integration_kwargs = kwargs if isinstance(integrator, str): nfo = getattr(self, '_integrate_' + integrator)(*args, **kwargs) else: kwargs['with_jacobian'] = getattr(integrator, 'with_jacobian', None) nfo = self._integrate(integrator.integrate_adaptive, integrator.integrate_predefined, *args, **kwargs) if twodim: _xout = [d['internal_xout'] for d in nfo] _yout = [d['internal_yout'] for d in nfo] _params = [d['internal_params'] for d in nfo] res = [Result(*(self.post_process(_xout[i], _yout[i], _params[i]) + (nfo[i], self))) for i in range(len(nfo))] else: _xout = nfo[0]['internal_xout'] _yout = nfo[0]['internal_yout'] self._internal = _xout.copy(), _yout.copy(), _p.copy() nfo = nfo[0] res = Result(*(self.post_process(_xout, _yout, _p) + (nfo, self))) return res
[ " Integrate the system of ordinary differential equations.\n\n Solves the initial value problem (IVP).\n\n Parameters\n ----------\n x : array_like or pair (start and final time) or float\n if float:\n make it a pair: (0, x)\n if pair or length-2 array:\n initial and final value of the independent variable\n if array_like:\n values of independent variable report at\n y0 : array_like\n Initial values at x[0] for the dependent variables.\n params : array_like (default: tuple())\n Value of parameters passed to user-supplied callbacks.\n integrator : str or None\n Name of integrator, one of:\n - 'scipy': :meth:`_integrate_scipy`\n - 'gsl': :meth:`_integrate_gsl`\n - 'odeint': :meth:`_integrate_odeint`\n - 'cvode': :meth:`_integrate_cvode`\n\n See respective method for more information.\n If ``None``: ``os.environ.get('PYODESYS_INTEGRATOR', 'scipy')``\n atol : float\n Absolute tolerance\n rtol : float\n Relative tolerance\n with_jacobian : bool or None (default)\n Whether to use the jacobian. When ``None`` the choice is\n done automatically (only used when required). This matters\n when jacobian is derived at runtime (high computational cost).\n with_jtimes : bool (default: False)\n Whether to use the jacobian-vector product. This is only supported\n by ``cvode`` and only when ``linear_solver`` is one of: gmres',\n 'gmres_classic', 'bicgstab', 'tfqmr'. See the documentation\n for ``pycvodes`` for more information.\n force_predefined : bool (default: False)\n override behaviour of ``len(x) == 2`` => :meth:`adaptive`\n \\\\*\\\\*kwargs :\n Additional keyword arguments for ``_integrate_$(integrator)``.\n\n Returns\n -------\n Length 3 tuple: (x, yout, info)\n x : array of values of the independent variable\n yout : array of the dependent variable(s) for the different\n values of x.\n info : dict ('nfev' is guaranteed to be a key)\n " ]
Please provide a description of the function:def _integrate_scipy(self, intern_xout, intern_y0, intern_p, atol=1e-8, rtol=1e-8, first_step=None, with_jacobian=None, force_predefined=False, name=None, **kwargs): from scipy.integrate import ode ny = intern_y0.shape[-1] nx = intern_xout.shape[-1] results = [] for _xout, _y0, _p in zip(intern_xout, intern_y0, intern_p): if name is None: if self.j_cb is None: name = 'dopri5' else: name = 'lsoda' if with_jacobian is None: if name == 'lsoda': # lsoda might call jacobian with_jacobian = True elif name in ('dop853', 'dopri5'): with_jacobian = False # explicit steppers elif name == 'vode': with_jacobian = kwargs.get('method', 'adams') == 'bdf' def rhs(t, y, p=()): rhs.ncall += 1 return self.f_cb(t, y, p) rhs.ncall = 0 if self.j_cb is not None: def jac(t, y, p=()): jac.ncall += 1 return self.j_cb(t, y, p) jac.ncall = 0 r = ode(rhs, jac=jac if with_jacobian else None) if 'lband' in kwargs or 'uband' in kwargs or 'band' in kwargs: raise ValueError("lband and uband set locally (set `band` at initialization instead)") if self.band is not None: kwargs['lband'], kwargs['uband'] = self.band r.set_integrator(name, atol=atol, rtol=rtol, **kwargs) if len(_p) > 0: r.set_f_params(_p) r.set_jac_params(_p) r.set_initial_value(_y0, _xout[0]) if nx == 2 and not force_predefined: mode = 'adaptive' if name in ('vode', 'lsoda'): warnings.warn("'adaptive' mode with SciPy's integrator (vode/lsoda) may overshoot (itask=2)") warnings.warn("'adaptive' mode with SciPy's integrator is unreliable, consider using e.g. cvode") # vode itask 2 (may overshoot) ysteps = [_y0] xsteps = [_xout[0]] while r.t < _xout[1]: r.integrate(_xout[1], step=True) if not r.successful(): raise RuntimeError("failed") xsteps.append(r.t) ysteps.append(r.y) else: xsteps, ysteps = [], [] def solout(x, y): xsteps.append(x) ysteps.append(y) r.set_solout(solout) r.integrate(_xout[1]) if not r.successful(): raise RuntimeError("failed") _yout = np.array(ysteps) _xout = np.array(xsteps) else: # predefined mode = 'predefined' _yout = np.empty((nx, ny)) _yout[0, :] = _y0 for idx in range(1, nx): r.integrate(_xout[idx]) if not r.successful(): raise RuntimeError("failed") _yout[idx, :] = r.y info = { 'internal_xout': _xout, 'internal_yout': _yout, 'internal_params': _p, 'success': r.successful(), 'nfev': rhs.ncall, 'n_steps': -1, # don't know how to obtain this number 'name': name, 'mode': mode, 'atol': atol, 'rtol': rtol } if self.j_cb is not None: info['njev'] = jac.ncall results.append(info) return results
[ " Do not use directly (use ``integrate('scipy', ...)``).\n\n Uses `scipy.integrate.ode <http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html>`_\n\n Parameters\n ----------\n \\*args :\n See :meth:`integrate`.\n name : str (default: 'lsoda'/'dopri5' when jacobian is available/not)\n What integrator wrapped in scipy.integrate.ode to use.\n \\*\\*kwargs :\n Keyword arguments passed onto `set_integrator(...) <\n http://docs.scipy.org/doc/scipy/reference/generated/\n scipy.integrate.ode.set_integrator.html#scipy.integrate.ode.set_integrator>`_\n\n Returns\n -------\n See :meth:`integrate`.\n " ]
Please provide a description of the function:def _integrate_gsl(self, *args, **kwargs): import pygslodeiv2 # Python interface GSL's "odeiv2" integrators kwargs['with_jacobian'] = kwargs.get( 'method', 'bsimp') in pygslodeiv2.requires_jac return self._integrate(pygslodeiv2.integrate_adaptive, pygslodeiv2.integrate_predefined, *args, **kwargs)
[ " Do not use directly (use ``integrate(..., integrator='gsl')``).\n\n Uses `GNU Scientific Library <http://www.gnu.org/software/gsl/>`_\n (via `pygslodeiv2 <https://pypi.python.org/pypi/pygslodeiv2>`_)\n to integrate the ODE system.\n\n Parameters\n ----------\n \\*args :\n see :meth:`integrate`\n method : str (default: 'bsimp')\n what stepper to use, see :py:attr:`gslodeiv2.steppers`\n \\*\\*kwargs :\n keyword arguments passed onto\n :py:func:`gslodeiv2.integrate_adaptive`/:py:func:`gslodeiv2.integrate_predefined`\n\n Returns\n -------\n See :meth:`integrate`\n " ]
Please provide a description of the function:def _integrate_odeint(self, *args, **kwargs): import pyodeint # Python interface to boost's odeint integrators kwargs['with_jacobian'] = kwargs.get( 'method', 'rosenbrock4') in pyodeint.requires_jac return self._integrate(pyodeint.integrate_adaptive, pyodeint.integrate_predefined, *args, **kwargs)
[ " Do not use directly (use ``integrate(..., integrator='odeint')``).\n\n Uses `Boost.Numeric.Odeint <http://www.odeint.com>`_\n (via `pyodeint <https://pypi.python.org/pypi/pyodeint>`_) to integrate\n the ODE system.\n " ]
Please provide a description of the function:def _integrate_cvode(self, *args, **kwargs): import pycvodes # Python interface to SUNDIALS's cvodes integrators kwargs['with_jacobian'] = kwargs.get('method', 'bdf') in pycvodes.requires_jac if 'lband' in kwargs or 'uband' in kwargs or 'band' in kwargs: raise ValueError("lband and uband set locally (set at" " initialization instead)") if self.band is not None: kwargs['lband'], kwargs['uband'] = self.band kwargs['autonomous_exprs'] = self.autonomous_exprs return self._integrate(pycvodes.integrate_adaptive, pycvodes.integrate_predefined, *args, **kwargs)
[ " Do not use directly (use ``integrate(..., integrator='cvode')``).\n\n Uses CVode from CVodes in\n `SUNDIALS <https://computation.llnl.gov/casc/sundials/>`_\n (via `pycvodes <https://pypi.python.org/pypi/pycvodes>`_)\n to integrate the ODE system. " ]
Please provide a description of the function:def plot_phase_plane(self, indices=None, **kwargs): return self._plot(plot_phase_plane, indices=indices, **kwargs)
[ " Plots a phase portrait from last integration.\n\n This method will be deprecated. Please use :meth:`Result.plot_phase_plane`.\n See :func:`pyodesys.plotting.plot_phase_plane`\n " ]
Please provide a description of the function:def stiffness(self, xyp=None, eigenvals_cb=None): if eigenvals_cb is None: if self.band is not None: raise NotImplementedError eigenvals_cb = self._jac_eigenvals_svd if xyp is None: x, y, intern_p = self._internal else: x, y, intern_p = self.pre_process(*xyp) singular_values = [] for xval, yvals in zip(x, y): singular_values.append(eigenvals_cb(xval, yvals, intern_p)) return (np.abs(singular_values).max(axis=-1) / np.abs(singular_values).min(axis=-1))
[ " [DEPRECATED] Use :meth:`Result.stiffness`, stiffness ration\n\n Running stiffness ratio from last integration.\n Calculate sittness ratio, i.e. the ratio between the largest and\n smallest absolute eigenvalue of the jacobian matrix. The user may\n supply their own routine for calculating the eigenvalues, or they\n will be calculated from the SVD (singular value decomposition).\n Note that calculating the SVD for any but the smallest Jacobians may\n prove to be prohibitively expensive.\n\n Parameters\n ----------\n xyp : length 3 tuple (default: None)\n internal_xout, internal_yout, internal_params, taken\n from last integration if not specified.\n eigenvals_cb : callback (optional)\n Signature (x, y, p) (internal variables), when not provided an\n internal routine will use ``self.j_cb`` and ``scipy.linalg.svd``.\n\n " ]
Please provide a description of the function:def build_dummy_request(newsitem): url = newsitem.full_url if url: url_info = urlparse(url) hostname = url_info.hostname path = url_info.path port = url_info.port or 80 else: # Cannot determine a URL to this page - cobble one together based on # whatever we find in ALLOWED_HOSTS try: hostname = settings.ALLOWED_HOSTS[0] except IndexError: hostname = 'localhost' path = '/' port = 80 request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'PATH_INFO': path, 'SERVER_NAME': hostname, 'SERVER_PORT': port, 'HTTP_HOST': hostname, 'wsgi.input': StringIO(), }) # Apply middleware to the request - see http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/ handler = BaseHandler() handler.load_middleware() # call each middleware in turn and throw away any responses that they might return if hasattr(handler, '_request_middleware'): for middleware_method in handler._request_middleware: middleware_method(request) else: handler.get_response(request) return request
[ "\n Construct a HttpRequest object that is, as far as possible,\n representative of ones that would receive this page as a response. Used\n for previewing / moderation and any other place where we want to\n display a view of this page in the admin interface without going\n through the regular page routing logic.\n " ]
Please provide a description of the function:def user_can_edit_news(user): newsitem_models = [model.get_newsitem_model() for model in NEWSINDEX_MODEL_CLASSES] if user.is_active and user.is_superuser: # admin can edit news iff any news types exist return bool(newsitem_models) for NewsItem in newsitem_models: for perm in format_perms(NewsItem, ['add', 'change', 'delete']): if user.has_perm(perm): return True return False
[ "\n Check if the user has permission to edit any of the registered NewsItem\n types.\n " ]
Please provide a description of the function:def user_can_edit_newsitem(user, NewsItem): for perm in format_perms(NewsItem, ['add', 'change', 'delete']): if user.has_perm(perm): return True return False
[ "\n Check if the user has permission to edit a particular NewsItem type.\n " ]
Please provide a description of the function:def get_date_or_404(year, month, day): try: return datetime.date(int(year), int(month), int(day)) except ValueError: raise Http404
[ "Try to make a date from the given inputs, raising Http404 on error" ]
Please provide a description of the function:def respond(self, request, view, newsitems, extra_context={}): context = self.get_context(request, view=view) context.update(self.paginate_newsitems(request, newsitems)) context.update(extra_context) template = self.get_template(request, view=view) return TemplateResponse(request, template, context)
[ "A helper that takes some news items and returns an HttpResponse" ]
Please provide a description of the function:def from_latitude_longitude(cls, latitude=0.0, longitude=0.0): assert -180.0 <= longitude <= 180.0, 'Longitude needs to be a value between -180.0 and 180.0.' assert -90.0 <= latitude <= 90.0, 'Latitude needs to be a value between -90.0 and 90.0.' return cls(latitude=latitude, longitude=longitude)
[ "Creates a point from lat/lon in WGS84" ]
Please provide a description of the function:def from_pixel(cls, pixel_x=0, pixel_y=0, zoom=None): max_pixel = (2 ** zoom) * TILE_SIZE assert 0 <= pixel_x <= max_pixel, 'Point X needs to be a value between 0 and (2^zoom) * 256.' assert 0 <= pixel_y <= max_pixel, 'Point Y needs to be a value between 0 and (2^zoom) * 256.' meter_x = pixel_x * resolution(zoom) - ORIGIN_SHIFT meter_y = pixel_y * resolution(zoom) - ORIGIN_SHIFT meter_x, meter_y = cls._sign_meters(meters=(meter_x, meter_y), pixels=(pixel_x, pixel_y), zoom=zoom) return cls.from_meters(meter_x=meter_x, meter_y=meter_y)
[ "Creates a point from pixels X Y Z (zoom) in pyramid" ]
Please provide a description of the function:def from_meters(cls, meter_x=0.0, meter_y=0.0): assert -ORIGIN_SHIFT <= meter_x <= ORIGIN_SHIFT, \ 'Meter X needs to be a value between -{0} and {0}.'.format(ORIGIN_SHIFT) assert -ORIGIN_SHIFT <= meter_y <= ORIGIN_SHIFT, \ 'Meter Y needs to be a value between -{0} and {0}.'.format(ORIGIN_SHIFT) longitude = (meter_x / ORIGIN_SHIFT) * 180.0 latitude = (meter_y / ORIGIN_SHIFT) * 180.0 latitude = 180.0 / math.pi * (2 * math.atan(math.exp(latitude * math.pi / 180.0)) - math.pi / 2.0) return cls(latitude=latitude, longitude=longitude)
[ "Creates a point from X Y Z (zoom) meters in Spherical Mercator EPSG:900913" ]
Please provide a description of the function:def pixels(self, zoom=None): meter_x, meter_y = self.meters pixel_x = (meter_x + ORIGIN_SHIFT) / resolution(zoom=zoom) pixel_y = (meter_y - ORIGIN_SHIFT) / resolution(zoom=zoom) return abs(round(pixel_x)), abs(round(pixel_y))
[ "Gets pixels of the EPSG:4326 pyramid by a specific zoom, converted from lat/lon in WGS84" ]
Please provide a description of the function:def meters(self): latitude, longitude = self.latitude_longitude meter_x = longitude * ORIGIN_SHIFT / 180.0 meter_y = math.log(math.tan((90.0 + latitude) * math.pi / 360.0)) / (math.pi / 180.0) meter_y = meter_y * ORIGIN_SHIFT / 180.0 return meter_x, meter_y
[ "Gets the XY meters in Spherical Mercator EPSG:900913, converted from lat/lon in WGS84" ]
Please provide a description of the function:def from_quad_tree(cls, quad_tree): assert bool(re.match('^[0-3]*$', quad_tree)), 'QuadTree value can only consists of the digits 0, 1, 2 and 3.' zoom = len(str(quad_tree)) offset = int(math.pow(2, zoom)) - 1 google_x, google_y = [reduce(lambda result, bit: (result << 1) | bit, bits, 0) for bits in zip(*(reversed(divmod(digit, 2)) for digit in (int(c) for c in str(quad_tree))))] return cls(tms_x=google_x, tms_y=(offset - google_y), zoom=zoom)
[ "Creates a tile from a Microsoft QuadTree" ]
Please provide a description of the function:def from_tms(cls, tms_x, tms_y, zoom): max_tile = (2 ** zoom) - 1 assert 0 <= tms_x <= max_tile, 'TMS X needs to be a value between 0 and (2^zoom) -1.' assert 0 <= tms_y <= max_tile, 'TMS Y needs to be a value between 0 and (2^zoom) -1.' return cls(tms_x=tms_x, tms_y=tms_y, zoom=zoom)
[ "Creates a tile from Tile Map Service (TMS) X Y and zoom" ]
Please provide a description of the function:def from_google(cls, google_x, google_y, zoom): max_tile = (2 ** zoom) - 1 assert 0 <= google_x <= max_tile, 'Google X needs to be a value between 0 and (2^zoom) -1.' assert 0 <= google_y <= max_tile, 'Google Y needs to be a value between 0 and (2^zoom) -1.' return cls(tms_x=google_x, tms_y=(2 ** zoom - 1) - google_y, zoom=zoom)
[ "Creates a tile from Google format X Y and zoom" ]
Please provide a description of the function:def for_point(cls, point, zoom): latitude, longitude = point.latitude_longitude return cls.for_latitude_longitude(latitude=latitude, longitude=longitude, zoom=zoom)
[ "Creates a tile for given point" ]
Please provide a description of the function:def for_pixels(cls, pixel_x, pixel_y, zoom): tms_x = int(math.ceil(pixel_x / float(TILE_SIZE)) - 1) tms_y = int(math.ceil(pixel_y / float(TILE_SIZE)) - 1) return cls(tms_x=tms_x, tms_y=(2 ** zoom - 1) - tms_y, zoom=zoom)
[ "Creates a tile from pixels X Y Z (zoom) in pyramid" ]
Please provide a description of the function:def for_meters(cls, meter_x, meter_y, zoom): point = Point.from_meters(meter_x=meter_x, meter_y=meter_y) pixel_x, pixel_y = point.pixels(zoom=zoom) return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
[ "Creates a tile from X Y meters in Spherical Mercator EPSG:900913" ]
Please provide a description of the function:def for_latitude_longitude(cls, latitude, longitude, zoom): point = Point.from_latitude_longitude(latitude=latitude, longitude=longitude) pixel_x, pixel_y = point.pixels(zoom=zoom) return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
[ "Creates a tile from lat/lon in WGS84" ]
Please provide a description of the function:def quad_tree(self): value = '' tms_x, tms_y = self.tms tms_y = (2 ** self.zoom - 1) - tms_y for i in range(self.zoom, 0, -1): digit = 0 mask = 1 << (i - 1) if (tms_x & mask) != 0: digit += 1 if (tms_y & mask) != 0: digit += 2 value += str(digit) return value
[ "Gets the tile in the Microsoft QuadTree format, converted from TMS" ]
Please provide a description of the function:def google(self): tms_x, tms_y = self.tms return tms_x, (2 ** self.zoom - 1) - tms_y
[ "Gets the tile in the Google format, converted from TMS" ]
Please provide a description of the function:def bounds(self): google_x, google_y = self.google pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE pixel_x_east, pixel_y_south = (google_x + 1) * TILE_SIZE, (google_y + 1) * TILE_SIZE point_min = Point.from_pixel(pixel_x=pixel_x_west, pixel_y=pixel_y_south, zoom=self.zoom) point_max = Point.from_pixel(pixel_x=pixel_x_east, pixel_y=pixel_y_north, zoom=self.zoom) return point_min, point_max
[ "Gets the bounds of a tile represented as the most west and south point and the most east and north point" ]
Please provide a description of the function:def fit(self, X, C): X, C = _check_fit_input(X, C) self.nclasses = C.shape[1] ncombs = int( self.nclasses * (self.nclasses - 1) / 2 ) self.classifiers = [ deepcopy(self.base_classifier) for c in range(ncombs) ] self.classes_compared = [None for i in range(ncombs)] if self.weigh_by_cost_diff: V = C else: V = self._calculate_v(C) V = np.asfortranarray(V) Parallel(n_jobs=self.njobs, verbose=0, require="sharedmem")\ ( delayed(self._fit)(i, j, V, X) for i in range(self.nclasses - 1) for j in range(i + 1, self.nclasses) ) self.classes_compared = np.array(self.classes_compared) return self
[ "\n Fit one classifier comparing each pair of classes\n \n Parameters\n ----------\n X : array (n_samples, n_features)\n The data on which to fit a cost-sensitive classifier.\n C : array (n_samples, n_classes)\n The cost of predicting each label for each observation (more means worse).\n " ]