id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
19,600
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.load
def load(self, target_type, target_id, target_parent_id=None): """ Constructs and immediately loads the object, circumventing the lazy-loading scheme by immediately making an API request. Does not load related objects. For example, if you wanted to load an :any:`Instance` object with ID 123, you could do this:: loaded_linode = client.load(Instance, 123) Similarly, if you instead wanted to load a :any:`NodeBalancerConfig`, you could do so like this:: loaded_nodebalancer_config = client.load(NodeBalancerConfig, 456, 432) :param target_type: The type of object to create. :type target_type: type :param target_id: The ID of the object to create. :type target_id: int or str :param target_parent_id: The parent ID of the object to create, if applicable. :type target_parent_id: int, str, or None :returns: The resulting object, fully loaded. :rtype: target_type :raise ApiError: if the requested object could not be loaded. """ result = target_type.make_instance(target_id, self, parent_id=target_parent_id) result._api_get() return result
python
def load(self, target_type, target_id, target_parent_id=None): result = target_type.make_instance(target_id, self, parent_id=target_parent_id) result._api_get() return result
[ "def", "load", "(", "self", ",", "target_type", ",", "target_id", ",", "target_parent_id", "=", "None", ")", ":", "result", "=", "target_type", ".", "make_instance", "(", "target_id", ",", "self", ",", "parent_id", "=", "target_parent_id", ")", "result", "."...
Constructs and immediately loads the object, circumventing the lazy-loading scheme by immediately making an API request. Does not load related objects. For example, if you wanted to load an :any:`Instance` object with ID 123, you could do this:: loaded_linode = client.load(Instance, 123) Similarly, if you instead wanted to load a :any:`NodeBalancerConfig`, you could do so like this:: loaded_nodebalancer_config = client.load(NodeBalancerConfig, 456, 432) :param target_type: The type of object to create. :type target_type: type :param target_id: The ID of the object to create. :type target_id: int or str :param target_parent_id: The parent ID of the object to create, if applicable. :type target_parent_id: int, str, or None :returns: The resulting object, fully loaded. :rtype: target_type :raise ApiError: if the requested object could not be loaded.
[ "Constructs", "and", "immediately", "loads", "the", "object", "circumventing", "the", "lazy", "-", "loading", "scheme", "by", "immediately", "making", "an", "API", "request", ".", "Does", "not", "load", "related", "objects", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L808-L839
19,601
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient._api_call
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None): """ Makes a call to the linode api. Data should only be given if the method is POST or PUT, and should be a dictionary """ if not self.token: raise RuntimeError("You do not have an API token!") if not method: raise ValueError("Method is required for API calls!") if model: endpoint = endpoint.format(**vars(model)) url = '{}{}'.format(self.base_url, endpoint) headers = { 'Authorization': "Bearer {}".format(self.token), 'Content-Type': 'application/json', 'User-Agent': self._user_agent, } if filters: headers['X-Filter'] = json.dumps(filters) body = None if data is not None: body = json.dumps(data) response = method(url, headers=headers, data=body) warning = response.headers.get('Warning', None) if warning: logger.warning('Received warning from server: {}'.format(warning)) if 399 < response.status_code < 600: j = None error_msg = '{}: '.format(response.status_code) try: j = response.json() if 'errors' in j.keys(): for e in j['errors']: error_msg += '{}; '.format(e['reason']) \ if 'reason' in e.keys() else '' except: pass raise ApiError(error_msg, status=response.status_code, json=j) if response.status_code != 204: j = response.json() else: j = None # handle no response body return j
python
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None): if not self.token: raise RuntimeError("You do not have an API token!") if not method: raise ValueError("Method is required for API calls!") if model: endpoint = endpoint.format(**vars(model)) url = '{}{}'.format(self.base_url, endpoint) headers = { 'Authorization': "Bearer {}".format(self.token), 'Content-Type': 'application/json', 'User-Agent': self._user_agent, } if filters: headers['X-Filter'] = json.dumps(filters) body = None if data is not None: body = json.dumps(data) response = method(url, headers=headers, data=body) warning = response.headers.get('Warning', None) if warning: logger.warning('Received warning from server: {}'.format(warning)) if 399 < response.status_code < 600: j = None error_msg = '{}: '.format(response.status_code) try: j = response.json() if 'errors' in j.keys(): for e in j['errors']: error_msg += '{}; '.format(e['reason']) \ if 'reason' in e.keys() else '' except: pass raise ApiError(error_msg, status=response.status_code, json=j) if response.status_code != 204: j = response.json() else: j = None # handle no response body return j
[ "def", "_api_call", "(", "self", ",", "endpoint", ",", "model", "=", "None", ",", "method", "=", "None", ",", "data", "=", "None", ",", "filters", "=", "None", ")", ":", "if", "not", "self", ".", "token", ":", "raise", "RuntimeError", "(", "\"You do ...
Makes a call to the linode api. Data should only be given if the method is POST or PUT, and should be a dictionary
[ "Makes", "a", "call", "to", "the", "linode", "api", ".", "Data", "should", "only", "be", "given", "if", "the", "method", "is", "POST", "or", "PUT", "and", "should", "be", "a", "dictionary" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L841-L892
19,602
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.image_create
def image_create(self, disk, label=None, description=None): """ Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type label: str :param description: The description for the new Image. :type description: str :returns: The new Image. :rtype: Image """ params = { "disk_id": disk.id if issubclass(type(disk), Base) else disk, } if label is not None: params["label"] = label if description is not None: params["description"] = description result = self.post('/images', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating an ' 'Image from disk {}'.format(disk)) return Image(self, result['id'], result)
python
def image_create(self, disk, label=None, description=None): params = { "disk_id": disk.id if issubclass(type(disk), Base) else disk, } if label is not None: params["label"] = label if description is not None: params["description"] = description result = self.post('/images', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating an ' 'Image from disk {}'.format(disk)) return Image(self, result['id'], result)
[ "def", "image_create", "(", "self", ",", "disk", ",", "label", "=", "None", ",", "description", "=", "None", ")", ":", "params", "=", "{", "\"disk_id\"", ":", "disk", ".", "id", "if", "issubclass", "(", "type", "(", "disk", ")", ",", "Base", ")", "...
Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type label: str :param description: The description for the new Image. :type description: str :returns: The new Image. :rtype: Image
[ "Creates", "a", "new", "Image", "from", "a", "disk", "you", "own", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L950-L981
19,603
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.nodebalancer_create
def nodebalancer_create(self, region, **kwargs): """ Creates a new NodeBalancer in the given Region. :param region: The Region in which to create the NodeBalancer. :type region: Region or str :returns: The new NodeBalancer :rtype: NodeBalancer """ params = { "region": region.id if isinstance(region, Base) else region, } params.update(kwargs) result = self.post('/nodebalancers', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Nodebalaner!', json=result) n = NodeBalancer(self, result['id'], result) return n
python
def nodebalancer_create(self, region, **kwargs): params = { "region": region.id if isinstance(region, Base) else region, } params.update(kwargs) result = self.post('/nodebalancers', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Nodebalaner!', json=result) n = NodeBalancer(self, result['id'], result) return n
[ "def", "nodebalancer_create", "(", "self", ",", "region", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "\"region\"", ":", "region", ".", "id", "if", "isinstance", "(", "region", ",", "Base", ")", "else", "region", ",", "}", "params", ".", "...
Creates a new NodeBalancer in the given Region. :param region: The Region in which to create the NodeBalancer. :type region: Region or str :returns: The new NodeBalancer :rtype: NodeBalancer
[ "Creates", "a", "new", "NodeBalancer", "in", "the", "given", "Region", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L1005-L1026
19,604
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.domain_create
def domain_create(self, domain, master=True, **kwargs): """ Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Linode's DNS manager. :type domain: str :param master: Whether this is a master (defaults to true) :type master: bool :returns: The new Domain object. :rtype: Domain """ params = { 'domain': domain, 'type': 'master' if master else 'slave', } params.update(kwargs) result = self.post('/domains', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Domain!', json=result) d = Domain(self, result['id'], result) return d
python
def domain_create(self, domain, master=True, **kwargs): params = { 'domain': domain, 'type': 'master' if master else 'slave', } params.update(kwargs) result = self.post('/domains', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Domain!', json=result) d = Domain(self, result['id'], result) return d
[ "def", "domain_create", "(", "self", ",", "domain", ",", "master", "=", "True", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'domain'", ":", "domain", ",", "'type'", ":", "'master'", "if", "master", "else", "'slave'", ",", "}", "params", "...
Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Linode's DNS manager. :type domain: str :param master: Whether this is a master (defaults to true) :type master: bool :returns: The new Domain object. :rtype: Domain
[ "Registers", "a", "new", "Domain", "on", "the", "acting", "user", "s", "account", ".", "Make", "sure", "to", "point", "your", "registrar", "to", "Linode", "s", "nameservers", "so", "that", "Linode", "s", "DNS", "manager", "will", "correctly", "serve", "you...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L1028-L1054
19,605
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.tag_create
def tag_create(self, label, instances=None, domains=None, nodebalancers=None, volumes=None, entities=[]): """ Creates a new Tag and optionally applies it to the given entities. :param label: The label for the new Tag :type label: str :param entities: A list of objects to apply this Tag to upon creation. May only be taggable types (Linode Instances, Domains, NodeBalancers, or Volumes). These are applied *in addition to* any IDs specified with ``instances``, ``domains``, ``nodebalancers``, or ``volumes``, and is a convenience for sending multiple entity types without sorting them yourself. :type entities: list of Instance, Domain, NodeBalancer, and/or Volume :param instances: A list of Linode Instances to apply this Tag to upon creation :type instances: list of Instance or list of int :param domains: A list of Domains to apply this Tag to upon creation :type domains: list of Domain or list of int :param nodebalancers: A list of NodeBalancers to apply this Tag to upon creation :type nodebalancers: list of NodeBalancer or list of int :param volumes: A list of Volumes to apply this Tag to upon creation :type volumes: list of Volumes or list of int :returns: The new Tag :rtype: Tag """ linode_ids, nodebalancer_ids, domain_ids, volume_ids = [], [], [], [] # filter input into lists of ids sorter = zip((linode_ids, nodebalancer_ids, domain_ids, volume_ids), (instances, nodebalancers, domains, volumes)) for id_list, input_list in sorter: # if we got something, we need to find its ID if input_list is not None: for cur in input_list: if isinstance(cur, int): id_list.append(cur) else: id_list.append(cur.id) # filter entities into id lists too type_map = { Instance: linode_ids, NodeBalancer: nodebalancer_ids, Domain: domain_ids, Volume: volume_ids, } for e in entities: if type(e) in type_map: type_map[type(e)].append(e.id) else: raise ValueError('Unsupported entity type {}'.format(type(e))) # finally, omit all id lists that are empty params = { 'label': label, 'linodes': linode_ids or None, 'nodebalancers': nodebalancer_ids or None, 'domains': domain_ids or None, 'volumes': volume_ids or None, } result = self.post('/tags', data=params) if not 'label' in result: raise UnexpectedResponseError('Unexpected response when creating Tag!', json=result) t = Tag(self, result['label'], result) return t
python
def tag_create(self, label, instances=None, domains=None, nodebalancers=None, volumes=None, entities=[]): linode_ids, nodebalancer_ids, domain_ids, volume_ids = [], [], [], [] # filter input into lists of ids sorter = zip((linode_ids, nodebalancer_ids, domain_ids, volume_ids), (instances, nodebalancers, domains, volumes)) for id_list, input_list in sorter: # if we got something, we need to find its ID if input_list is not None: for cur in input_list: if isinstance(cur, int): id_list.append(cur) else: id_list.append(cur.id) # filter entities into id lists too type_map = { Instance: linode_ids, NodeBalancer: nodebalancer_ids, Domain: domain_ids, Volume: volume_ids, } for e in entities: if type(e) in type_map: type_map[type(e)].append(e.id) else: raise ValueError('Unsupported entity type {}'.format(type(e))) # finally, omit all id lists that are empty params = { 'label': label, 'linodes': linode_ids or None, 'nodebalancers': nodebalancer_ids or None, 'domains': domain_ids or None, 'volumes': volume_ids or None, } result = self.post('/tags', data=params) if not 'label' in result: raise UnexpectedResponseError('Unexpected response when creating Tag!', json=result) t = Tag(self, result['label'], result) return t
[ "def", "tag_create", "(", "self", ",", "label", ",", "instances", "=", "None", ",", "domains", "=", "None", ",", "nodebalancers", "=", "None", ",", "volumes", "=", "None", ",", "entities", "=", "[", "]", ")", ":", "linode_ids", ",", "nodebalancer_ids", ...
Creates a new Tag and optionally applies it to the given entities. :param label: The label for the new Tag :type label: str :param entities: A list of objects to apply this Tag to upon creation. May only be taggable types (Linode Instances, Domains, NodeBalancers, or Volumes). These are applied *in addition to* any IDs specified with ``instances``, ``domains``, ``nodebalancers``, or ``volumes``, and is a convenience for sending multiple entity types without sorting them yourself. :type entities: list of Instance, Domain, NodeBalancer, and/or Volume :param instances: A list of Linode Instances to apply this Tag to upon creation :type instances: list of Instance or list of int :param domains: A list of Domains to apply this Tag to upon creation :type domains: list of Domain or list of int :param nodebalancers: A list of NodeBalancers to apply this Tag to upon creation :type nodebalancers: list of NodeBalancer or list of int :param volumes: A list of Volumes to apply this Tag to upon creation :type volumes: list of Volumes or list of int :returns: The new Tag :rtype: Tag
[ "Creates", "a", "new", "Tag", "and", "optionally", "applies", "it", "to", "the", "given", "entities", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L1068-L1143
19,606
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.volume_create
def volume_create(self, label, region=None, linode=None, size=20, **kwargs): """ Creates a new Block Storage Volume, either in the given Region or attached to the given Instance. :param label: The label for the new Volume. :type label: str :param region: The Region to create this Volume in. Not required if `linode` is provided. :type region: Region or str :param linode: The Instance to attach this Volume to. If not given, the new Volume will not be attached to anything. :type linode: Instance or int :param size: The size, in GB, of the new Volume. Defaults to 20. :type size: int :returns: The new Volume. :rtype: Volume """ if not (region or linode): raise ValueError('region or linode required!') params = { "label": label, "size": size, "region": region.id if issubclass(type(region), Base) else region, "linode_id": linode.id if issubclass(type(linode), Base) else linode, } params.update(kwargs) result = self.post('/volumes', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating volume!', json=result) v = Volume(self, result['id'], result) return v
python
def volume_create(self, label, region=None, linode=None, size=20, **kwargs): if not (region or linode): raise ValueError('region or linode required!') params = { "label": label, "size": size, "region": region.id if issubclass(type(region), Base) else region, "linode_id": linode.id if issubclass(type(linode), Base) else linode, } params.update(kwargs) result = self.post('/volumes', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating volume!', json=result) v = Volume(self, result['id'], result) return v
[ "def", "volume_create", "(", "self", ",", "label", ",", "region", "=", "None", ",", "linode", "=", "None", ",", "size", "=", "20", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "region", "or", "linode", ")", ":", "raise", "ValueError", "(", ...
Creates a new Block Storage Volume, either in the given Region or attached to the given Instance. :param label: The label for the new Volume. :type label: str :param region: The Region to create this Volume in. Not required if `linode` is provided. :type region: Region or str :param linode: The Instance to attach this Volume to. If not given, the new Volume will not be attached to anything. :type linode: Instance or int :param size: The size, in GB, of the new Volume. Defaults to 20. :type size: int :returns: The new Volume. :rtype: Volume
[ "Creates", "a", "new", "Block", "Storage", "Volume", "either", "in", "the", "given", "Region", "or", "attached", "to", "the", "given", "Instance", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L1156-L1192
19,607
linode/linode_api4-python
linode_api4/login_client.py
LinodeLoginClient.expire_token
def expire_token(self, token): """ Given a token, makes a request to the authentication server to expire it immediately. This is considered a responsible way to log out a user. If you simply remove the session your application has for the user without expiring their token, the user is not _really_ logged out. :param token: The OAuth token you wish to expire :type token: str :returns: If the expiration attempt succeeded. :rtype: bool :raises ApiError: If the expiration attempt failed. """ r = requests.post(self._login_uri("/oauth/token/expire"), data={ "client_id": self.client_id, "client_secret": self.client_secret, "token": token, }) if r.status_code != 200: raise ApiError("Failed to expire token!", r) return True
python
def expire_token(self, token): r = requests.post(self._login_uri("/oauth/token/expire"), data={ "client_id": self.client_id, "client_secret": self.client_secret, "token": token, }) if r.status_code != 200: raise ApiError("Failed to expire token!", r) return True
[ "def", "expire_token", "(", "self", ",", "token", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "_login_uri", "(", "\"/oauth/token/expire\"", ")", ",", "data", "=", "{", "\"client_id\"", ":", "self", ".", "client_id", ",", "\"client_secret...
Given a token, makes a request to the authentication server to expire it immediately. This is considered a responsible way to log out a user. If you simply remove the session your application has for the user without expiring their token, the user is not _really_ logged out. :param token: The OAuth token you wish to expire :type token: str :returns: If the expiration attempt succeeded. :rtype: bool :raises ApiError: If the expiration attempt failed.
[ "Given", "a", "token", "makes", "a", "request", "to", "the", "authentication", "server", "to", "expire", "it", "immediately", ".", "This", "is", "considered", "a", "responsible", "way", "to", "log", "out", "a", "user", ".", "If", "you", "simply", "remove",...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/login_client.py#L417-L441
19,608
linode/linode_api4-python
linode_api4/objects/profile.py
Profile.grants
def grants(self): """ Returns grants for the current user """ from linode_api4.objects.account import UserGrants resp = self._client.get('/profile/grants') # use special endpoint for restricted users grants = None if resp is not None: # if resp is None, we're unrestricted and do not have grants grants = UserGrants(self._client, self.username, resp) return grants
python
def grants(self): from linode_api4.objects.account import UserGrants resp = self._client.get('/profile/grants') # use special endpoint for restricted users grants = None if resp is not None: # if resp is None, we're unrestricted and do not have grants grants = UserGrants(self._client, self.username, resp) return grants
[ "def", "grants", "(", "self", ")", ":", "from", "linode_api4", ".", "objects", ".", "account", "import", "UserGrants", "resp", "=", "self", ".", "_client", ".", "get", "(", "'/profile/grants'", ")", "# use special endpoint for restricted users", "grants", "=", "...
Returns grants for the current user
[ "Returns", "grants", "for", "the", "current", "user" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/profile.py#L91-L103
19,609
linode/linode_api4-python
linode_api4/objects/profile.py
Profile.add_whitelist_entry
def add_whitelist_entry(self, address, netmask, note=None): """ Adds a new entry to this user's IP whitelist, if enabled """ result = self._client.post("{}/whitelist".format(Profile.api_endpoint), data={ "address": address, "netmask": netmask, "note": note, }) if not 'id' in result: raise UnexpectedResponseError("Unexpected response creating whitelist entry!") return WhitelistEntry(result['id'], self._client, json=result)
python
def add_whitelist_entry(self, address, netmask, note=None): result = self._client.post("{}/whitelist".format(Profile.api_endpoint), data={ "address": address, "netmask": netmask, "note": note, }) if not 'id' in result: raise UnexpectedResponseError("Unexpected response creating whitelist entry!") return WhitelistEntry(result['id'], self._client, json=result)
[ "def", "add_whitelist_entry", "(", "self", ",", "address", ",", "netmask", ",", "note", "=", "None", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "\"{}/whitelist\"", ".", "format", "(", "Profile", ".", "api_endpoint", ")", ",", "dat...
Adds a new entry to this user's IP whitelist, if enabled
[ "Adds", "a", "new", "entry", "to", "this", "user", "s", "IP", "whitelist", "if", "enabled" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/profile.py#L112-L126
19,610
tmm/django-username-email
cuser/forms.py
AuthenticationForm.confirm_login_allowed
def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``forms.ValidationError``. If the given user may log in, this method should return None. """ if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', )
python
def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', )
[ "def", "confirm_login_allowed", "(", "self", ",", "user", ")", ":", "if", "not", "user", ".", "is_active", ":", "raise", "forms", ".", "ValidationError", "(", "self", ".", "error_messages", "[", "'inactive'", "]", ",", "code", "=", "'inactive'", ",", ")" ]
Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``forms.ValidationError``. If the given user may log in, this method should return None.
[ "Controls", "whether", "the", "given", "User", "may", "log", "in", ".", "This", "is", "a", "policy", "setting", "independent", "of", "end", "-", "user", "authentication", ".", "This", "default", "behavior", "is", "to", "allow", "login", "by", "active", "us...
36e56bcbf79d46af101ba4c8f4bd848856306329
https://github.com/tmm/django-username-email/blob/36e56bcbf79d46af101ba4c8f4bd848856306329/cuser/forms.py#L68-L83
19,611
dwavesystems/dwave-system
dwave/embedding/chain_breaks.py
broken_chains
def broken_chains(samples, chains): """Find the broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: :obj:`numpy.ndarray`: A nS x nC boolean array. If i, j is True, then chain j in sample i is broken. Examples: >>> samples = np.array([[-1, +1, -1, +1], [-1, -1, +1, +1]], dtype=np.int8) >>> chains = [[0, 1], [2, 3]] >>> dwave.embedding.broken_chains(samples, chains) array([[True, True], [ False, False]]) >>> samples = np.array([[-1, +1, -1, +1], [-1, -1, +1, +1]], dtype=np.int8) >>> chains = [[0, 2], [1, 3]] >>> dwave.embedding.broken_chains(samples, chains) array([[False, False], [ True, True]]) """ samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") num_samples, num_variables = samples.shape num_chains = len(chains) broken = np.zeros((num_samples, num_chains), dtype=bool, order='F') for cidx, chain in enumerate(chains): if isinstance(chain, set): chain = list(chain) chain = np.asarray(chain) if chain.ndim > 1: raise ValueError("chains should be 1D array_like objects") # chains of length 1, or 0 cannot be broken if len(chain) <= 1: continue all_ = (samples[:, chain] == 1).all(axis=1) any_ = (samples[:, chain] == 1).any(axis=1) broken[:, cidx] = np.bitwise_xor(all_, any_) return broken
python
def broken_chains(samples, chains): samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") num_samples, num_variables = samples.shape num_chains = len(chains) broken = np.zeros((num_samples, num_chains), dtype=bool, order='F') for cidx, chain in enumerate(chains): if isinstance(chain, set): chain = list(chain) chain = np.asarray(chain) if chain.ndim > 1: raise ValueError("chains should be 1D array_like objects") # chains of length 1, or 0 cannot be broken if len(chain) <= 1: continue all_ = (samples[:, chain] == 1).all(axis=1) any_ = (samples[:, chain] == 1).any(axis=1) broken[:, cidx] = np.bitwise_xor(all_, any_) return broken
[ "def", "broken_chains", "(", "samples", ",", "chains", ")", ":", "samples", "=", "np", ".", "asarray", "(", "samples", ")", "if", "samples", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"expected samples to be a numpy 2D array\"", ")", "num_sampl...
Find the broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: :obj:`numpy.ndarray`: A nS x nC boolean array. If i, j is True, then chain j in sample i is broken. Examples: >>> samples = np.array([[-1, +1, -1, +1], [-1, -1, +1, +1]], dtype=np.int8) >>> chains = [[0, 1], [2, 3]] >>> dwave.embedding.broken_chains(samples, chains) array([[True, True], [ False, False]]) >>> samples = np.array([[-1, +1, -1, +1], [-1, -1, +1, +1]], dtype=np.int8) >>> chains = [[0, 2], [1, 3]] >>> dwave.embedding.broken_chains(samples, chains) array([[False, False], [ True, True]])
[ "Find", "the", "broken", "chains", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chain_breaks.py#L33-L88
19,612
dwavesystems/dwave-system
dwave/embedding/chain_breaks.py
discard
def discard(samples, chains): """Discard broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: An array of unembedded samples. Broken chains are discarded. The array has dtype 'int8'. :obj:`numpy.ndarray`: The indicies of the rows with unbroken chains. Examples: This example unembeds two samples that chains nodes 0 and 1 to represent a single source node. The first sample has an unbroken chain, the second a broken chain. >>> import dimod >>> import numpy as np ... >>> chains = [(0, 1), (2,)] >>> samples = np.array([[1, 1, 0], [1, 0, 0]], dtype=np.int8) >>> unembedded, idx = dwave.embedding.discard(samples, chains) >>> unembedded array([[1, 0]], dtype=int8) >>> idx array([0]) """ samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") num_samples, num_variables = samples.shape num_chains = len(chains) broken = broken_chains(samples, chains) unbroken_idxs, = np.where(~broken.any(axis=1)) chain_variables = np.fromiter((np.asarray(tuple(chain))[0] if isinstance(chain, set) else np.asarray(chain)[0] for chain in chains), count=num_chains, dtype=int) return samples[np.ix_(unbroken_idxs, chain_variables)], unbroken_idxs
python
def discard(samples, chains): samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") num_samples, num_variables = samples.shape num_chains = len(chains) broken = broken_chains(samples, chains) unbroken_idxs, = np.where(~broken.any(axis=1)) chain_variables = np.fromiter((np.asarray(tuple(chain))[0] if isinstance(chain, set) else np.asarray(chain)[0] for chain in chains), count=num_chains, dtype=int) return samples[np.ix_(unbroken_idxs, chain_variables)], unbroken_idxs
[ "def", "discard", "(", "samples", ",", "chains", ")", ":", "samples", "=", "np", ".", "asarray", "(", "samples", ")", "if", "samples", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"expected samples to be a numpy 2D array\"", ")", "num_samples", ...
Discard broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: An array of unembedded samples. Broken chains are discarded. The array has dtype 'int8'. :obj:`numpy.ndarray`: The indicies of the rows with unbroken chains. Examples: This example unembeds two samples that chains nodes 0 and 1 to represent a single source node. The first sample has an unbroken chain, the second a broken chain. >>> import dimod >>> import numpy as np ... >>> chains = [(0, 1), (2,)] >>> samples = np.array([[1, 1, 0], [1, 0, 0]], dtype=np.int8) >>> unembedded, idx = dwave.embedding.discard(samples, chains) >>> unembedded array([[1, 0]], dtype=int8) >>> idx array([0])
[ "Discard", "broken", "chains", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chain_breaks.py#L91-L142
19,613
dwavesystems/dwave-system
dwave/embedding/chain_breaks.py
majority_vote
def majority_vote(samples, chains): """Use the most common element in broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: A nS x nC array of unembedded samples. The array has dtype 'int8'. Where there is a chain break, the value is chosen to match the most common value in the chain. For broken chains without a majority, the value is chosen arbitrarily. :obj:`numpy.ndarray`: Equivalent to :code:`np.arange(nS)` because all samples are kept and no samples are added. Examples: This example unembeds samples from a target graph that chains nodes 0 and 1 to represent one source node and nodes 2, 3, and 4 to represent another. Both samples have one broken chain, with different majority values. >>> import dimod >>> import numpy as np ... >>> chains = [(0, 1), (2, 3, 4)] >>> samples = np.array([[1, 1, 0, 0, 1], [1, 1, 1, 0, 1]], dtype=np.int8) >>> unembedded, idx = dwave.embedding.majority_vote(samples, chains) >>> unembedded array([[1, 0], [1, 1]], dtype=int8) >>> idx array([0, 1]) """ samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") num_samples, num_variables = samples.shape num_chains = len(chains) unembedded = np.empty((num_samples, num_chains), dtype='int8', order='F') # determine if spin or binary. If samples are all 1, then either method works, so we use spin # because it is faster if samples.all(): # spin-valued for cidx, chain in enumerate(chains): # we just need the sign for spin. We don't use np.sign because in that can return 0 # and fixing the 0s is slow. unembedded[:, cidx] = 2*(samples[:, chain].sum(axis=1) >= 0) - 1 else: # binary-valued for cidx, chain in enumerate(chains): mid = len(chain) / 2 unembedded[:, cidx] = (samples[:, chain].sum(axis=1) >= mid) return unembedded, np.arange(num_samples)
python
def majority_vote(samples, chains): samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") num_samples, num_variables = samples.shape num_chains = len(chains) unembedded = np.empty((num_samples, num_chains), dtype='int8', order='F') # determine if spin or binary. If samples are all 1, then either method works, so we use spin # because it is faster if samples.all(): # spin-valued for cidx, chain in enumerate(chains): # we just need the sign for spin. We don't use np.sign because in that can return 0 # and fixing the 0s is slow. unembedded[:, cidx] = 2*(samples[:, chain].sum(axis=1) >= 0) - 1 else: # binary-valued for cidx, chain in enumerate(chains): mid = len(chain) / 2 unembedded[:, cidx] = (samples[:, chain].sum(axis=1) >= mid) return unembedded, np.arange(num_samples)
[ "def", "majority_vote", "(", "samples", ",", "chains", ")", ":", "samples", "=", "np", ".", "asarray", "(", "samples", ")", "if", "samples", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"expected samples to be a numpy 2D array\"", ")", "num_sampl...
Use the most common element in broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: A nS x nC array of unembedded samples. The array has dtype 'int8'. Where there is a chain break, the value is chosen to match the most common value in the chain. For broken chains without a majority, the value is chosen arbitrarily. :obj:`numpy.ndarray`: Equivalent to :code:`np.arange(nS)` because all samples are kept and no samples are added. Examples: This example unembeds samples from a target graph that chains nodes 0 and 1 to represent one source node and nodes 2, 3, and 4 to represent another. Both samples have one broken chain, with different majority values. >>> import dimod >>> import numpy as np ... >>> chains = [(0, 1), (2, 3, 4)] >>> samples = np.array([[1, 1, 0, 0, 1], [1, 1, 1, 0, 1]], dtype=np.int8) >>> unembedded, idx = dwave.embedding.majority_vote(samples, chains) >>> unembedded array([[1, 0], [1, 1]], dtype=int8) >>> idx array([0, 1])
[ "Use", "the", "most", "common", "element", "in", "broken", "chains", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chain_breaks.py#L145-L206
19,614
dwavesystems/dwave-system
dwave/embedding/chain_breaks.py
weighted_random
def weighted_random(samples, chains): """Determine the sample values of chains by weighed random choice. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: A nS x nC array of unembedded samples. The array has dtype 'int8'. Where there is a chain break, the value is chosen randomly, weighted by frequency of the chain's value. :obj:`numpy.ndarray`: Equivalent to :code:`np.arange(nS)` because all samples are kept and no samples are added. Examples: This example unembeds samples from a target graph that chains nodes 0 and 1 to represent one source node and nodes 2, 3, and 4 to represent another. The sample has broken chains for both source nodes. >>> import dimod >>> import numpy as np ... >>> chains = [(0, 1), (2, 3, 4)] >>> samples = np.array([[1, 0, 1, 0, 1]], dtype=np.int8) >>> unembedded, idx = dwave.embedding.weighted_random(samples, chains) # doctest: +SKIP >>> unembedded # doctest: +SKIP array([[1, 1]], dtype=int8) >>> idx # doctest: +SKIP array([0, 1]) """ samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") # it sufficies to choose a random index from each chain and use that to construct the matrix idx = [np.random.choice(chain) for chain in chains] num_samples, num_variables = samples.shape return samples[:, idx], np.arange(num_samples)
python
def weighted_random(samples, chains): samples = np.asarray(samples) if samples.ndim != 2: raise ValueError("expected samples to be a numpy 2D array") # it sufficies to choose a random index from each chain and use that to construct the matrix idx = [np.random.choice(chain) for chain in chains] num_samples, num_variables = samples.shape return samples[:, idx], np.arange(num_samples)
[ "def", "weighted_random", "(", "samples", ",", "chains", ")", ":", "samples", "=", "np", ".", "asarray", "(", "samples", ")", "if", "samples", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"expected samples to be a numpy 2D array\"", ")", "# it su...
Determine the sample values of chains by weighed random choice. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): List of chains of length nC where nC is the number of chains. Each chain should be an array_like collection of column indices in samples. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: A nS x nC array of unembedded samples. The array has dtype 'int8'. Where there is a chain break, the value is chosen randomly, weighted by frequency of the chain's value. :obj:`numpy.ndarray`: Equivalent to :code:`np.arange(nS)` because all samples are kept and no samples are added. Examples: This example unembeds samples from a target graph that chains nodes 0 and 1 to represent one source node and nodes 2, 3, and 4 to represent another. The sample has broken chains for both source nodes. >>> import dimod >>> import numpy as np ... >>> chains = [(0, 1), (2, 3, 4)] >>> samples = np.array([[1, 0, 1, 0, 1]], dtype=np.int8) >>> unembedded, idx = dwave.embedding.weighted_random(samples, chains) # doctest: +SKIP >>> unembedded # doctest: +SKIP array([[1, 1]], dtype=int8) >>> idx # doctest: +SKIP array([0, 1])
[ "Determine", "the", "sample", "values", "of", "chains", "by", "weighed", "random", "choice", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chain_breaks.py#L209-L256
19,615
dwavesystems/dwave-system
dwave/system/samplers/dwave_sampler.py
DWaveSampler.validate_anneal_schedule
def validate_anneal_schedule(self, anneal_schedule): """Raise an exception if the specified schedule is invalid for the sampler. Args: anneal_schedule (list): An anneal schedule variation is defined by a series of pairs of floating-point numbers identifying points in the schedule at which to change slope. The first element in the pair is time t in microseconds; the second, normalized persistent current s in the range [0,1]. The resulting schedule is the piecewise-linear curve that connects the provided points. Raises: ValueError: If the schedule violates any of the conditions listed below. RuntimeError: If the sampler does not accept the `anneal_schedule` parameter or if it does not have `annealing_time_range` or `max_anneal_schedule_points` properties. An anneal schedule must satisfy the following conditions: * Time t must increase for all points in the schedule. * For forward annealing, the first point must be (0,0) and the anneal fraction s must increase monotonically. * For reverse annealing, the anneal fraction s must start and end at s=1. * In the final point, anneal fraction s must equal 1 and time t must not exceed the maximum value in the `annealing_time_range` property. * The number of points must be >=2. * The upper bound is system-dependent; check the `max_anneal_schedule_points` property. For reverse annealing, the maximum number of points allowed is one more than the number given by this property. Examples: This example sets a quench schedule on a D-Wave system selected by the user's default :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`. >>> from dwave.system.samplers import DWaveSampler >>> sampler = DWaveSampler() >>> quench_schedule=[[0.0, 0.0], [12.0, 0.6], [12.8, 1.0]] >>> DWaveSampler().validate_anneal_schedule(quench_schedule) # doctest: +SKIP >>> """ if 'anneal_schedule' not in self.parameters: raise RuntimeError("anneal_schedule is not an accepted parameter for this sampler") properties = self.properties try: min_anneal_time, max_anneal_time = properties['annealing_time_range'] max_anneal_schedule_points = properties['max_anneal_schedule_points'] except KeyError: raise RuntimeError("annealing_time_range and max_anneal_schedule_points are not properties of this solver") # The number of points must be >= 2. # The upper bound is system-dependent; check the max_anneal_schedule_points property if not isinstance(anneal_schedule, list): raise TypeError("anneal_schedule should be a list") elif len(anneal_schedule) < 2 or len(anneal_schedule) > max_anneal_schedule_points: msg = ("anneal_schedule must contain between 2 and {} points (contains {})" ).format(max_anneal_schedule_points, len(anneal_schedule)) raise ValueError(msg) try: t_list, s_list = zip(*anneal_schedule) except ValueError: raise ValueError("anneal_schedule should be a list of 2-tuples") # Time t must increase for all points in the schedule. if not all(tail_t < lead_t for tail_t, lead_t in zip(t_list, t_list[1:])): raise ValueError("Time t must increase for all points in the schedule") # max t cannot exceed max_anneal_time if t_list[-1] > max_anneal_time: raise ValueError("schedule cannot be longer than the maximum anneal time of {}".format(max_anneal_time)) start_s, end_s = s_list[0], s_list[-1] if end_s != 1: raise ValueError("In the final point, anneal fraction s must equal 1.") if start_s == 1: # reverse annealing pass elif start_s == 0: # forward annealing, s must monotonically increase. if not all(tail_s <= lead_s for tail_s, lead_s in zip(s_list, s_list[1:])): raise ValueError("For forward anneals, anneal fraction s must monotonically increase") else: msg = ("In the first point, anneal fraction s must equal 0 for forward annealing or " "1 for reverse annealing") raise ValueError(msg) # finally check the slope abs(slope) < 1/min_anneal_time max_slope = 1.0 / min_anneal_time for (t0, s0), (t1, s1) in zip(anneal_schedule, anneal_schedule[1:]): if abs((s0 - s1) / (t0 - t1)) > max_slope: raise ValueError("the maximum slope cannot exceed {}".format(max_slope))
python
def validate_anneal_schedule(self, anneal_schedule): if 'anneal_schedule' not in self.parameters: raise RuntimeError("anneal_schedule is not an accepted parameter for this sampler") properties = self.properties try: min_anneal_time, max_anneal_time = properties['annealing_time_range'] max_anneal_schedule_points = properties['max_anneal_schedule_points'] except KeyError: raise RuntimeError("annealing_time_range and max_anneal_schedule_points are not properties of this solver") # The number of points must be >= 2. # The upper bound is system-dependent; check the max_anneal_schedule_points property if not isinstance(anneal_schedule, list): raise TypeError("anneal_schedule should be a list") elif len(anneal_schedule) < 2 or len(anneal_schedule) > max_anneal_schedule_points: msg = ("anneal_schedule must contain between 2 and {} points (contains {})" ).format(max_anneal_schedule_points, len(anneal_schedule)) raise ValueError(msg) try: t_list, s_list = zip(*anneal_schedule) except ValueError: raise ValueError("anneal_schedule should be a list of 2-tuples") # Time t must increase for all points in the schedule. if not all(tail_t < lead_t for tail_t, lead_t in zip(t_list, t_list[1:])): raise ValueError("Time t must increase for all points in the schedule") # max t cannot exceed max_anneal_time if t_list[-1] > max_anneal_time: raise ValueError("schedule cannot be longer than the maximum anneal time of {}".format(max_anneal_time)) start_s, end_s = s_list[0], s_list[-1] if end_s != 1: raise ValueError("In the final point, anneal fraction s must equal 1.") if start_s == 1: # reverse annealing pass elif start_s == 0: # forward annealing, s must monotonically increase. if not all(tail_s <= lead_s for tail_s, lead_s in zip(s_list, s_list[1:])): raise ValueError("For forward anneals, anneal fraction s must monotonically increase") else: msg = ("In the first point, anneal fraction s must equal 0 for forward annealing or " "1 for reverse annealing") raise ValueError(msg) # finally check the slope abs(slope) < 1/min_anneal_time max_slope = 1.0 / min_anneal_time for (t0, s0), (t1, s1) in zip(anneal_schedule, anneal_schedule[1:]): if abs((s0 - s1) / (t0 - t1)) > max_slope: raise ValueError("the maximum slope cannot exceed {}".format(max_slope))
[ "def", "validate_anneal_schedule", "(", "self", ",", "anneal_schedule", ")", ":", "if", "'anneal_schedule'", "not", "in", "self", ".", "parameters", ":", "raise", "RuntimeError", "(", "\"anneal_schedule is not an accepted parameter for this sampler\"", ")", "properties", ...
Raise an exception if the specified schedule is invalid for the sampler. Args: anneal_schedule (list): An anneal schedule variation is defined by a series of pairs of floating-point numbers identifying points in the schedule at which to change slope. The first element in the pair is time t in microseconds; the second, normalized persistent current s in the range [0,1]. The resulting schedule is the piecewise-linear curve that connects the provided points. Raises: ValueError: If the schedule violates any of the conditions listed below. RuntimeError: If the sampler does not accept the `anneal_schedule` parameter or if it does not have `annealing_time_range` or `max_anneal_schedule_points` properties. An anneal schedule must satisfy the following conditions: * Time t must increase for all points in the schedule. * For forward annealing, the first point must be (0,0) and the anneal fraction s must increase monotonically. * For reverse annealing, the anneal fraction s must start and end at s=1. * In the final point, anneal fraction s must equal 1 and time t must not exceed the maximum value in the `annealing_time_range` property. * The number of points must be >=2. * The upper bound is system-dependent; check the `max_anneal_schedule_points` property. For reverse annealing, the maximum number of points allowed is one more than the number given by this property. Examples: This example sets a quench schedule on a D-Wave system selected by the user's default :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`. >>> from dwave.system.samplers import DWaveSampler >>> sampler = DWaveSampler() >>> quench_schedule=[[0.0, 0.0], [12.0, 0.6], [12.8, 1.0]] >>> DWaveSampler().validate_anneal_schedule(quench_schedule) # doctest: +SKIP >>>
[ "Raise", "an", "exception", "if", "the", "specified", "schedule", "is", "invalid", "for", "the", "sampler", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/samplers/dwave_sampler.py#L318-L412
19,616
dwavesystems/dwave-system
dwave/embedding/utils.py
target_to_source
def target_to_source(target_adjacency, embedding): """Derive the source adjacency from an embedding and target adjacency. Args: target_adjacency (dict/:class:`networkx.Graph`): A dict of the form {v: Nv, ...} where v is a node in the target graph and Nv is the neighbors of v as an iterable. This can also be a networkx graph. embedding (dict): A mapping from a source graph to a target graph. Returns: dict: The adjacency of the source graph. Raises: ValueError: If any node in the target_adjacency is assigned more than one node in the source graph by embedding. Examples: >>> target_adjacency = {0: {1, 3}, 1: {0, 2}, 2: {1, 3}, 3: {0, 2}} # a square graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> source_adjacency = dimod.embedding.target_to_source(target_adjacency, embedding) >>> source_adjacency # triangle {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}} This function also works with networkx graphs. >>> import networkx as nx >>> target_graph = nx.complete_graph(5) >>> embedding = {'a': {0, 1, 2}, 'b': {3, 4}} >>> dimod.embedding.target_to_source(target_graph, embedding) """ # the nodes in the source adjacency are just the keys of the embedding source_adjacency = {v: set() for v in embedding} # we need the mapping from each node in the target to its source node reverse_embedding = {} for v, chain in iteritems(embedding): for u in chain: if u in reverse_embedding: raise ValueError("target node {} assigned to more than one source node".format(u)) reverse_embedding[u] = v # v is node in target, n node in source for v, n in iteritems(reverse_embedding): neighbors = target_adjacency[v] # u is node in target for u in neighbors: # some nodes might not be assigned to chains if u not in reverse_embedding: continue # m is node in source m = reverse_embedding[u] if m == n: continue source_adjacency[n].add(m) source_adjacency[m].add(n) return source_adjacency
python
def target_to_source(target_adjacency, embedding): # the nodes in the source adjacency are just the keys of the embedding source_adjacency = {v: set() for v in embedding} # we need the mapping from each node in the target to its source node reverse_embedding = {} for v, chain in iteritems(embedding): for u in chain: if u in reverse_embedding: raise ValueError("target node {} assigned to more than one source node".format(u)) reverse_embedding[u] = v # v is node in target, n node in source for v, n in iteritems(reverse_embedding): neighbors = target_adjacency[v] # u is node in target for u in neighbors: # some nodes might not be assigned to chains if u not in reverse_embedding: continue # m is node in source m = reverse_embedding[u] if m == n: continue source_adjacency[n].add(m) source_adjacency[m].add(n) return source_adjacency
[ "def", "target_to_source", "(", "target_adjacency", ",", "embedding", ")", ":", "# the nodes in the source adjacency are just the keys of the embedding", "source_adjacency", "=", "{", "v", ":", "set", "(", ")", "for", "v", "in", "embedding", "}", "# we need the mapping fr...
Derive the source adjacency from an embedding and target adjacency. Args: target_adjacency (dict/:class:`networkx.Graph`): A dict of the form {v: Nv, ...} where v is a node in the target graph and Nv is the neighbors of v as an iterable. This can also be a networkx graph. embedding (dict): A mapping from a source graph to a target graph. Returns: dict: The adjacency of the source graph. Raises: ValueError: If any node in the target_adjacency is assigned more than one node in the source graph by embedding. Examples: >>> target_adjacency = {0: {1, 3}, 1: {0, 2}, 2: {1, 3}, 3: {0, 2}} # a square graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> source_adjacency = dimod.embedding.target_to_source(target_adjacency, embedding) >>> source_adjacency # triangle {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}} This function also works with networkx graphs. >>> import networkx as nx >>> target_graph = nx.complete_graph(5) >>> embedding = {'a': {0, 1, 2}, 'b': {3, 4}} >>> dimod.embedding.target_to_source(target_graph, embedding)
[ "Derive", "the", "source", "adjacency", "from", "an", "embedding", "and", "target", "adjacency", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/utils.py#L30-L95
19,617
dwavesystems/dwave-system
dwave/embedding/utils.py
chain_to_quadratic
def chain_to_quadratic(chain, target_adjacency, chain_strength): """Determine the quadratic biases that induce the given chain. Args: chain (iterable): The variables that make up a chain. target_adjacency (dict/:class:`networkx.Graph`): Should be a dict of the form {s: Ns, ...} where s is a variable in the target graph and Ns is the set of neighbours of s. chain_strength (float): The magnitude of the quadratic bias that should be used to create chains. Returns: dict[edge, float]: The quadratic biases that induce the given chain. Raises: ValueError: If the variables in chain do not form a connected subgraph of target. Examples: >>> chain = {1, 2} >>> target_adjacency = {0: {1, 2}, 1: {0, 2}, 2: {0, 1}} >>> dimod.embedding.chain_to_quadratic(chain, target_adjacency, 1) {(1, 2): -1} """ quadratic = {} # we will be adding the edges that make the chain here # do a breadth first search seen = set() try: next_level = {next(iter(chain))} except StopIteration: raise ValueError("chain must have at least one variable") while next_level: this_level = next_level next_level = set() for v in this_level: if v not in seen: seen.add(v) for u in target_adjacency[v]: if u not in chain: continue next_level.add(u) if u != v and (u, v) not in quadratic: quadratic[(v, u)] = -chain_strength if len(chain) != len(seen): raise ValueError('{} is not a connected chain'.format(chain)) return quadratic
python
def chain_to_quadratic(chain, target_adjacency, chain_strength): quadratic = {} # we will be adding the edges that make the chain here # do a breadth first search seen = set() try: next_level = {next(iter(chain))} except StopIteration: raise ValueError("chain must have at least one variable") while next_level: this_level = next_level next_level = set() for v in this_level: if v not in seen: seen.add(v) for u in target_adjacency[v]: if u not in chain: continue next_level.add(u) if u != v and (u, v) not in quadratic: quadratic[(v, u)] = -chain_strength if len(chain) != len(seen): raise ValueError('{} is not a connected chain'.format(chain)) return quadratic
[ "def", "chain_to_quadratic", "(", "chain", ",", "target_adjacency", ",", "chain_strength", ")", ":", "quadratic", "=", "{", "}", "# we will be adding the edges that make the chain here", "# do a breadth first search", "seen", "=", "set", "(", ")", "try", ":", "next_leve...
Determine the quadratic biases that induce the given chain. Args: chain (iterable): The variables that make up a chain. target_adjacency (dict/:class:`networkx.Graph`): Should be a dict of the form {s: Ns, ...} where s is a variable in the target graph and Ns is the set of neighbours of s. chain_strength (float): The magnitude of the quadratic bias that should be used to create chains. Returns: dict[edge, float]: The quadratic biases that induce the given chain. Raises: ValueError: If the variables in chain do not form a connected subgraph of target. Examples: >>> chain = {1, 2} >>> target_adjacency = {0: {1, 2}, 1: {0, 2}, 2: {0, 1}} >>> dimod.embedding.chain_to_quadratic(chain, target_adjacency, 1) {(1, 2): -1}
[ "Determine", "the", "quadratic", "biases", "that", "induce", "the", "given", "chain", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/utils.py#L98-L150
19,618
dwavesystems/dwave-system
dwave/embedding/utils.py
chain_break_frequency
def chain_break_frequency(samples_like, embedding): """Determine the frequency of chain breaks in the given samples. Args: samples_like (samples_like/:obj:`dimod.SampleSet`): A collection of raw samples. 'samples_like' is an extension of NumPy's array_like. See :func:`dimod.as_samples`. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. Returns: dict: Frequency of chain breaks as a dict in the form {s: f, ...}, where s is a variable in the source graph, and frequency, a float, is the fraction of broken chains. Examples: This example embeds a single source node, 'a', as a chain of two target nodes (0, 1) and uses :func:`.chain_break_frequency` to show that out of two synthetic samples, one ([-1, +1]) represents a broken chain. >>> import dimod >>> import numpy as np >>> samples = np.array([[-1, +1], [+1, +1]]) >>> embedding = {'a': {0, 1}} >>> print(dimod.chain_break_frequency(samples, embedding)['a']) 0.5 This example embeds a single source node (0) as a chain of two target nodes (a, b) and uses :func:`.chain_break_frequency` to show that out of two samples in a dimod response, one ({'a': 1, 'b': 0}) represents a broken chain. >>> import dimod ... >>> response = dimod.SampleSet.from_samples([{'a': 1, 'b': 0}, {'a': 0, 'b': 0}], ... {'energy': [1, 0]}, {}, dimod.BINARY) >>> embedding = {0: {'a', 'b'}} >>> print(dimod.chain_break_frequency(response, embedding)[0]) 0.5 """ if isinstance(samples_like, dimod.SampleSet): labels = samples_like.variables samples = samples_like.record.sample num_occurrences = samples_like.record.num_occurrences else: samples, labels = dimod.as_samples(samples_like) num_occurrences = np.ones(samples.shape[0]) if not all(v == idx for idx, v in enumerate(labels)): labels_to_idx = {v: idx for idx, v in enumerate(labels)} embedding = {v: {labels_to_idx[u] for u in chain} for v, chain in embedding.items()} if not embedding: return {} variables, chains = zip(*embedding.items()) broken = broken_chains(samples, chains) return {v: float(np.average(broken[:, cidx], weights=num_occurrences)) for cidx, v in enumerate(variables)}
python
def chain_break_frequency(samples_like, embedding): if isinstance(samples_like, dimod.SampleSet): labels = samples_like.variables samples = samples_like.record.sample num_occurrences = samples_like.record.num_occurrences else: samples, labels = dimod.as_samples(samples_like) num_occurrences = np.ones(samples.shape[0]) if not all(v == idx for idx, v in enumerate(labels)): labels_to_idx = {v: idx for idx, v in enumerate(labels)} embedding = {v: {labels_to_idx[u] for u in chain} for v, chain in embedding.items()} if not embedding: return {} variables, chains = zip(*embedding.items()) broken = broken_chains(samples, chains) return {v: float(np.average(broken[:, cidx], weights=num_occurrences)) for cidx, v in enumerate(variables)}
[ "def", "chain_break_frequency", "(", "samples_like", ",", "embedding", ")", ":", "if", "isinstance", "(", "samples_like", ",", "dimod", ".", "SampleSet", ")", ":", "labels", "=", "samples_like", ".", "variables", "samples", "=", "samples_like", ".", "record", ...
Determine the frequency of chain breaks in the given samples. Args: samples_like (samples_like/:obj:`dimod.SampleSet`): A collection of raw samples. 'samples_like' is an extension of NumPy's array_like. See :func:`dimod.as_samples`. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. Returns: dict: Frequency of chain breaks as a dict in the form {s: f, ...}, where s is a variable in the source graph, and frequency, a float, is the fraction of broken chains. Examples: This example embeds a single source node, 'a', as a chain of two target nodes (0, 1) and uses :func:`.chain_break_frequency` to show that out of two synthetic samples, one ([-1, +1]) represents a broken chain. >>> import dimod >>> import numpy as np >>> samples = np.array([[-1, +1], [+1, +1]]) >>> embedding = {'a': {0, 1}} >>> print(dimod.chain_break_frequency(samples, embedding)['a']) 0.5 This example embeds a single source node (0) as a chain of two target nodes (a, b) and uses :func:`.chain_break_frequency` to show that out of two samples in a dimod response, one ({'a': 1, 'b': 0}) represents a broken chain. >>> import dimod ... >>> response = dimod.SampleSet.from_samples([{'a': 1, 'b': 0}, {'a': 0, 'b': 0}], ... {'energy': [1, 0]}, {}, dimod.BINARY) >>> embedding = {0: {'a', 'b'}} >>> print(dimod.chain_break_frequency(response, embedding)[0]) 0.5
[ "Determine", "the", "frequency", "of", "chain", "breaks", "in", "the", "given", "samples", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/utils.py#L153-L216
19,619
dwavesystems/dwave-system
dwave/embedding/utils.py
edgelist_to_adjacency
def edgelist_to_adjacency(edgelist): """Converts an iterator of edges to an adjacency dict. Args: edgelist (iterable): An iterator over 2-tuples where each 2-tuple is an edge. Returns: dict: The adjacency dict. A dict of the form {v: Nv, ...} where v is a node in a graph and Nv is the neighbors of v as an set. """ adjacency = dict() for u, v in edgelist: if u in adjacency: adjacency[u].add(v) else: adjacency[u] = {v} if v in adjacency: adjacency[v].add(u) else: adjacency[v] = {u} return adjacency
python
def edgelist_to_adjacency(edgelist): adjacency = dict() for u, v in edgelist: if u in adjacency: adjacency[u].add(v) else: adjacency[u] = {v} if v in adjacency: adjacency[v].add(u) else: adjacency[v] = {u} return adjacency
[ "def", "edgelist_to_adjacency", "(", "edgelist", ")", ":", "adjacency", "=", "dict", "(", ")", "for", "u", ",", "v", "in", "edgelist", ":", "if", "u", "in", "adjacency", ":", "adjacency", "[", "u", "]", ".", "add", "(", "v", ")", "else", ":", "adja...
Converts an iterator of edges to an adjacency dict. Args: edgelist (iterable): An iterator over 2-tuples where each 2-tuple is an edge. Returns: dict: The adjacency dict. A dict of the form {v: Nv, ...} where v is a node in a graph and Nv is the neighbors of v as an set.
[ "Converts", "an", "iterator", "of", "edges", "to", "an", "adjacency", "dict", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/utils.py#L219-L241
19,620
dwavesystems/dwave-system
dwave/system/composites/tiling.py
TilingComposite.sample
def sample(self, bqm, **kwargs): """Sample from the specified binary quadratic model. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Optional keyword arguments for the sampling method, specified per solver. Returns: :class:`dimod.SampleSet` Examples: This example submits a simple Ising problem of just two variables on a D-Wave system selected by the user's default :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`. Because the problem fits in a single :term:`Chimera` unit cell, it is tiled across the solver's entire Chimera graph, resulting in multiple samples (the exact number depends on the working Chimera graph of the D-Wave system). >>> from dwave.system.samplers import DWaveSampler >>> from dwave.system.composites import EmbeddingComposite >>> from dwave.system.composites import EmbeddingComposite, TilingComposite ... >>> sampler = EmbeddingComposite(TilingComposite(DWaveSampler(), 1, 1, 4)) >>> response = sampler.sample_ising({},{('a', 'b'): 1}) >>> len(response) # doctest: +SKIP 246 See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools. """ # apply the embeddings to the given problem to tile it across the child sampler embedded_bqm = dimod.BinaryQuadraticModel.empty(bqm.vartype) __, __, target_adjacency = self.child.structure for embedding in self.embeddings: embedded_bqm.update(dwave.embedding.embed_bqm(bqm, embedding, target_adjacency)) # solve the problem on the child system tiled_response = self.child.sample(embedded_bqm, **kwargs) responses = [] for embedding in self.embeddings: embedding = {v: chain for v, chain in embedding.items() if v in bqm.variables} responses.append(dwave.embedding.unembed_sampleset(tiled_response, embedding, bqm)) return dimod.concatenate(responses)
python
def sample(self, bqm, **kwargs): # apply the embeddings to the given problem to tile it across the child sampler embedded_bqm = dimod.BinaryQuadraticModel.empty(bqm.vartype) __, __, target_adjacency = self.child.structure for embedding in self.embeddings: embedded_bqm.update(dwave.embedding.embed_bqm(bqm, embedding, target_adjacency)) # solve the problem on the child system tiled_response = self.child.sample(embedded_bqm, **kwargs) responses = [] for embedding in self.embeddings: embedding = {v: chain for v, chain in embedding.items() if v in bqm.variables} responses.append(dwave.embedding.unembed_sampleset(tiled_response, embedding, bqm)) return dimod.concatenate(responses)
[ "def", "sample", "(", "self", ",", "bqm", ",", "*", "*", "kwargs", ")", ":", "# apply the embeddings to the given problem to tile it across the child sampler", "embedded_bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "empty", "(", "bqm", ".", "vartype", ")", ...
Sample from the specified binary quadratic model. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Optional keyword arguments for the sampling method, specified per solver. Returns: :class:`dimod.SampleSet` Examples: This example submits a simple Ising problem of just two variables on a D-Wave system selected by the user's default :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`. Because the problem fits in a single :term:`Chimera` unit cell, it is tiled across the solver's entire Chimera graph, resulting in multiple samples (the exact number depends on the working Chimera graph of the D-Wave system). >>> from dwave.system.samplers import DWaveSampler >>> from dwave.system.composites import EmbeddingComposite >>> from dwave.system.composites import EmbeddingComposite, TilingComposite ... >>> sampler = EmbeddingComposite(TilingComposite(DWaveSampler(), 1, 1, 4)) >>> response = sampler.sample_ising({},{('a', 'b'): 1}) >>> len(response) # doctest: +SKIP 246 See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools.
[ "Sample", "from", "the", "specified", "binary", "quadratic", "model", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/composites/tiling.py#L199-L250
19,621
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
cache_connect
def cache_connect(database=None): """Returns a connection object to a sqlite database. Args: database (str, optional): The path to the database the user wishes to connect to. If not specified, a default is chosen using :func:`.cache_file`. If the special database name ':memory:' is given, then a temporary database is created in memory. Returns: :class:`sqlite3.Connection` """ if database is None: database = cache_file() if os.path.isfile(database): # just connect to the database as-is conn = sqlite3.connect(database) else: # we need to populate the database conn = sqlite3.connect(database) conn.executescript(schema) with conn as cur: # turn on foreign keys, allows deletes to cascade. cur.execute("PRAGMA foreign_keys = ON;") conn.row_factory = sqlite3.Row return conn
python
def cache_connect(database=None): if database is None: database = cache_file() if os.path.isfile(database): # just connect to the database as-is conn = sqlite3.connect(database) else: # we need to populate the database conn = sqlite3.connect(database) conn.executescript(schema) with conn as cur: # turn on foreign keys, allows deletes to cascade. cur.execute("PRAGMA foreign_keys = ON;") conn.row_factory = sqlite3.Row return conn
[ "def", "cache_connect", "(", "database", "=", "None", ")", ":", "if", "database", "is", "None", ":", "database", "=", "cache_file", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "database", ")", ":", "# just connect to the database as-is", "conn", ...
Returns a connection object to a sqlite database. Args: database (str, optional): The path to the database the user wishes to connect to. If not specified, a default is chosen using :func:`.cache_file`. If the special database name ':memory:' is given, then a temporary database is created in memory. Returns: :class:`sqlite3.Connection`
[ "Returns", "a", "connection", "object", "to", "a", "sqlite", "database", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L37-L67
19,622
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
insert_chain
def insert_chain(cur, chain, encoded_data=None): """Insert a chain into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act as one node. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. Notes: This function assumes that the nodes in chain are index-labeled. """ if encoded_data is None: encoded_data = {} if 'nodes' not in encoded_data: encoded_data['nodes'] = json.dumps(sorted(chain), separators=(',', ':')) if 'chain_length' not in encoded_data: encoded_data['chain_length'] = len(chain) insert = "INSERT OR IGNORE INTO chain(chain_length, nodes) VALUES (:chain_length, :nodes);" cur.execute(insert, encoded_data)
python
def insert_chain(cur, chain, encoded_data=None): if encoded_data is None: encoded_data = {} if 'nodes' not in encoded_data: encoded_data['nodes'] = json.dumps(sorted(chain), separators=(',', ':')) if 'chain_length' not in encoded_data: encoded_data['chain_length'] = len(chain) insert = "INSERT OR IGNORE INTO chain(chain_length, nodes) VALUES (:chain_length, :nodes);" cur.execute(insert, encoded_data)
[ "def", "insert_chain", "(", "cur", ",", "chain", ",", "encoded_data", "=", "None", ")", ":", "if", "encoded_data", "is", "None", ":", "encoded_data", "=", "{", "}", "if", "'nodes'", "not", "in", "encoded_data", ":", "encoded_data", "[", "'nodes'", "]", "...
Insert a chain into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act as one node. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. Notes: This function assumes that the nodes in chain are index-labeled.
[ "Insert", "a", "chain", "into", "the", "cache", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L70-L98
19,623
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
iter_chain
def iter_chain(cur): """Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain. """ select = "SELECT nodes FROM chain" for nodes, in cur.execute(select): yield json.loads(nodes)
python
def iter_chain(cur): select = "SELECT nodes FROM chain" for nodes, in cur.execute(select): yield json.loads(nodes)
[ "def", "iter_chain", "(", "cur", ")", ":", "select", "=", "\"SELECT nodes FROM chain\"", "for", "nodes", ",", "in", "cur", ".", "execute", "(", "select", ")", ":", "yield", "json", ".", "loads", "(", "nodes", ")" ]
Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain.
[ "Iterate", "over", "all", "of", "the", "chains", "in", "the", "database", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L101-L114
19,624
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
insert_system
def insert_system(cur, system_name, encoded_data=None): """Insert a system name into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. system_name (str): The unique name of a system encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. """ if encoded_data is None: encoded_data = {} if 'system_name' not in encoded_data: encoded_data['system_name'] = system_name insert = "INSERT OR IGNORE INTO system(system_name) VALUES (:system_name);" cur.execute(insert, encoded_data)
python
def insert_system(cur, system_name, encoded_data=None): if encoded_data is None: encoded_data = {} if 'system_name' not in encoded_data: encoded_data['system_name'] = system_name insert = "INSERT OR IGNORE INTO system(system_name) VALUES (:system_name);" cur.execute(insert, encoded_data)
[ "def", "insert_system", "(", "cur", ",", "system_name", ",", "encoded_data", "=", "None", ")", ":", "if", "encoded_data", "is", "None", ":", "encoded_data", "=", "{", "}", "if", "'system_name'", "not", "in", "encoded_data", ":", "encoded_data", "[", "'system...
Insert a system name into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. system_name (str): The unique name of a system encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times.
[ "Insert", "a", "system", "name", "into", "the", "cache", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L117-L139
19,625
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
insert_flux_bias
def insert_flux_bias(cur, chain, system, flux_bias, chain_strength, encoded_data=None): """Insert a flux bias offset into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act as one node. system (str): The unique name of a system. flux_bias (float): The flux bias offset associated with the given chain. chain_strength (float): The magnitude of the negative quadratic bias that induces the given chain in an Ising problem. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. """ if encoded_data is None: encoded_data = {} insert_chain(cur, chain, encoded_data) insert_system(cur, system, encoded_data) if 'flux_bias' not in encoded_data: encoded_data['flux_bias'] = _encode_real(flux_bias) if 'chain_strength' not in encoded_data: encoded_data['chain_strength'] = _encode_real(chain_strength) if 'insert_time' not in encoded_data: encoded_data['insert_time'] = datetime.datetime.now() insert = \ """ INSERT OR REPLACE INTO flux_bias(chain_id, system_id, insert_time, flux_bias, chain_strength) SELECT chain.id, system.id, :insert_time, :flux_bias, :chain_strength FROM chain, system WHERE chain.chain_length = :chain_length AND chain.nodes = :nodes AND system.system_name = :system_name; """ cur.execute(insert, encoded_data)
python
def insert_flux_bias(cur, chain, system, flux_bias, chain_strength, encoded_data=None): if encoded_data is None: encoded_data = {} insert_chain(cur, chain, encoded_data) insert_system(cur, system, encoded_data) if 'flux_bias' not in encoded_data: encoded_data['flux_bias'] = _encode_real(flux_bias) if 'chain_strength' not in encoded_data: encoded_data['chain_strength'] = _encode_real(chain_strength) if 'insert_time' not in encoded_data: encoded_data['insert_time'] = datetime.datetime.now() insert = \ """ INSERT OR REPLACE INTO flux_bias(chain_id, system_id, insert_time, flux_bias, chain_strength) SELECT chain.id, system.id, :insert_time, :flux_bias, :chain_strength FROM chain, system WHERE chain.chain_length = :chain_length AND chain.nodes = :nodes AND system.system_name = :system_name; """ cur.execute(insert, encoded_data)
[ "def", "insert_flux_bias", "(", "cur", ",", "chain", ",", "system", ",", "flux_bias", ",", "chain_strength", ",", "encoded_data", "=", "None", ")", ":", "if", "encoded_data", "is", "None", ":", "encoded_data", "=", "{", "}", "insert_chain", "(", "cur", ","...
Insert a flux bias offset into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act as one node. system (str): The unique name of a system. flux_bias (float): The flux bias offset associated with the given chain. chain_strength (float): The magnitude of the negative quadratic bias that induces the given chain in an Ising problem. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times.
[ "Insert", "a", "flux", "bias", "offset", "into", "the", "cache", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L158-L212
19,626
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
get_flux_biases_from_cache
def get_flux_biases_from_cache(cur, chains, system_name, chain_strength, max_age=3600): """Determine the flux biases for all of the the given chains, system and chain strength. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chains (iterable): An iterable of chains. Each chain is a collection of nodes. Chains in embedding act as one node. system_name (str): The unique name of a system. chain_strength (float): The magnitude of the negative quadratic bias that induces the given chain in an Ising problem. max_age (int, optional, default=3600): The maximum age (in seconds) for the flux_bias offsets. Returns: dict: A dict where the keys are the nodes in the chains and the values are the flux biases. """ select = \ """ SELECT flux_bias FROM flux_bias_view WHERE chain_length = :chain_length AND nodes = :nodes AND chain_strength = :chain_strength AND system_name = :system_name AND insert_time >= :time_limit; """ encoded_data = {'chain_strength': _encode_real(chain_strength), 'system_name': system_name, 'time_limit': datetime.datetime.now() + datetime.timedelta(seconds=-max_age)} flux_biases = {} for chain in chains: encoded_data['chain_length'] = len(chain) encoded_data['nodes'] = json.dumps(sorted(chain), separators=(',', ':')) row = cur.execute(select, encoded_data).fetchone() if row is None: raise MissingFluxBias flux_bias = _decode_real(*row) if flux_bias == 0: continue flux_biases.update({v: flux_bias for v in chain}) return flux_biases
python
def get_flux_biases_from_cache(cur, chains, system_name, chain_strength, max_age=3600): select = \ """ SELECT flux_bias FROM flux_bias_view WHERE chain_length = :chain_length AND nodes = :nodes AND chain_strength = :chain_strength AND system_name = :system_name AND insert_time >= :time_limit; """ encoded_data = {'chain_strength': _encode_real(chain_strength), 'system_name': system_name, 'time_limit': datetime.datetime.now() + datetime.timedelta(seconds=-max_age)} flux_biases = {} for chain in chains: encoded_data['chain_length'] = len(chain) encoded_data['nodes'] = json.dumps(sorted(chain), separators=(',', ':')) row = cur.execute(select, encoded_data).fetchone() if row is None: raise MissingFluxBias flux_bias = _decode_real(*row) if flux_bias == 0: continue flux_biases.update({v: flux_bias for v in chain}) return flux_biases
[ "def", "get_flux_biases_from_cache", "(", "cur", ",", "chains", ",", "system_name", ",", "chain_strength", ",", "max_age", "=", "3600", ")", ":", "select", "=", "\"\"\"\n SELECT\n flux_bias\n FROM flux_bias_view WHERE\n chain_length = :chain_le...
Determine the flux biases for all of the the given chains, system and chain strength. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chains (iterable): An iterable of chains. Each chain is a collection of nodes. Chains in embedding act as one node. system_name (str): The unique name of a system. chain_strength (float): The magnitude of the negative quadratic bias that induces the given chain in an Ising problem. max_age (int, optional, default=3600): The maximum age (in seconds) for the flux_bias offsets. Returns: dict: A dict where the keys are the nodes in the chains and the values are the flux biases.
[ "Determine", "the", "flux", "biases", "for", "all", "of", "the", "the", "given", "chains", "system", "and", "chain", "strength", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L255-L312
19,627
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
insert_graph
def insert_graph(cur, nodelist, edgelist, encoded_data=None): """Insert a graph into the cache. A graph is stored by number of nodes, number of edges and a json-encoded list of edges. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. nodelist (list): The nodes in the graph. edgelist (list): The edges in the graph. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. Notes: This function assumes that the nodes are index-labeled and range from 0 to num_nodes - 1. In order to minimize the total size of the cache, it is a good idea to sort the nodelist and edgelist before inserting. Examples: >>> nodelist = [0, 1, 2] >>> edgelist = [(0, 1), (1, 2)] >>> with pmc.cache_connect(':memory:') as cur: ... pmc.insert_graph(cur, nodelist, edgelist) >>> nodelist = [0, 1, 2] >>> edgelist = [(0, 1), (1, 2)] >>> encoded_data = {} >>> with pmc.cache_connect(':memory:') as cur: ... pmc.insert_graph(cur, nodelist, edgelist, encoded_data) >>> encoded_data['num_nodes'] 3 >>> encoded_data['num_edges'] 2 >>> encoded_data['edges'] '[[0,1],[1,2]]' """ if encoded_data is None: encoded_data = {} if 'num_nodes' not in encoded_data: encoded_data['num_nodes'] = len(nodelist) if 'num_edges' not in encoded_data: encoded_data['num_edges'] = len(edgelist) if 'edges' not in encoded_data: encoded_data['edges'] = json.dumps(edgelist, separators=(',', ':')) insert = \ """ INSERT OR IGNORE INTO graph(num_nodes, num_edges, edges) VALUES (:num_nodes, :num_edges, :edges); """ cur.execute(insert, encoded_data)
python
def insert_graph(cur, nodelist, edgelist, encoded_data=None): if encoded_data is None: encoded_data = {} if 'num_nodes' not in encoded_data: encoded_data['num_nodes'] = len(nodelist) if 'num_edges' not in encoded_data: encoded_data['num_edges'] = len(edgelist) if 'edges' not in encoded_data: encoded_data['edges'] = json.dumps(edgelist, separators=(',', ':')) insert = \ """ INSERT OR IGNORE INTO graph(num_nodes, num_edges, edges) VALUES (:num_nodes, :num_edges, :edges); """ cur.execute(insert, encoded_data)
[ "def", "insert_graph", "(", "cur", ",", "nodelist", ",", "edgelist", ",", "encoded_data", "=", "None", ")", ":", "if", "encoded_data", "is", "None", ":", "encoded_data", "=", "{", "}", "if", "'num_nodes'", "not", "in", "encoded_data", ":", "encoded_data", ...
Insert a graph into the cache. A graph is stored by number of nodes, number of edges and a json-encoded list of edges. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. nodelist (list): The nodes in the graph. edgelist (list): The edges in the graph. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. Notes: This function assumes that the nodes are index-labeled and range from 0 to num_nodes - 1. In order to minimize the total size of the cache, it is a good idea to sort the nodelist and edgelist before inserting. Examples: >>> nodelist = [0, 1, 2] >>> edgelist = [(0, 1), (1, 2)] >>> with pmc.cache_connect(':memory:') as cur: ... pmc.insert_graph(cur, nodelist, edgelist) >>> nodelist = [0, 1, 2] >>> edgelist = [(0, 1), (1, 2)] >>> encoded_data = {} >>> with pmc.cache_connect(':memory:') as cur: ... pmc.insert_graph(cur, nodelist, edgelist, encoded_data) >>> encoded_data['num_nodes'] 3 >>> encoded_data['num_edges'] 2 >>> encoded_data['edges'] '[[0,1],[1,2]]'
[ "Insert", "a", "graph", "into", "the", "cache", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L315-L372
19,628
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
select_embedding_from_tag
def select_embedding_from_tag(cur, embedding_tag, target_nodelist, target_edgelist): """Select an embedding from the given tag and target graph. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. source_nodelist (list): The nodes in the source graph. Should be integer valued. source_edgelist (list): The edges in the source graph. target_nodelist (list): The nodes in the target graph. Should be integer valued. target_edgelist (list): The edges in the target graph. Returns: dict: The mapping from the source graph to the target graph. In the form {v: {s, ...}, ...} where v is a variable in the source model and s is a variable in the target model. """ encoded_data = {'num_nodes': len(target_nodelist), 'num_edges': len(target_edgelist), 'edges': json.dumps(target_edgelist, separators=(',', ':')), 'tag': embedding_tag} select = \ """ SELECT source_node, chain FROM embedding_component_view WHERE embedding_tag = :tag AND target_edges = :edges AND target_num_nodes = :num_nodes AND target_num_edges = :num_edges """ embedding = {v: json.loads(chain) for v, chain in cur.execute(select, encoded_data)} return embedding
python
def select_embedding_from_tag(cur, embedding_tag, target_nodelist, target_edgelist): encoded_data = {'num_nodes': len(target_nodelist), 'num_edges': len(target_edgelist), 'edges': json.dumps(target_edgelist, separators=(',', ':')), 'tag': embedding_tag} select = \ """ SELECT source_node, chain FROM embedding_component_view WHERE embedding_tag = :tag AND target_edges = :edges AND target_num_nodes = :num_nodes AND target_num_edges = :num_edges """ embedding = {v: json.loads(chain) for v, chain in cur.execute(select, encoded_data)} return embedding
[ "def", "select_embedding_from_tag", "(", "cur", ",", "embedding_tag", ",", "target_nodelist", ",", "target_edgelist", ")", ":", "encoded_data", "=", "{", "'num_nodes'", ":", "len", "(", "target_nodelist", ")", ",", "'num_edges'", ":", "len", "(", "target_edgelist"...
Select an embedding from the given tag and target graph. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. source_nodelist (list): The nodes in the source graph. Should be integer valued. source_edgelist (list): The edges in the source graph. target_nodelist (list): The nodes in the target graph. Should be integer valued. target_edgelist (list): The edges in the target graph. Returns: dict: The mapping from the source graph to the target graph. In the form {v: {s, ...}, ...} where v is a variable in the source model and s is a variable in the target model.
[ "Select", "an", "embedding", "from", "the", "given", "tag", "and", "target", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L512-L557
19,629
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
select_embedding_from_source
def select_embedding_from_source(cur, source_nodelist, source_edgelist, target_nodelist, target_edgelist): """Select an embedding from the source graph and target graph. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. target_nodelist (list): The nodes in the target graph. Should be integer valued. target_edgelist (list): The edges in the target graph. embedding_tag (str): A string tag to associate with the embedding. Returns: dict: The mapping from the source graph to the target graph. In the form {v: {s, ...}, ...} where v is a variable in the source model and s is a variable in the target model. """ encoded_data = {'target_num_nodes': len(target_nodelist), 'target_num_edges': len(target_edgelist), 'target_edges': json.dumps(target_edgelist, separators=(',', ':')), 'source_num_nodes': len(source_nodelist), 'source_num_edges': len(source_edgelist), 'source_edges': json.dumps(source_edgelist, separators=(',', ':'))} select = \ """ SELECT source_node, chain FROM embedding_component_view WHERE source_num_edges = :source_num_edges AND source_edges = :source_edges AND source_num_nodes = :source_num_nodes AND target_num_edges = :target_num_edges AND target_edges = :target_edges AND target_num_nodes = :target_num_nodes """ embedding = {v: json.loads(chain) for v, chain in cur.execute(select, encoded_data)} return embedding
python
def select_embedding_from_source(cur, source_nodelist, source_edgelist, target_nodelist, target_edgelist): encoded_data = {'target_num_nodes': len(target_nodelist), 'target_num_edges': len(target_edgelist), 'target_edges': json.dumps(target_edgelist, separators=(',', ':')), 'source_num_nodes': len(source_nodelist), 'source_num_edges': len(source_edgelist), 'source_edges': json.dumps(source_edgelist, separators=(',', ':'))} select = \ """ SELECT source_node, chain FROM embedding_component_view WHERE source_num_edges = :source_num_edges AND source_edges = :source_edges AND source_num_nodes = :source_num_nodes AND target_num_edges = :target_num_edges AND target_edges = :target_edges AND target_num_nodes = :target_num_nodes """ embedding = {v: json.loads(chain) for v, chain in cur.execute(select, encoded_data)} return embedding
[ "def", "select_embedding_from_source", "(", "cur", ",", "source_nodelist", ",", "source_edgelist", ",", "target_nodelist", ",", "target_edgelist", ")", ":", "encoded_data", "=", "{", "'target_num_nodes'", ":", "len", "(", "target_nodelist", ")", ",", "'target_num_edge...
Select an embedding from the source graph and target graph. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. target_nodelist (list): The nodes in the target graph. Should be integer valued. target_edgelist (list): The edges in the target graph. embedding_tag (str): A string tag to associate with the embedding. Returns: dict: The mapping from the source graph to the target graph. In the form {v: {s, ...}, ...} where v is a variable in the source model and s is a variable in the target model.
[ "Select", "an", "embedding", "from", "the", "source", "graph", "and", "target", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L560-L608
19,630
dwavesystems/dwave-system
dwave/embedding/drawing.py
draw_chimera_bqm
def draw_chimera_bqm(bqm, width=None, height=None): """Draws a Chimera Graph representation of a Binary Quadratic Model. If cell width and height not provided assumes square cell dimensions. Throws an error if drawing onto a Chimera graph of the given dimensions fails. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Should be equivalent to a Chimera graph or a subgraph of a Chimera graph produced by dnx.chimera_graph. The nodes and edges should have integer variables as in the dnx.chimera_graph. width (int, optional): An integer representing the number of cells of the Chimera graph will be in width. height (int, optional): An integer representing the number of cells of the Chimera graph will be in height. Examples: >>> from dwave.embedding.drawing import draw_chimera_bqm >>> from dimod import BinaryQuadraticModel >>> Q={(0, 0): 2, (1, 1): 1, (2, 2): 0, (3, 3): -1, (4, 4): -2, (5, 5): -2, (6, 6): -2, (7, 7): -2, ... (0, 4): 2, (0, 4): -1, (1, 7): 1, (1, 5): 0, (2, 5): -2, (2, 6): -2, (3, 4): -2, (3, 7): -2} >>> draw_chimera_bqm(BinaryQuadraticModel.from_qubo(Q), width=1, height=1) """ linear = bqm.linear.keys() quadratic = bqm.quadratic.keys() if width is None and height is None: # Create a graph large enough to fit the input networkx graph. graph_size = ceil(sqrt((max(linear) + 1) / 8.0)) width = graph_size height = graph_size if not width or not height: raise Exception("Both dimensions must be defined, not just one.") # A background image of the same size is created to show the complete graph. G0 = chimera_graph(height, width, 4) G = chimera_graph(height, width, 4) # Check if input graph is chimera graph shaped, by making sure that no edges are invalid. # Invalid edges can also appear if the size of the chimera graph is incompatible with the input graph in cell dimensions. non_chimera_nodes = [] non_chimera_edges = [] for node in linear: if not node in G.nodes: non_chimera_nodes.append(node) for edge in quadratic: if not edge in G.edges: non_chimera_edges.append(edge) linear_set = set(linear) g_node_set = set(G.nodes) quadratic_set = set(map(frozenset, quadratic)) g_edge_set = set(map(frozenset, G.edges)) non_chimera_nodes = linear_set - g_node_set non_chimera_edges = quadratic_set - g_edge_set if non_chimera_nodes or non_chimera_edges: raise Exception("Input graph is not a chimera graph: Nodes: %s Edges: %s" % (non_chimera_nodes, non_chimera_edges)) # Get lists of nodes and edges to remove from the complete graph to turn the complete graph into your graph. remove_nodes = list(g_node_set - linear_set) remove_edges = list(g_edge_set - quadratic_set) # Remove the nodes and edges from the graph. for edge in remove_edges: G.remove_edge(*edge) for node in remove_nodes: G.remove_node(node) node_size = 100 # Draw the complete chimera graph as the background. draw_chimera(G0, node_size=node_size*0.5, node_color='black', edge_color='black') # Draw your graph over the complete graph to show the connectivity. draw_chimera(G, node_size=node_size, linear_biases=bqm.linear, quadratic_biases=bqm.quadratic, width=3) return
python
def draw_chimera_bqm(bqm, width=None, height=None): linear = bqm.linear.keys() quadratic = bqm.quadratic.keys() if width is None and height is None: # Create a graph large enough to fit the input networkx graph. graph_size = ceil(sqrt((max(linear) + 1) / 8.0)) width = graph_size height = graph_size if not width or not height: raise Exception("Both dimensions must be defined, not just one.") # A background image of the same size is created to show the complete graph. G0 = chimera_graph(height, width, 4) G = chimera_graph(height, width, 4) # Check if input graph is chimera graph shaped, by making sure that no edges are invalid. # Invalid edges can also appear if the size of the chimera graph is incompatible with the input graph in cell dimensions. non_chimera_nodes = [] non_chimera_edges = [] for node in linear: if not node in G.nodes: non_chimera_nodes.append(node) for edge in quadratic: if not edge in G.edges: non_chimera_edges.append(edge) linear_set = set(linear) g_node_set = set(G.nodes) quadratic_set = set(map(frozenset, quadratic)) g_edge_set = set(map(frozenset, G.edges)) non_chimera_nodes = linear_set - g_node_set non_chimera_edges = quadratic_set - g_edge_set if non_chimera_nodes or non_chimera_edges: raise Exception("Input graph is not a chimera graph: Nodes: %s Edges: %s" % (non_chimera_nodes, non_chimera_edges)) # Get lists of nodes and edges to remove from the complete graph to turn the complete graph into your graph. remove_nodes = list(g_node_set - linear_set) remove_edges = list(g_edge_set - quadratic_set) # Remove the nodes and edges from the graph. for edge in remove_edges: G.remove_edge(*edge) for node in remove_nodes: G.remove_node(node) node_size = 100 # Draw the complete chimera graph as the background. draw_chimera(G0, node_size=node_size*0.5, node_color='black', edge_color='black') # Draw your graph over the complete graph to show the connectivity. draw_chimera(G, node_size=node_size, linear_biases=bqm.linear, quadratic_biases=bqm.quadratic, width=3) return
[ "def", "draw_chimera_bqm", "(", "bqm", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "linear", "=", "bqm", ".", "linear", ".", "keys", "(", ")", "quadratic", "=", "bqm", ".", "quadratic", ".", "keys", "(", ")", "if", "width", "is...
Draws a Chimera Graph representation of a Binary Quadratic Model. If cell width and height not provided assumes square cell dimensions. Throws an error if drawing onto a Chimera graph of the given dimensions fails. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Should be equivalent to a Chimera graph or a subgraph of a Chimera graph produced by dnx.chimera_graph. The nodes and edges should have integer variables as in the dnx.chimera_graph. width (int, optional): An integer representing the number of cells of the Chimera graph will be in width. height (int, optional): An integer representing the number of cells of the Chimera graph will be in height. Examples: >>> from dwave.embedding.drawing import draw_chimera_bqm >>> from dimod import BinaryQuadraticModel >>> Q={(0, 0): 2, (1, 1): 1, (2, 2): 0, (3, 3): -1, (4, 4): -2, (5, 5): -2, (6, 6): -2, (7, 7): -2, ... (0, 4): 2, (0, 4): -1, (1, 7): 1, (1, 5): 0, (2, 5): -2, (2, 6): -2, (3, 4): -2, (3, 7): -2} >>> draw_chimera_bqm(BinaryQuadraticModel.from_qubo(Q), width=1, height=1)
[ "Draws", "a", "Chimera", "Graph", "representation", "of", "a", "Binary", "Quadratic", "Model", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/drawing.py#L23-L104
19,631
dwavesystems/dwave-system
dwave/embedding/transforms.py
embed_bqm
def embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=1.0, smear_vartype=None): """Embed a binary quadratic model onto a target graph. Args: source_bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to embed. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. target_adjacency (dict/:class:`networkx.Graph`): Adjacency of the target graph as a dict of form {t: Nt, ...}, where t is a variable in the target graph and Nt is its set of neighbours. chain_strength (float, optional): Magnitude of the quadratic bias (in SPIN-space) applied between variables to create chains. Note that the energy penalty of chain breaks is 2 * `chain_strength`. smear_vartype (:class:`.Vartype`, optional, default=None): When a single variable is embedded, it's linear bias is 'smeared' evenly over the chain. This parameter determines whether the variable is smeared in SPIN or BINARY space. By default the embedding is done according to the given source_bqm. Returns: :obj:`.BinaryQuadraticModel`: Target binary quadratic model. Examples: This example embeds a fully connected :math:`K_3` graph onto a square target graph. Embedding is accomplished by an edge contraction operation on the target graph: target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> import networkx as nx >>> # Binary quadratic model for a triangular source graph >>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1}) >>> # Target graph is a graph >>> target = nx.cycle_graph(4) >>> # Embedding from source to target graphs >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the BQM >>> target_bqm = dimod.embed_bqm(bqm, embedding, target) >>> target_bqm.quadratic[(0, 1)] == bqm.quadratic[('a', 'b')] True >>> target_bqm.quadratic # doctest: +SKIP {(0, 1): 1.0, (0, 3): 1.0, (1, 2): 1.0, (2, 3): -1.0} This example embeds a fully connected :math:`K_3` graph onto the target graph of a dimod reference structured sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a square graph specified. Target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> # Binary quadratic model for a triangular source graph >>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1}) >>> # Structured dimod sampler with a structure defined by a square graph >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), [0, 1, 2, 3], [(0, 1), (1, 2), (2, 3), (0, 3)]) >>> # Embedding from source to target graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the BQM >>> target_bqm = dimod.embed_bqm(bqm, embedding, sampler.adjacency) >>> # Sample >>> samples = sampler.sample(target_bqm) >>> samples.record.sample # doctest: +SKIP array([[-1, -1, -1, -1], [ 1, -1, -1, -1], [ 1, 1, -1, -1], [-1, 1, -1, -1], [-1, 1, 1, -1], >>> # Snipped above samples for brevity """ if smear_vartype is dimod.SPIN and source_bqm.vartype is dimod.BINARY: return embed_bqm(source_bqm.spin, embedding, target_adjacency, chain_strength=chain_strength, smear_vartype=None).binary elif smear_vartype is dimod.BINARY and source_bqm.vartype is dimod.SPIN: return embed_bqm(source_bqm.binary, embedding, target_adjacency, chain_strength=chain_strength, smear_vartype=None).spin # create a new empty binary quadratic model with the same class as source_bqm target_bqm = source_bqm.empty(source_bqm.vartype) # add the offset target_bqm.add_offset(source_bqm.offset) # start with the linear biases, spreading the source bias equally over the target variables in # the chain for v, bias in iteritems(source_bqm.linear): if v in embedding: chain = embedding[v] else: raise MissingChainError(v) if any(u not in target_adjacency for u in chain): raise InvalidNodeError(v, next(u not in target_adjacency for u in chain)) b = bias / len(chain) target_bqm.add_variables_from({u: b for u in chain}) # next up the quadratic biases, spread the quadratic biases evenly over the available # interactions for (u, v), bias in iteritems(source_bqm.quadratic): available_interactions = {(s, t) for s in embedding[u] for t in embedding[v] if s in target_adjacency[t]} if not available_interactions: raise MissingEdgeError(u, v) b = bias / len(available_interactions) target_bqm.add_interactions_from((u, v, b) for u, v in available_interactions) for chain in itervalues(embedding): # in the case where the chain has length 1, there are no chain quadratic biases, but we # none-the-less want the chain variables to appear in the target_bqm if len(chain) == 1: v, = chain target_bqm.add_variable(v, 0.0) continue quadratic_chain_biases = chain_to_quadratic(chain, target_adjacency, chain_strength) target_bqm.add_interactions_from(quadratic_chain_biases, vartype=dimod.SPIN) # these are spin # add the energy for satisfied chains to the offset energy_diff = -sum(itervalues(quadratic_chain_biases)) target_bqm.add_offset(energy_diff) return target_bqm
python
def embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=1.0, smear_vartype=None): if smear_vartype is dimod.SPIN and source_bqm.vartype is dimod.BINARY: return embed_bqm(source_bqm.spin, embedding, target_adjacency, chain_strength=chain_strength, smear_vartype=None).binary elif smear_vartype is dimod.BINARY and source_bqm.vartype is dimod.SPIN: return embed_bqm(source_bqm.binary, embedding, target_adjacency, chain_strength=chain_strength, smear_vartype=None).spin # create a new empty binary quadratic model with the same class as source_bqm target_bqm = source_bqm.empty(source_bqm.vartype) # add the offset target_bqm.add_offset(source_bqm.offset) # start with the linear biases, spreading the source bias equally over the target variables in # the chain for v, bias in iteritems(source_bqm.linear): if v in embedding: chain = embedding[v] else: raise MissingChainError(v) if any(u not in target_adjacency for u in chain): raise InvalidNodeError(v, next(u not in target_adjacency for u in chain)) b = bias / len(chain) target_bqm.add_variables_from({u: b for u in chain}) # next up the quadratic biases, spread the quadratic biases evenly over the available # interactions for (u, v), bias in iteritems(source_bqm.quadratic): available_interactions = {(s, t) for s in embedding[u] for t in embedding[v] if s in target_adjacency[t]} if not available_interactions: raise MissingEdgeError(u, v) b = bias / len(available_interactions) target_bqm.add_interactions_from((u, v, b) for u, v in available_interactions) for chain in itervalues(embedding): # in the case where the chain has length 1, there are no chain quadratic biases, but we # none-the-less want the chain variables to appear in the target_bqm if len(chain) == 1: v, = chain target_bqm.add_variable(v, 0.0) continue quadratic_chain_biases = chain_to_quadratic(chain, target_adjacency, chain_strength) target_bqm.add_interactions_from(quadratic_chain_biases, vartype=dimod.SPIN) # these are spin # add the energy for satisfied chains to the offset energy_diff = -sum(itervalues(quadratic_chain_biases)) target_bqm.add_offset(energy_diff) return target_bqm
[ "def", "embed_bqm", "(", "source_bqm", ",", "embedding", ",", "target_adjacency", ",", "chain_strength", "=", "1.0", ",", "smear_vartype", "=", "None", ")", ":", "if", "smear_vartype", "is", "dimod", ".", "SPIN", "and", "source_bqm", ".", "vartype", "is", "d...
Embed a binary quadratic model onto a target graph. Args: source_bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to embed. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. target_adjacency (dict/:class:`networkx.Graph`): Adjacency of the target graph as a dict of form {t: Nt, ...}, where t is a variable in the target graph and Nt is its set of neighbours. chain_strength (float, optional): Magnitude of the quadratic bias (in SPIN-space) applied between variables to create chains. Note that the energy penalty of chain breaks is 2 * `chain_strength`. smear_vartype (:class:`.Vartype`, optional, default=None): When a single variable is embedded, it's linear bias is 'smeared' evenly over the chain. This parameter determines whether the variable is smeared in SPIN or BINARY space. By default the embedding is done according to the given source_bqm. Returns: :obj:`.BinaryQuadraticModel`: Target binary quadratic model. Examples: This example embeds a fully connected :math:`K_3` graph onto a square target graph. Embedding is accomplished by an edge contraction operation on the target graph: target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> import networkx as nx >>> # Binary quadratic model for a triangular source graph >>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1}) >>> # Target graph is a graph >>> target = nx.cycle_graph(4) >>> # Embedding from source to target graphs >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the BQM >>> target_bqm = dimod.embed_bqm(bqm, embedding, target) >>> target_bqm.quadratic[(0, 1)] == bqm.quadratic[('a', 'b')] True >>> target_bqm.quadratic # doctest: +SKIP {(0, 1): 1.0, (0, 3): 1.0, (1, 2): 1.0, (2, 3): -1.0} This example embeds a fully connected :math:`K_3` graph onto the target graph of a dimod reference structured sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a square graph specified. Target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> # Binary quadratic model for a triangular source graph >>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1}) >>> # Structured dimod sampler with a structure defined by a square graph >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), [0, 1, 2, 3], [(0, 1), (1, 2), (2, 3), (0, 3)]) >>> # Embedding from source to target graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the BQM >>> target_bqm = dimod.embed_bqm(bqm, embedding, sampler.adjacency) >>> # Sample >>> samples = sampler.sample(target_bqm) >>> samples.record.sample # doctest: +SKIP array([[-1, -1, -1, -1], [ 1, -1, -1, -1], [ 1, 1, -1, -1], [-1, 1, -1, -1], [-1, 1, 1, -1], >>> # Snipped above samples for brevity
[ "Embed", "a", "binary", "quadratic", "model", "onto", "a", "target", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/transforms.py#L38-L168
19,632
dwavesystems/dwave-system
dwave/embedding/transforms.py
embed_ising
def embed_ising(source_h, source_J, embedding, target_adjacency, chain_strength=1.0): """Embed an Ising problem onto a target graph. Args: source_h (dict[variable, bias]/list[bias]): Linear biases of the Ising problem. If a list, the list's indices are used as variable labels. source_J (dict[(variable, variable), bias]): Quadratic biases of the Ising problem. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. target_adjacency (dict/:class:`networkx.Graph`): Adjacency of the target graph as a dict of form {t: Nt, ...}, where t is a target-graph variable and Nt is its set of neighbours. chain_strength (float, optional): Magnitude of the quadratic bias (in SPIN-space) applied between variables to form a chain. Note that the energy penalty of chain breaks is 2 * `chain_strength`. Returns: tuple: A 2-tuple: dict[variable, bias]: Linear biases of the target Ising problem. dict[(variable, variable), bias]: Quadratic biases of the target Ising problem. Examples: This example embeds a fully connected :math:`K_3` graph onto a square target graph. Embedding is accomplished by an edge contraction operation on the target graph: target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> import networkx as nx >>> # Ising problem for a triangular source graph >>> h = {} >>> J = {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1} >>> # Target graph is a square graph >>> target = nx.cycle_graph(4) >>> # Embedding from source to target graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the Ising problem >>> target_h, target_J = dimod.embed_ising(h, J, embedding, target) >>> target_J[(0, 1)] == J[('a', 'b')] True >>> target_J # doctest: +SKIP {(0, 1): 1.0, (0, 3): 1.0, (1, 2): 1.0, (2, 3): -1.0} This example embeds a fully connected :math:`K_3` graph onto the target graph of a dimod reference structured sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a square graph specified. Target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> # Ising problem for a triangular source graph >>> h = {} >>> J = {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1} >>> # Structured dimod sampler with a structure defined by a square graph >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), [0, 1, 2, 3], [(0, 1), (1, 2), (2, 3), (0, 3)]) >>> # Embedding from source to target graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the Ising problem >>> target_h, target_J = dimod.embed_ising(h, J, embedding, sampler.adjacency) >>> # Sample >>> samples = sampler.sample_ising(target_h, target_J) >>> for sample in samples.samples(n=3, sorted_by='energy'): # doctest: +SKIP ... print(sample) ... {0: 1, 1: -1, 2: -1, 3: -1} {0: 1, 1: 1, 2: -1, 3: -1} {0: -1, 1: 1, 2: -1, 3: -1} """ source_bqm = dimod.BinaryQuadraticModel.from_ising(source_h, source_J) target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength) target_h, target_J, __ = target_bqm.to_ising() return target_h, target_J
python
def embed_ising(source_h, source_J, embedding, target_adjacency, chain_strength=1.0): source_bqm = dimod.BinaryQuadraticModel.from_ising(source_h, source_J) target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength) target_h, target_J, __ = target_bqm.to_ising() return target_h, target_J
[ "def", "embed_ising", "(", "source_h", ",", "source_J", ",", "embedding", ",", "target_adjacency", ",", "chain_strength", "=", "1.0", ")", ":", "source_bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "from_ising", "(", "source_h", ",", "source_J", ")", "...
Embed an Ising problem onto a target graph. Args: source_h (dict[variable, bias]/list[bias]): Linear biases of the Ising problem. If a list, the list's indices are used as variable labels. source_J (dict[(variable, variable), bias]): Quadratic biases of the Ising problem. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. target_adjacency (dict/:class:`networkx.Graph`): Adjacency of the target graph as a dict of form {t: Nt, ...}, where t is a target-graph variable and Nt is its set of neighbours. chain_strength (float, optional): Magnitude of the quadratic bias (in SPIN-space) applied between variables to form a chain. Note that the energy penalty of chain breaks is 2 * `chain_strength`. Returns: tuple: A 2-tuple: dict[variable, bias]: Linear biases of the target Ising problem. dict[(variable, variable), bias]: Quadratic biases of the target Ising problem. Examples: This example embeds a fully connected :math:`K_3` graph onto a square target graph. Embedding is accomplished by an edge contraction operation on the target graph: target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> import networkx as nx >>> # Ising problem for a triangular source graph >>> h = {} >>> J = {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1} >>> # Target graph is a square graph >>> target = nx.cycle_graph(4) >>> # Embedding from source to target graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the Ising problem >>> target_h, target_J = dimod.embed_ising(h, J, embedding, target) >>> target_J[(0, 1)] == J[('a', 'b')] True >>> target_J # doctest: +SKIP {(0, 1): 1.0, (0, 3): 1.0, (1, 2): 1.0, (2, 3): -1.0} This example embeds a fully connected :math:`K_3` graph onto the target graph of a dimod reference structured sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a square graph specified. Target-nodes 2 and 3 are chained to represent source-node c. >>> import dimod >>> # Ising problem for a triangular source graph >>> h = {} >>> J = {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1} >>> # Structured dimod sampler with a structure defined by a square graph >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), [0, 1, 2, 3], [(0, 1), (1, 2), (2, 3), (0, 3)]) >>> # Embedding from source to target graph >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}} >>> # Embed the Ising problem >>> target_h, target_J = dimod.embed_ising(h, J, embedding, sampler.adjacency) >>> # Sample >>> samples = sampler.sample_ising(target_h, target_J) >>> for sample in samples.samples(n=3, sorted_by='energy'): # doctest: +SKIP ... print(sample) ... {0: 1, 1: -1, 2: -1, 3: -1} {0: 1, 1: 1, 2: -1, 3: -1} {0: -1, 1: 1, 2: -1, 3: -1}
[ "Embed", "an", "Ising", "problem", "onto", "a", "target", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/transforms.py#L171-L250
19,633
dwavesystems/dwave-system
dwave/embedding/transforms.py
embed_qubo
def embed_qubo(source_Q, embedding, target_adjacency, chain_strength=1.0): """Embed a QUBO onto a target graph. Args: source_Q (dict[(variable, variable), bias]): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. target_adjacency (dict/:class:`networkx.Graph`): Adjacency of the target graph as a dict of form {t: Nt, ...}, where t is a target-graph variable and Nt is its set of neighbours. chain_strength (float, optional): Magnitude of the quadratic bias (in SPIN-space) applied between variables to form a chain. Note that the energy penalty of chain breaks is 2 * `chain_strength`. Returns: dict[(variable, variable), bias]: Quadratic biases of the target QUBO. Examples: This example embeds a square source graph onto fully connected :math:`K_5` graph. Embedding is accomplished by an edge deletion operation on the target graph: target-node 0 is not used. >>> import dimod >>> import networkx as nx >>> # QUBO problem for a square graph >>> Q = {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 3): 4.0, ... (3, 3): -4.0, (3, 4): 4.0, (4, 1): 4.0, (4, 4): -4.0} >>> # Target graph is a fully connected k5 graph >>> K_5 = nx.complete_graph(5) >>> 0 in K_5 True >>> # Embedding from source to target graph >>> embedding = {1: {4}, 2: {3}, 3: {1}, 4: {2}} >>> # Embed the QUBO >>> target_Q = dimod.embed_qubo(Q, embedding, K_5) >>> (0, 0) in target_Q False >>> target_Q # doctest: +SKIP {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 4): 4.0, (3, 1): 4.0, (3, 3): -4.0, (4, 3): 4.0, (4, 4): -4.0} This example embeds a square graph onto the target graph of a dimod reference structured sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a fully connected :math:`K_5` graph specified. >>> import dimod >>> import networkx as nx >>> # QUBO problem for a square graph >>> Q = {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 3): 4.0, ... (3, 3): -4.0, (3, 4): 4.0, (4, 1): 4.0, (4, 4): -4.0} >>> # Structured dimod sampler with a structure defined by a K5 graph >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), list(K_5.nodes), list(K_5.edges)) >>> sampler.adjacency # doctest: +SKIP {0: {1, 2, 3, 4}, 1: {0, 2, 3, 4}, 2: {0, 1, 3, 4}, 3: {0, 1, 2, 4}, 4: {0, 1, 2, 3}} >>> # Embedding from source to target graph >>> embedding = {0: [4], 1: [3], 2: [1], 3: [2], 4: [0]} >>> # Embed the QUBO >>> target_Q = dimod.embed_qubo(Q, embedding, sampler.adjacency) >>> # Sample >>> samples = sampler.sample_qubo(target_Q) >>> for datum in samples.data(): # doctest: +SKIP ... print(datum) ... Sample(sample={1: 0, 2: 1, 3: 1, 4: 0}, energy=-8.0) Sample(sample={1: 1, 2: 0, 3: 0, 4: 1}, energy=-8.0) Sample(sample={1: 1, 2: 0, 3: 0, 4: 0}, energy=-4.0) Sample(sample={1: 1, 2: 1, 3: 0, 4: 0}, energy=-4.0) Sample(sample={1: 0, 2: 1, 3: 0, 4: 0}, energy=-4.0) Sample(sample={1: 1, 2: 1, 3: 1, 4: 0}, energy=-4.0) >>> # Snipped above samples for brevity """ source_bqm = dimod.BinaryQuadraticModel.from_qubo(source_Q) target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength) target_Q, __ = target_bqm.to_qubo() return target_Q
python
def embed_qubo(source_Q, embedding, target_adjacency, chain_strength=1.0): source_bqm = dimod.BinaryQuadraticModel.from_qubo(source_Q) target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength) target_Q, __ = target_bqm.to_qubo() return target_Q
[ "def", "embed_qubo", "(", "source_Q", ",", "embedding", ",", "target_adjacency", ",", "chain_strength", "=", "1.0", ")", ":", "source_bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "from_qubo", "(", "source_Q", ")", "target_bqm", "=", "embed_bqm", "(", ...
Embed a QUBO onto a target graph. Args: source_Q (dict[(variable, variable), bias]): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source-model variable and t is a target-model variable. target_adjacency (dict/:class:`networkx.Graph`): Adjacency of the target graph as a dict of form {t: Nt, ...}, where t is a target-graph variable and Nt is its set of neighbours. chain_strength (float, optional): Magnitude of the quadratic bias (in SPIN-space) applied between variables to form a chain. Note that the energy penalty of chain breaks is 2 * `chain_strength`. Returns: dict[(variable, variable), bias]: Quadratic biases of the target QUBO. Examples: This example embeds a square source graph onto fully connected :math:`K_5` graph. Embedding is accomplished by an edge deletion operation on the target graph: target-node 0 is not used. >>> import dimod >>> import networkx as nx >>> # QUBO problem for a square graph >>> Q = {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 3): 4.0, ... (3, 3): -4.0, (3, 4): 4.0, (4, 1): 4.0, (4, 4): -4.0} >>> # Target graph is a fully connected k5 graph >>> K_5 = nx.complete_graph(5) >>> 0 in K_5 True >>> # Embedding from source to target graph >>> embedding = {1: {4}, 2: {3}, 3: {1}, 4: {2}} >>> # Embed the QUBO >>> target_Q = dimod.embed_qubo(Q, embedding, K_5) >>> (0, 0) in target_Q False >>> target_Q # doctest: +SKIP {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 4): 4.0, (3, 1): 4.0, (3, 3): -4.0, (4, 3): 4.0, (4, 4): -4.0} This example embeds a square graph onto the target graph of a dimod reference structured sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a fully connected :math:`K_5` graph specified. >>> import dimod >>> import networkx as nx >>> # QUBO problem for a square graph >>> Q = {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 3): 4.0, ... (3, 3): -4.0, (3, 4): 4.0, (4, 1): 4.0, (4, 4): -4.0} >>> # Structured dimod sampler with a structure defined by a K5 graph >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), list(K_5.nodes), list(K_5.edges)) >>> sampler.adjacency # doctest: +SKIP {0: {1, 2, 3, 4}, 1: {0, 2, 3, 4}, 2: {0, 1, 3, 4}, 3: {0, 1, 2, 4}, 4: {0, 1, 2, 3}} >>> # Embedding from source to target graph >>> embedding = {0: [4], 1: [3], 2: [1], 3: [2], 4: [0]} >>> # Embed the QUBO >>> target_Q = dimod.embed_qubo(Q, embedding, sampler.adjacency) >>> # Sample >>> samples = sampler.sample_qubo(target_Q) >>> for datum in samples.data(): # doctest: +SKIP ... print(datum) ... Sample(sample={1: 0, 2: 1, 3: 1, 4: 0}, energy=-8.0) Sample(sample={1: 1, 2: 0, 3: 0, 4: 1}, energy=-8.0) Sample(sample={1: 1, 2: 0, 3: 0, 4: 0}, energy=-4.0) Sample(sample={1: 1, 2: 1, 3: 0, 4: 0}, energy=-4.0) Sample(sample={1: 0, 2: 1, 3: 0, 4: 0}, energy=-4.0) Sample(sample={1: 1, 2: 1, 3: 1, 4: 0}, energy=-4.0) >>> # Snipped above samples for brevity
[ "Embed", "a", "QUBO", "onto", "a", "target", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/transforms.py#L253-L343
19,634
dwavesystems/dwave-system
dwave/embedding/transforms.py
unembed_sampleset
def unembed_sampleset(target_sampleset, embedding, source_bqm, chain_break_method=None, chain_break_fraction=False): """Unembed the samples set. Construct a sample set for the source binary quadratic model (BQM) by unembedding the given samples from the target BQM. Args: target_sampleset (:obj:`dimod.SampleSet`): SampleSet from the target BQM. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source variable and t is a target variable. source_bqm (:obj:`dimod.BinaryQuadraticModel`): Source binary quadratic model. chain_break_method (function, optional): Method used to resolve chain breaks. See :mod:`dwave.embedding.chain_breaks`. chain_break_fraction (bool, optional, default=False): If True, a 'chain_break_fraction' field is added to the unembedded samples which report what fraction of the chains were broken before unembedding. Returns: :obj:`.SampleSet`: Examples: >>> import dimod ... >>> # say we have a bqm on a triangle and an embedding >>> J = {('a', 'b'): -1, ('b', 'c'): -1, ('a', 'c'): -1} >>> bqm = dimod.BinaryQuadraticModel.from_ising({}, J) >>> embedding = {'a': [0, 1], 'b': [2], 'c': [3]} ... >>> # and some samples from the embedding >>> samples = [{0: -1, 1: -1, 2: -1, 3: -1}, # [0, 1] is unbroken {0: -1, 1: +1, 2: +1, 3: +1}] # [0, 1] is broken >>> energies = [-3, 1] >>> embedded = dimod.SampleSet.from_samples(samples, dimod.SPIN, energies) ... >>> # unembed >>> samples = dwave.embedding.unembed_sampleset(embedded, embedding, bqm) >>> samples.record.sample # doctest: +SKIP array([[-1, -1, -1], [ 1, 1, 1]], dtype=int8) """ if chain_break_method is None: chain_break_method = majority_vote variables = list(source_bqm) try: chains = [embedding[v] for v in variables] except KeyError: raise ValueError("given bqm does not match the embedding") chain_idxs = [[target_sampleset.variables.index[v] for v in chain] for chain in chains] record = target_sampleset.record unembedded, idxs = chain_break_method(record.sample, chain_idxs) # dev note: this is a bug in dimod that empty unembedded is not handled, # in the future this try-except can be removed try: energies = source_bqm.energies((unembedded, variables)) except ValueError: datatypes = [('sample', np.dtype(np.int8), (len(variables),)), ('energy', np.float)] datatypes.extend((name, record[name].dtype, record[name].shape[1:]) for name in record.dtype.names if name not in {'sample', 'energy'}) if chain_break_fraction: datatypes.append(('chain_break_fraction', np.float64)) # there are no samples so everything is empty data = np.rec.array(np.empty(0, dtype=datatypes)) return dimod.SampleSet(data, variables, target_sampleset.info.copy(), target_sampleset.vartype) reserved = {'sample', 'energy'} vectors = {name: record[name][idxs] for name in record.dtype.names if name not in reserved} if chain_break_fraction: vectors['chain_break_fraction'] = broken_chains(record.sample, chain_idxs).mean(axis=1)[idxs] return dimod.SampleSet.from_samples((unembedded, variables), target_sampleset.vartype, energy=energies, info=target_sampleset.info.copy(), **vectors)
python
def unembed_sampleset(target_sampleset, embedding, source_bqm, chain_break_method=None, chain_break_fraction=False): if chain_break_method is None: chain_break_method = majority_vote variables = list(source_bqm) try: chains = [embedding[v] for v in variables] except KeyError: raise ValueError("given bqm does not match the embedding") chain_idxs = [[target_sampleset.variables.index[v] for v in chain] for chain in chains] record = target_sampleset.record unembedded, idxs = chain_break_method(record.sample, chain_idxs) # dev note: this is a bug in dimod that empty unembedded is not handled, # in the future this try-except can be removed try: energies = source_bqm.energies((unembedded, variables)) except ValueError: datatypes = [('sample', np.dtype(np.int8), (len(variables),)), ('energy', np.float)] datatypes.extend((name, record[name].dtype, record[name].shape[1:]) for name in record.dtype.names if name not in {'sample', 'energy'}) if chain_break_fraction: datatypes.append(('chain_break_fraction', np.float64)) # there are no samples so everything is empty data = np.rec.array(np.empty(0, dtype=datatypes)) return dimod.SampleSet(data, variables, target_sampleset.info.copy(), target_sampleset.vartype) reserved = {'sample', 'energy'} vectors = {name: record[name][idxs] for name in record.dtype.names if name not in reserved} if chain_break_fraction: vectors['chain_break_fraction'] = broken_chains(record.sample, chain_idxs).mean(axis=1)[idxs] return dimod.SampleSet.from_samples((unembedded, variables), target_sampleset.vartype, energy=energies, info=target_sampleset.info.copy(), **vectors)
[ "def", "unembed_sampleset", "(", "target_sampleset", ",", "embedding", ",", "source_bqm", ",", "chain_break_method", "=", "None", ",", "chain_break_fraction", "=", "False", ")", ":", "if", "chain_break_method", "is", "None", ":", "chain_break_method", "=", "majority...
Unembed the samples set. Construct a sample set for the source binary quadratic model (BQM) by unembedding the given samples from the target BQM. Args: target_sampleset (:obj:`dimod.SampleSet`): SampleSet from the target BQM. embedding (dict): Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...}, where s is a source variable and t is a target variable. source_bqm (:obj:`dimod.BinaryQuadraticModel`): Source binary quadratic model. chain_break_method (function, optional): Method used to resolve chain breaks. See :mod:`dwave.embedding.chain_breaks`. chain_break_fraction (bool, optional, default=False): If True, a 'chain_break_fraction' field is added to the unembedded samples which report what fraction of the chains were broken before unembedding. Returns: :obj:`.SampleSet`: Examples: >>> import dimod ... >>> # say we have a bqm on a triangle and an embedding >>> J = {('a', 'b'): -1, ('b', 'c'): -1, ('a', 'c'): -1} >>> bqm = dimod.BinaryQuadraticModel.from_ising({}, J) >>> embedding = {'a': [0, 1], 'b': [2], 'c': [3]} ... >>> # and some samples from the embedding >>> samples = [{0: -1, 1: -1, 2: -1, 3: -1}, # [0, 1] is unbroken {0: -1, 1: +1, 2: +1, 3: +1}] # [0, 1] is broken >>> energies = [-3, 1] >>> embedded = dimod.SampleSet.from_samples(samples, dimod.SPIN, energies) ... >>> # unembed >>> samples = dwave.embedding.unembed_sampleset(embedded, embedding, bqm) >>> samples.record.sample # doctest: +SKIP array([[-1, -1, -1], [ 1, 1, 1]], dtype=int8)
[ "Unembed", "the", "samples", "set", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/transforms.py#L346-L441
19,635
dwavesystems/dwave-system
dwave/system/composites/embedding.py
LazyFixedEmbeddingComposite.sample
def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters): """Sample the binary quadratic model. Note: At the initial sample(..) call, it will find a suitable embedding and initialize the remaining attributes before sampling the bqm. All following sample(..) calls will reuse that initial embedding. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. chain_strength (float, optional, default=1.0): Magnitude of the quadratic bias (in SPIN-space) applied between variables to create chains. Note that the energy penalty of chain breaks is 2 * `chain_strength`. chain_break_fraction (bool, optional, default=True): If True, a ‘chain_break_fraction’ field is added to the unembedded response which report what fraction of the chains were broken before unembedding. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :class:`dimod.SampleSet` """ if self.embedding is None: # Find embedding child = self.child # Solve the problem on the child system __, target_edgelist, target_adjacency = child.structure source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear] # Add self-loops for single variables embedding = minorminer.find_embedding(source_edgelist, target_edgelist) # Initialize properties that need embedding super(LazyFixedEmbeddingComposite, self)._set_graph_related_init(embedding=embedding) return super(LazyFixedEmbeddingComposite, self).sample(bqm, chain_strength=chain_strength, chain_break_fraction=chain_break_fraction, **parameters)
python
def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters): if self.embedding is None: # Find embedding child = self.child # Solve the problem on the child system __, target_edgelist, target_adjacency = child.structure source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear] # Add self-loops for single variables embedding = minorminer.find_embedding(source_edgelist, target_edgelist) # Initialize properties that need embedding super(LazyFixedEmbeddingComposite, self)._set_graph_related_init(embedding=embedding) return super(LazyFixedEmbeddingComposite, self).sample(bqm, chain_strength=chain_strength, chain_break_fraction=chain_break_fraction, **parameters)
[ "def", "sample", "(", "self", ",", "bqm", ",", "chain_strength", "=", "1.0", ",", "chain_break_fraction", "=", "True", ",", "*", "*", "parameters", ")", ":", "if", "self", ".", "embedding", "is", "None", ":", "# Find embedding", "child", "=", "self", "."...
Sample the binary quadratic model. Note: At the initial sample(..) call, it will find a suitable embedding and initialize the remaining attributes before sampling the bqm. All following sample(..) calls will reuse that initial embedding. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. chain_strength (float, optional, default=1.0): Magnitude of the quadratic bias (in SPIN-space) applied between variables to create chains. Note that the energy penalty of chain breaks is 2 * `chain_strength`. chain_break_fraction (bool, optional, default=True): If True, a ‘chain_break_fraction’ field is added to the unembedded response which report what fraction of the chains were broken before unembedding. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :class:`dimod.SampleSet`
[ "Sample", "the", "binary", "quadratic", "model", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/composites/embedding.py#L461-L495
19,636
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
_accumulate_random
def _accumulate_random(count, found, oldthing, newthing): """This performs on-line random selection. We have a stream of objects o_1,c_1; o_2,c_2; ... where there are c_i equivalent objects like o_1. We'd like to pick a random object o uniformly at random from the list [o_1]*c_1 + [o_2]*c_2 + ... (actually, this algorithm allows arbitrary positive weights, not necessarily integers) without spending the time&space to actually create that list. Luckily, the following works: thing = None c_tot for o_n, c_n in things: c_tot += c_n if randint(1,c_tot) <= c_n: thing = o_n This function is written in an accumulator format, so it can be used one call at a time: EXAMPLE: > thing = None > count = 0 > for i in range(10): > c = 10-i > count, thing = accumulate_random(count,c,thing,i) INPUTS: count: integer, sum of weights found before newthing found: integer, weight for newthing oldthing: previously selected object (will never be selected if count == 0) newthing: incoming object OUTPUT: (newcount, pick): newcount is count+found, pick is the newly selected object. """ if randint(1, count + found) <= found: return count + found, newthing else: return count + found, oldthing
python
def _accumulate_random(count, found, oldthing, newthing): if randint(1, count + found) <= found: return count + found, newthing else: return count + found, oldthing
[ "def", "_accumulate_random", "(", "count", ",", "found", ",", "oldthing", ",", "newthing", ")", ":", "if", "randint", "(", "1", ",", "count", "+", "found", ")", "<=", "found", ":", "return", "count", "+", "found", ",", "newthing", "else", ":", "return"...
This performs on-line random selection. We have a stream of objects o_1,c_1; o_2,c_2; ... where there are c_i equivalent objects like o_1. We'd like to pick a random object o uniformly at random from the list [o_1]*c_1 + [o_2]*c_2 + ... (actually, this algorithm allows arbitrary positive weights, not necessarily integers) without spending the time&space to actually create that list. Luckily, the following works: thing = None c_tot for o_n, c_n in things: c_tot += c_n if randint(1,c_tot) <= c_n: thing = o_n This function is written in an accumulator format, so it can be used one call at a time: EXAMPLE: > thing = None > count = 0 > for i in range(10): > c = 10-i > count, thing = accumulate_random(count,c,thing,i) INPUTS: count: integer, sum of weights found before newthing found: integer, weight for newthing oldthing: previously selected object (will never be selected if count == 0) newthing: incoming object OUTPUT: (newcount, pick): newcount is count+found, pick is the newly selected object.
[ "This", "performs", "on", "-", "line", "random", "selection", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L60-L108
19,637
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
_bulk_to_linear
def _bulk_to_linear(M, N, L, qubits): "Converts a list of chimera coordinates to linear indices." return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits]
python
def _bulk_to_linear(M, N, L, qubits): "Converts a list of chimera coordinates to linear indices." return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits]
[ "def", "_bulk_to_linear", "(", "M", ",", "N", ",", "L", ",", "qubits", ")", ":", "return", "[", "2", "*", "L", "*", "N", "*", "x", "+", "2", "*", "L", "*", "y", "+", "L", "*", "u", "+", "k", "for", "x", ",", "y", ",", "u", ",", "k", "...
Converts a list of chimera coordinates to linear indices.
[ "Converts", "a", "list", "of", "chimera", "coordinates", "to", "linear", "indices", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1161-L1163
19,638
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
_to_linear
def _to_linear(M, N, L, q): "Converts a qubit in chimera coordinates to its linear index." (x, y, u, k) = q return 2 * L * N * x + 2 * L * y + L * u + k
python
def _to_linear(M, N, L, q): "Converts a qubit in chimera coordinates to its linear index." (x, y, u, k) = q return 2 * L * N * x + 2 * L * y + L * u + k
[ "def", "_to_linear", "(", "M", ",", "N", ",", "L", ",", "q", ")", ":", "(", "x", ",", "y", ",", "u", ",", "k", ")", "=", "q", "return", "2", "*", "L", "*", "N", "*", "x", "+", "2", "*", "L", "*", "y", "+", "L", "*", "u", "+", "k" ]
Converts a qubit in chimera coordinates to its linear index.
[ "Converts", "a", "qubit", "in", "chimera", "coordinates", "to", "its", "linear", "index", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1166-L1169
19,639
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
_bulk_to_chimera
def _bulk_to_chimera(M, N, L, qubits): "Converts a list of linear indices to chimera coordinates." return [(q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) for q in qubits]
python
def _bulk_to_chimera(M, N, L, qubits): "Converts a list of linear indices to chimera coordinates." return [(q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) for q in qubits]
[ "def", "_bulk_to_chimera", "(", "M", ",", "N", ",", "L", ",", "qubits", ")", ":", "return", "[", "(", "q", "//", "N", "//", "L", "//", "2", ",", "(", "q", "//", "L", "//", "2", ")", "%", "N", ",", "(", "q", "//", "L", ")", "%", "2", ","...
Converts a list of linear indices to chimera coordinates.
[ "Converts", "a", "list", "of", "linear", "indices", "to", "chimera", "coordinates", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1172-L1174
19,640
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
_to_chimera
def _to_chimera(M, N, L, q): "Converts a qubit's linear index to chimera coordinates." return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L)
python
def _to_chimera(M, N, L, q): "Converts a qubit's linear index to chimera coordinates." return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L)
[ "def", "_to_chimera", "(", "M", ",", "N", ",", "L", ",", "q", ")", ":", "return", "(", "q", "//", "N", "//", "L", "//", "2", ",", "(", "q", "//", "L", "//", "2", ")", "%", "N", ",", "(", "q", "//", "L", ")", "%", "2", ",", "q", "%", ...
Converts a qubit's linear index to chimera coordinates.
[ "Converts", "a", "qubit", "s", "linear", "index", "to", "chimera", "coordinates", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1177-L1179
19,641
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
eden_processor._compute_vline_scores
def _compute_vline_scores(self): """Does the hard work to prepare ``vline_score``. """ M, N, L = self.M, self.N, self.L vline_score = {} for x in range(M): laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)] for y in range(N): block = [0] * (y + 1) for k in range(L): if (x, y, 1, k) not in self: laststart[k] = None elif laststart[k] is None: laststart[k] = y block[y] += 1 elif y and (x, y, 1, k) not in self[x, y - 1, 1, k]: laststart[k] = y else: for y1 in range(laststart[k], y + 1): block[y1] += 1 for y1 in range(y + 1): vline_score[x, y1, y] = block[y1] self._vline_score = vline_score
python
def _compute_vline_scores(self): M, N, L = self.M, self.N, self.L vline_score = {} for x in range(M): laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)] for y in range(N): block = [0] * (y + 1) for k in range(L): if (x, y, 1, k) not in self: laststart[k] = None elif laststart[k] is None: laststart[k] = y block[y] += 1 elif y and (x, y, 1, k) not in self[x, y - 1, 1, k]: laststart[k] = y else: for y1 in range(laststart[k], y + 1): block[y1] += 1 for y1 in range(y + 1): vline_score[x, y1, y] = block[y1] self._vline_score = vline_score
[ "def", "_compute_vline_scores", "(", "self", ")", ":", "M", ",", "N", ",", "L", "=", "self", ".", "M", ",", "self", ".", "N", ",", "self", ".", "L", "vline_score", "=", "{", "}", "for", "x", "in", "range", "(", "M", ")", ":", "laststart", "=", ...
Does the hard work to prepare ``vline_score``.
[ "Does", "the", "hard", "work", "to", "prepare", "vline_score", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L188-L210
19,642
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
eden_processor._compute_hline_scores
def _compute_hline_scores(self): """Does the hard work to prepare ``hline_score``. """ M, N, L = self.M, self.N, self.L hline_score = {} for y in range(N): laststart = [0 if (0, y, 0, k) in self else None for k in range(L)] for x in range(M): block = [0] * (x + 1) for k in range(L): if (x, y, 0, k) not in self: laststart[k] = None elif laststart[k] is None: laststart[k] = x block[x] += 1 elif x and (x, y, 0, k) not in self[x - 1, y, 0, k]: laststart[k] = x else: for x1 in range(laststart[k], x + 1): block[x1] += 1 for x1 in range(x + 1): hline_score[y, x1, x] = block[x1] self._hline_score = hline_score
python
def _compute_hline_scores(self): M, N, L = self.M, self.N, self.L hline_score = {} for y in range(N): laststart = [0 if (0, y, 0, k) in self else None for k in range(L)] for x in range(M): block = [0] * (x + 1) for k in range(L): if (x, y, 0, k) not in self: laststart[k] = None elif laststart[k] is None: laststart[k] = x block[x] += 1 elif x and (x, y, 0, k) not in self[x - 1, y, 0, k]: laststart[k] = x else: for x1 in range(laststart[k], x + 1): block[x1] += 1 for x1 in range(x + 1): hline_score[y, x1, x] = block[x1] self._hline_score = hline_score
[ "def", "_compute_hline_scores", "(", "self", ")", ":", "M", ",", "N", ",", "L", "=", "self", ".", "M", ",", "self", ".", "N", ",", "self", ".", "L", "hline_score", "=", "{", "}", "for", "y", "in", "range", "(", "N", ")", ":", "laststart", "=", ...
Does the hard work to prepare ``hline_score``.
[ "Does", "the", "hard", "work", "to", "prepare", "hline_score", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L212-L234
19,643
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
eden_processor.biclique
def biclique(self, xmin, xmax, ymin, ymax): """Compute a maximum-sized complete bipartite graph contained in the rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of qubits is either a vertical line or a horizontal line. INPUTS: xmin,xmax,ymin,ymax: integers defining the bounds of a rectangle where we look for unbroken chains. These ranges include both endpoints. OUTPUT: (A_side, B_side): a tuple of two lists containing lists of qubits. the lists found in ``A_side`` and ``B_side`` are chains of qubits. These lists of qubits are arranged so that >>> [zip(chain,chain[1:]) for chain in A_side] and >>> [zip(chain,chain[1:]) for chain in B_side] are lists of valid couplers. """ Aside = sum((self.maximum_hline_bundle(y, xmin, xmax) for y in range(ymin, ymax + 1)), []) Bside = sum((self.maximum_vline_bundle(x, ymin, ymax) for x in range(xmin, xmax + 1)), []) return Aside, Bside
python
def biclique(self, xmin, xmax, ymin, ymax): Aside = sum((self.maximum_hline_bundle(y, xmin, xmax) for y in range(ymin, ymax + 1)), []) Bside = sum((self.maximum_vline_bundle(x, ymin, ymax) for x in range(xmin, xmax + 1)), []) return Aside, Bside
[ "def", "biclique", "(", "self", ",", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ")", ":", "Aside", "=", "sum", "(", "(", "self", ".", "maximum_hline_bundle", "(", "y", ",", "xmin", ",", "xmax", ")", "for", "y", "in", "range", "(", "ymin", ","...
Compute a maximum-sized complete bipartite graph contained in the rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of qubits is either a vertical line or a horizontal line. INPUTS: xmin,xmax,ymin,ymax: integers defining the bounds of a rectangle where we look for unbroken chains. These ranges include both endpoints. OUTPUT: (A_side, B_side): a tuple of two lists containing lists of qubits. the lists found in ``A_side`` and ``B_side`` are chains of qubits. These lists of qubits are arranged so that >>> [zip(chain,chain[1:]) for chain in A_side] and >>> [zip(chain,chain[1:]) for chain in B_side] are lists of valid couplers.
[ "Compute", "a", "maximum", "-", "sized", "complete", "bipartite", "graph", "contained", "in", "the", "rectangle", "defined", "by", "xmin", "xmax", "ymin", "ymax", "where", "each", "chain", "of", "qubits", "is", "either", "a", "vertical", "line", "or", "a", ...
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L291-L319
19,644
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
eden_processor._contains_line
def _contains_line(self, line): """Test if a chain of qubits is completely contained in ``self``. In particular, test if all qubits are present and the couplers connecting those qubits are also connected. NOTE: this function assumes that ``line`` is a list or tuple of qubits which satisfies the precondition that ``(line[i],line[i+1])`` is supposed to be a coupler for all ``i``. INPUTS: line: a list of qubits satisfying the above precondition OUTPUT: boolean """ return all(v in self for v in line) and all(u in self[v] for u, v in zip(line, line[1::]))
python
def _contains_line(self, line): return all(v in self for v in line) and all(u in self[v] for u, v in zip(line, line[1::]))
[ "def", "_contains_line", "(", "self", ",", "line", ")", ":", "return", "all", "(", "v", "in", "self", "for", "v", "in", "line", ")", "and", "all", "(", "u", "in", "self", "[", "v", "]", "for", "u", ",", "v", "in", "zip", "(", "line", ",", "li...
Test if a chain of qubits is completely contained in ``self``. In particular, test if all qubits are present and the couplers connecting those qubits are also connected. NOTE: this function assumes that ``line`` is a list or tuple of qubits which satisfies the precondition that ``(line[i],line[i+1])`` is supposed to be a coupler for all ``i``. INPUTS: line: a list of qubits satisfying the above precondition OUTPUT: boolean
[ "Test", "if", "a", "chain", "of", "qubits", "is", "completely", "contained", "in", "self", ".", "In", "particular", "test", "if", "all", "qubits", "are", "present", "and", "the", "couplers", "connecting", "those", "qubits", "are", "also", "connected", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L322-L337
19,645
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
eden_processor.maximum_ell_bundle
def maximum_ell_bundle(self, ell): """Return a maximum ell bundle in the rectangle bounded by :math:`\{x0,x1\} \\times \{y0,y1\}` with vertical component :math:`(x0,y0) ... (x0,y1) = {x0} \\times \{y0,...,y1\}` and horizontal component :math:`(x0,y0) ... (x1,y0) = \{x0,...,x1\} \\times \{y0\}`. Note that we don't require :math:`x0 \leq x1` or :math:`y0 \leq y1`. We go through some shenanigans so that the qubits we return are all in a path. A nice side-effect of this is that >>> chains = maximum_ell_bundle(...) >>> edges = [zip(path,path[:-1]) for path in chains] where ``edges`` will be a list of lists of chain edges. INPUTS:: ell: a tuple of 4 integers defining the ell, ``(x0, x1, y0, y1)`` OUTPUT:: chains: list of lists of qubits Note: this function only to be called to construct a native clique embedding *after* the block embedding has been constructed. Using this to evaluate the goodness of an ell block will be slow. """ (x0, x1, y0, y1) = ell hlines = self.maximum_hline_bundle(y0, x0, x1) vlines = self.maximum_vline_bundle(x0, y0, y1) if self.random_bundles: shuffle(hlines) shuffle(vlines) return [v + h for h, v in zip(hlines, vlines)]
python
def maximum_ell_bundle(self, ell): (x0, x1, y0, y1) = ell hlines = self.maximum_hline_bundle(y0, x0, x1) vlines = self.maximum_vline_bundle(x0, y0, y1) if self.random_bundles: shuffle(hlines) shuffle(vlines) return [v + h for h, v in zip(hlines, vlines)]
[ "def", "maximum_ell_bundle", "(", "self", ",", "ell", ")", ":", "(", "x0", ",", "x1", ",", "y0", ",", "y1", ")", "=", "ell", "hlines", "=", "self", ".", "maximum_hline_bundle", "(", "y0", ",", "x0", ",", "x1", ")", "vlines", "=", "self", ".", "ma...
Return a maximum ell bundle in the rectangle bounded by :math:`\{x0,x1\} \\times \{y0,y1\}` with vertical component :math:`(x0,y0) ... (x0,y1) = {x0} \\times \{y0,...,y1\}` and horizontal component :math:`(x0,y0) ... (x1,y0) = \{x0,...,x1\} \\times \{y0\}`. Note that we don't require :math:`x0 \leq x1` or :math:`y0 \leq y1`. We go through some shenanigans so that the qubits we return are all in a path. A nice side-effect of this is that >>> chains = maximum_ell_bundle(...) >>> edges = [zip(path,path[:-1]) for path in chains] where ``edges`` will be a list of lists of chain edges. INPUTS:: ell: a tuple of 4 integers defining the ell, ``(x0, x1, y0, y1)`` OUTPUT:: chains: list of lists of qubits Note: this function only to be called to construct a native clique embedding *after* the block embedding has been constructed. Using this to evaluate the goodness of an ell block will be slow.
[ "Return", "a", "maximum", "ell", "bundle", "in", "the", "rectangle", "bounded", "by" ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L368-L409
19,646
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
eden_processor.nativeCliqueEmbed
def nativeCliqueEmbed(self, width): """Compute a maximum-sized native clique embedding in an induced subgraph of chimera with all chainlengths ``width+1``. INPUTS: width: width of the squares to search, also `chainlength`-1 OUTPUT: score: the score for the returned clique (just ``len(clique)`` in the class :class:`eden_processor`; may differ in subclasses) clique: a list containing lists of qubits, each associated to a chain. These lists of qubits are carefully arranged so that >>> [zip(chain,chain[1:]) for chain in clique] is a list of valid couplers. """ maxCWR = {} M, N = self.M, self.N maxscore = None count = 0 key = None for w in range(width + 2): h = width - w - 2 for ymin in range(N - h): ymax = ymin + h for xmin in range(M - w): xmax = xmin + w R = (xmin, xmax, ymin, ymax) score, best = self.maxCliqueWithRectangle(R, maxCWR) maxCWR[R] = best if maxscore is None or (score is not None and maxscore < score): maxscore = score key = None # this gets overwritten immediately count = 0 # this gets overwritten immediately if maxscore == score: count, key = _accumulate_random(count, best[3], key, R) clique = [] while key in maxCWR: score, ell, key, num = maxCWR[key] if ell is not None: meb = self.maximum_ell_bundle(ell) clique.extend(meb) return maxscore, clique
python
def nativeCliqueEmbed(self, width): maxCWR = {} M, N = self.M, self.N maxscore = None count = 0 key = None for w in range(width + 2): h = width - w - 2 for ymin in range(N - h): ymax = ymin + h for xmin in range(M - w): xmax = xmin + w R = (xmin, xmax, ymin, ymax) score, best = self.maxCliqueWithRectangle(R, maxCWR) maxCWR[R] = best if maxscore is None or (score is not None and maxscore < score): maxscore = score key = None # this gets overwritten immediately count = 0 # this gets overwritten immediately if maxscore == score: count, key = _accumulate_random(count, best[3], key, R) clique = [] while key in maxCWR: score, ell, key, num = maxCWR[key] if ell is not None: meb = self.maximum_ell_bundle(ell) clique.extend(meb) return maxscore, clique
[ "def", "nativeCliqueEmbed", "(", "self", ",", "width", ")", ":", "maxCWR", "=", "{", "}", "M", ",", "N", "=", "self", ".", "M", ",", "self", ".", "N", "maxscore", "=", "None", "count", "=", "0", "key", "=", "None", "for", "w", "in", "range", "(...
Compute a maximum-sized native clique embedding in an induced subgraph of chimera with all chainlengths ``width+1``. INPUTS: width: width of the squares to search, also `chainlength`-1 OUTPUT: score: the score for the returned clique (just ``len(clique)`` in the class :class:`eden_processor`; may differ in subclasses) clique: a list containing lists of qubits, each associated to a chain. These lists of qubits are carefully arranged so that >>> [zip(chain,chain[1:]) for chain in clique] is a list of valid couplers.
[ "Compute", "a", "maximum", "-", "sized", "native", "clique", "embedding", "in", "an", "induced", "subgraph", "of", "chimera", "with", "all", "chainlengths", "width", "+", "1", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L496-L544
19,647
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
processor._compute_all_deletions
def _compute_all_deletions(self): """Returns all minimal edge covers of the set of evil edges. """ minimum_evil = [] for disabled_qubits in map(set, product(*self._evil)): newmin = [] for s in minimum_evil: if s < disabled_qubits: break elif disabled_qubits < s: continue newmin.append(s) else: minimum_evil = newmin + [disabled_qubits] return minimum_evil
python
def _compute_all_deletions(self): minimum_evil = [] for disabled_qubits in map(set, product(*self._evil)): newmin = [] for s in minimum_evil: if s < disabled_qubits: break elif disabled_qubits < s: continue newmin.append(s) else: minimum_evil = newmin + [disabled_qubits] return minimum_evil
[ "def", "_compute_all_deletions", "(", "self", ")", ":", "minimum_evil", "=", "[", "]", "for", "disabled_qubits", "in", "map", "(", "set", ",", "product", "(", "*", "self", ".", "_evil", ")", ")", ":", "newmin", "=", "[", "]", "for", "s", "in", "minim...
Returns all minimal edge covers of the set of evil edges.
[ "Returns", "all", "minimal", "edge", "covers", "of", "the", "set", "of", "evil", "edges", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L810-L824
19,648
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
processor._compute_deletions
def _compute_deletions(self): """If there are fewer than self._proc_limit possible deletion sets, compute all subprocessors obtained by deleting a minimal subset of qubits. """ M, N, L, edgelist = self.M, self.N, self.L, self._edgelist if 2**len(self._evil) <= self._proc_limit: deletions = self._compute_all_deletions() self._processors = [self._subprocessor(d) for d in deletions] else: self._processors = None
python
def _compute_deletions(self): M, N, L, edgelist = self.M, self.N, self.L, self._edgelist if 2**len(self._evil) <= self._proc_limit: deletions = self._compute_all_deletions() self._processors = [self._subprocessor(d) for d in deletions] else: self._processors = None
[ "def", "_compute_deletions", "(", "self", ")", ":", "M", ",", "N", ",", "L", ",", "edgelist", "=", "self", ".", "M", ",", "self", ".", "N", ",", "self", ".", "L", ",", "self", ".", "_edgelist", "if", "2", "**", "len", "(", "self", ".", "_evil",...
If there are fewer than self._proc_limit possible deletion sets, compute all subprocessors obtained by deleting a minimal subset of qubits.
[ "If", "there", "are", "fewer", "than", "self", ".", "_proc_limit", "possible", "deletion", "sets", "compute", "all", "subprocessors", "obtained", "by", "deleting", "a", "minimal", "subset", "of", "qubits", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L836-L846
19,649
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
processor._random_subprocessor
def _random_subprocessor(self): """Creates a random subprocessor where there is a coupler between every pair of working qubits on opposite sides of the same cell. This is guaranteed to be minimal in that adding a qubit back in will reintroduce a bad coupler, but not to have minimum size. OUTPUT: an :class:`eden_processor` instance """ deletion = set() for e in self._evil: if e[0] in deletion or e[1] in deletion: continue deletion.add(choice(e)) return self._subprocessor(deletion)
python
def _random_subprocessor(self): deletion = set() for e in self._evil: if e[0] in deletion or e[1] in deletion: continue deletion.add(choice(e)) return self._subprocessor(deletion)
[ "def", "_random_subprocessor", "(", "self", ")", ":", "deletion", "=", "set", "(", ")", "for", "e", "in", "self", ".", "_evil", ":", "if", "e", "[", "0", "]", "in", "deletion", "or", "e", "[", "1", "]", "in", "deletion", ":", "continue", "deletion"...
Creates a random subprocessor where there is a coupler between every pair of working qubits on opposite sides of the same cell. This is guaranteed to be minimal in that adding a qubit back in will reintroduce a bad coupler, but not to have minimum size. OUTPUT: an :class:`eden_processor` instance
[ "Creates", "a", "random", "subprocessor", "where", "there", "is", "a", "coupler", "between", "every", "pair", "of", "working", "qubits", "on", "opposite", "sides", "of", "the", "same", "cell", ".", "This", "is", "guaranteed", "to", "be", "minimal", "in", "...
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L848-L862
19,650
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
processor._objective_bestscore
def _objective_bestscore(self, old, new): """An objective function that returns True if new has a better score than old, and ``False`` otherwise. INPUTS: old (tuple): a tuple (score, embedding) new (tuple): a tuple (score, embedding) """ (oldscore, oldthing) = old (newscore, newthing) = new if oldscore is None: return True if newscore is None: return False return oldscore < newscore
python
def _objective_bestscore(self, old, new): (oldscore, oldthing) = old (newscore, newthing) = new if oldscore is None: return True if newscore is None: return False return oldscore < newscore
[ "def", "_objective_bestscore", "(", "self", ",", "old", ",", "new", ")", ":", "(", "oldscore", ",", "oldthing", ")", "=", "old", "(", "newscore", ",", "newthing", ")", "=", "new", "if", "oldscore", "is", "None", ":", "return", "True", "if", "newscore",...
An objective function that returns True if new has a better score than old, and ``False`` otherwise. INPUTS: old (tuple): a tuple (score, embedding) new (tuple): a tuple (score, embedding)
[ "An", "objective", "function", "that", "returns", "True", "if", "new", "has", "a", "better", "score", "than", "old", "and", "False", "otherwise", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L913-L929
19,651
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
processor.nativeCliqueEmbed
def nativeCliqueEmbed(self, width): """Compute a maximum-sized native clique embedding in an induced subgraph of chimera with chainsize ``width+1``. If possible, returns a uniform choice among all largest cliques. INPUTS: width: width of the squares to search, also `chainlength-1` OUTPUT: clique: a list containing lists of qubits, each associated to a chain. These lists of qubits are carefully arranged so that >>> [zip(chain,chain[1:]) for chain in clique] is a list of valid couplers. Note: this fails to return a uniform choice if there are broken intra-cell couplers between working qubits. (the choice is uniform on a particular subprocessor) """ def f(x): return x.nativeCliqueEmbed(width) objective = self._objective_bestscore return self._translate(self._map_to_processors(f, objective))
python
def nativeCliqueEmbed(self, width): def f(x): return x.nativeCliqueEmbed(width) objective = self._objective_bestscore return self._translate(self._map_to_processors(f, objective))
[ "def", "nativeCliqueEmbed", "(", "self", ",", "width", ")", ":", "def", "f", "(", "x", ")", ":", "return", "x", ".", "nativeCliqueEmbed", "(", "width", ")", "objective", "=", "self", ".", "_objective_bestscore", "return", "self", ".", "_translate", "(", ...
Compute a maximum-sized native clique embedding in an induced subgraph of chimera with chainsize ``width+1``. If possible, returns a uniform choice among all largest cliques. INPUTS: width: width of the squares to search, also `chainlength-1` OUTPUT: clique: a list containing lists of qubits, each associated to a chain. These lists of qubits are carefully arranged so that >>> [zip(chain,chain[1:]) for chain in clique] is a list of valid couplers. Note: this fails to return a uniform choice if there are broken intra-cell couplers between working qubits. (the choice is uniform on a particular subprocessor)
[ "Compute", "a", "maximum", "-", "sized", "native", "clique", "embedding", "in", "an", "induced", "subgraph", "of", "chimera", "with", "chainsize", "width", "+", "1", ".", "If", "possible", "returns", "a", "uniform", "choice", "among", "all", "largest", "cliq...
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1038-L1062
19,652
dwavesystems/dwave-system
dwave/embedding/polynomialembedder.py
processor._translate
def _translate(self, embedding): "Translates an embedding back to linear coordinates if necessary." if embedding is None: return None if not self._linear: return embedding return [_bulk_to_linear(self.M, self.N, self.L, chain) for chain in embedding]
python
def _translate(self, embedding): "Translates an embedding back to linear coordinates if necessary." if embedding is None: return None if not self._linear: return embedding return [_bulk_to_linear(self.M, self.N, self.L, chain) for chain in embedding]
[ "def", "_translate", "(", "self", ",", "embedding", ")", ":", "if", "embedding", "is", "None", ":", "return", "None", "if", "not", "self", ".", "_linear", ":", "return", "embedding", "return", "[", "_bulk_to_linear", "(", "self", ".", "M", ",", "self", ...
Translates an embedding back to linear coordinates if necessary.
[ "Translates", "an", "embedding", "back", "to", "linear", "coordinates", "if", "necessary", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/polynomialembedder.py#L1152-L1158
19,653
dwavesystems/dwave-system
dwave/system/composites/virtual_graph.py
_validate_chain_strength
def _validate_chain_strength(sampler, chain_strength): """Validate the provided chain strength, checking J-ranges of the sampler's children. Args: chain_strength (float) The provided chain strength. Use None to use J-range. Returns (float): A valid chain strength, either provided or based on available J-range. Positive finite float. """ properties = sampler.properties if 'extended_j_range' in properties: max_chain_strength = - min(properties['extended_j_range']) elif 'j_range' in properties: max_chain_strength = - min(properties['j_range']) else: raise ValueError("input sampler should have 'j_range' and/or 'extended_j_range' property.") if chain_strength is None: chain_strength = max_chain_strength elif chain_strength > max_chain_strength: raise ValueError("Provided chain strength exceedds the allowed range.") return chain_strength
python
def _validate_chain_strength(sampler, chain_strength): properties = sampler.properties if 'extended_j_range' in properties: max_chain_strength = - min(properties['extended_j_range']) elif 'j_range' in properties: max_chain_strength = - min(properties['j_range']) else: raise ValueError("input sampler should have 'j_range' and/or 'extended_j_range' property.") if chain_strength is None: chain_strength = max_chain_strength elif chain_strength > max_chain_strength: raise ValueError("Provided chain strength exceedds the allowed range.") return chain_strength
[ "def", "_validate_chain_strength", "(", "sampler", ",", "chain_strength", ")", ":", "properties", "=", "sampler", ".", "properties", "if", "'extended_j_range'", "in", "properties", ":", "max_chain_strength", "=", "-", "min", "(", "properties", "[", "'extended_j_rang...
Validate the provided chain strength, checking J-ranges of the sampler's children. Args: chain_strength (float) The provided chain strength. Use None to use J-range. Returns (float): A valid chain strength, either provided or based on available J-range. Positive finite float.
[ "Validate", "the", "provided", "chain", "strength", "checking", "J", "-", "ranges", "of", "the", "sampler", "s", "children", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/composites/virtual_graph.py#L368-L392
19,654
dwavesystems/dwave-system
dwave/system/composites/virtual_graph.py
VirtualGraphComposite.sample
def sample(self, bqm, apply_flux_bias_offsets=True, **kwargs): """Sample from the given Ising model. Args: h (list/dict): Linear biases of the Ising model. If a list, the list's indices are used as variable labels. J (dict of (int, int):float): Quadratic biases of the Ising model. apply_flux_bias_offsets (bool, optional): If True, use the calculated flux_bias offsets (if available). **kwargs: Optional keyword arguments for the sampling method, specified per solver. Examples: This example uses :class:`.VirtualGraphComposite` to instantiate a composed sampler that submits an Ising problem to a D-Wave solver selected by the user's default :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`. The problem represents a logical NOT gate using penalty function :math:`P = xy`, where variable x is the gate's input and y the output. This simple two-variable problem is manually minor-embedded to a single :std:doc:`Chimera <system:intro>` unit cell: each variable is represented by a chain of half the cell's qubits, x as qubits 0, 1, 4, 5, and y as qubits 2, 3, 6, 7. The chain strength is set to half the maximum allowed found from querying the solver's extended J range. In this example, the ten returned samples all represent valid states of the NOT gate. >>> from dwave.system.samplers import DWaveSampler >>> from dwave.system.composites import VirtualGraphComposite >>> embedding = {'x': {0, 4, 1, 5}, 'y': {2, 6, 3, 7}} >>> DWaveSampler().properties['extended_j_range'] # doctest: +SKIP [-2.0, 1.0] >>> sampler = VirtualGraphComposite(DWaveSampler(), embedding, chain_strength=1) # doctest: +SKIP >>> h = {} >>> J = {('x', 'y'): 1} >>> response = sampler.sample_ising(h, J, num_reads=10) # doctest: +SKIP >>> for sample in response.samples(): # doctest: +SKIP ... print(sample) ... {'y': -1, 'x': 1} {'y': 1, 'x': -1} {'y': -1, 'x': 1} {'y': -1, 'x': 1} {'y': -1, 'x': 1} {'y': 1, 'x': -1} {'y': 1, 'x': -1} {'y': 1, 'x': -1} {'y': -1, 'x': 1} {'y': 1, 'x': -1} See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools. """ child = self.child if apply_flux_bias_offsets: if self.flux_biases is not None: kwargs[FLUX_BIAS_KWARG] = self.flux_biases return child.sample(bqm, **kwargs)
python
def sample(self, bqm, apply_flux_bias_offsets=True, **kwargs): child = self.child if apply_flux_bias_offsets: if self.flux_biases is not None: kwargs[FLUX_BIAS_KWARG] = self.flux_biases return child.sample(bqm, **kwargs)
[ "def", "sample", "(", "self", ",", "bqm", ",", "apply_flux_bias_offsets", "=", "True", ",", "*", "*", "kwargs", ")", ":", "child", "=", "self", ".", "child", "if", "apply_flux_bias_offsets", ":", "if", "self", ".", "flux_biases", "is", "not", "None", ":"...
Sample from the given Ising model. Args: h (list/dict): Linear biases of the Ising model. If a list, the list's indices are used as variable labels. J (dict of (int, int):float): Quadratic biases of the Ising model. apply_flux_bias_offsets (bool, optional): If True, use the calculated flux_bias offsets (if available). **kwargs: Optional keyword arguments for the sampling method, specified per solver. Examples: This example uses :class:`.VirtualGraphComposite` to instantiate a composed sampler that submits an Ising problem to a D-Wave solver selected by the user's default :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`. The problem represents a logical NOT gate using penalty function :math:`P = xy`, where variable x is the gate's input and y the output. This simple two-variable problem is manually minor-embedded to a single :std:doc:`Chimera <system:intro>` unit cell: each variable is represented by a chain of half the cell's qubits, x as qubits 0, 1, 4, 5, and y as qubits 2, 3, 6, 7. The chain strength is set to half the maximum allowed found from querying the solver's extended J range. In this example, the ten returned samples all represent valid states of the NOT gate. >>> from dwave.system.samplers import DWaveSampler >>> from dwave.system.composites import VirtualGraphComposite >>> embedding = {'x': {0, 4, 1, 5}, 'y': {2, 6, 3, 7}} >>> DWaveSampler().properties['extended_j_range'] # doctest: +SKIP [-2.0, 1.0] >>> sampler = VirtualGraphComposite(DWaveSampler(), embedding, chain_strength=1) # doctest: +SKIP >>> h = {} >>> J = {('x', 'y'): 1} >>> response = sampler.sample_ising(h, J, num_reads=10) # doctest: +SKIP >>> for sample in response.samples(): # doctest: +SKIP ... print(sample) ... {'y': -1, 'x': 1} {'y': 1, 'x': -1} {'y': -1, 'x': 1} {'y': -1, 'x': 1} {'y': -1, 'x': 1} {'y': 1, 'x': -1} {'y': 1, 'x': -1} {'y': 1, 'x': -1} {'y': -1, 'x': 1} {'y': 1, 'x': -1} See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools.
[ "Sample", "from", "the", "given", "Ising", "model", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/composites/virtual_graph.py#L299-L365
19,655
dwavesystems/dwave-system
dwave/system/flux_bias_offsets.py
get_flux_biases
def get_flux_biases(sampler, embedding, chain_strength, num_reads=1000, max_age=3600): """Get the flux bias offsets for sampler and embedding. Args: sampler (:obj:`.DWaveSampler`): A D-Wave sampler. embedding (dict[hashable, iterable]): Mapping from a source graph to the specified sampler’s graph (the target graph). The keys of embedding should be nodes in the source graph, the values should be an iterable of nodes in the target graph. chain_strength (number): Desired chain coupling strength. This is the magnitude of couplings between qubits in a chain. num_reads (int, optional, default=1000): The number of reads per system call if new flux biases need to be calculated. max_age (int, optional, default=3600): The maximum age (in seconds) allowed for previously calculated flux bias offsets. Returns: dict: A dict where the keys are the nodes in the chains and the values are the flux biases. """ if not isinstance(sampler, dimod.Sampler): raise TypeError("input sampler should be DWaveSampler") # try to read the chip_id, otherwise get the name system_name = sampler.properties.get('chip_id', str(sampler.__class__)) try: with cache_connect() as cur: fbo = get_flux_biases_from_cache(cur, embedding.values(), system_name, chain_strength=chain_strength, max_age=max_age) return fbo except MissingFluxBias: pass # if dwave-drivers is not available, then we can't calculate the biases try: import dwave.drivers as drivers except ImportError: msg = ("dwave-drivers not found, cannot calculate flux biases. dwave-drivers can be " "installed with " "'pip install dwave-drivers --extra-index-url https://pypi.dwavesys.com/simple'. " "See documentation for dwave-drivers license.") raise RuntimeError(msg) fbo = drivers.oneshot_flux_bias(sampler, embedding.values(), num_reads=num_reads, chain_strength=chain_strength) # store them in the cache with cache_connect() as cur: for chain in embedding.values(): v = next(iter(chain)) flux_bias = fbo.get(v, 0.0) insert_flux_bias(cur, chain, system_name, flux_bias, chain_strength) return fbo
python
def get_flux_biases(sampler, embedding, chain_strength, num_reads=1000, max_age=3600): if not isinstance(sampler, dimod.Sampler): raise TypeError("input sampler should be DWaveSampler") # try to read the chip_id, otherwise get the name system_name = sampler.properties.get('chip_id', str(sampler.__class__)) try: with cache_connect() as cur: fbo = get_flux_biases_from_cache(cur, embedding.values(), system_name, chain_strength=chain_strength, max_age=max_age) return fbo except MissingFluxBias: pass # if dwave-drivers is not available, then we can't calculate the biases try: import dwave.drivers as drivers except ImportError: msg = ("dwave-drivers not found, cannot calculate flux biases. dwave-drivers can be " "installed with " "'pip install dwave-drivers --extra-index-url https://pypi.dwavesys.com/simple'. " "See documentation for dwave-drivers license.") raise RuntimeError(msg) fbo = drivers.oneshot_flux_bias(sampler, embedding.values(), num_reads=num_reads, chain_strength=chain_strength) # store them in the cache with cache_connect() as cur: for chain in embedding.values(): v = next(iter(chain)) flux_bias = fbo.get(v, 0.0) insert_flux_bias(cur, chain, system_name, flux_bias, chain_strength) return fbo
[ "def", "get_flux_biases", "(", "sampler", ",", "embedding", ",", "chain_strength", ",", "num_reads", "=", "1000", ",", "max_age", "=", "3600", ")", ":", "if", "not", "isinstance", "(", "sampler", ",", "dimod", ".", "Sampler", ")", ":", "raise", "TypeError"...
Get the flux bias offsets for sampler and embedding. Args: sampler (:obj:`.DWaveSampler`): A D-Wave sampler. embedding (dict[hashable, iterable]): Mapping from a source graph to the specified sampler’s graph (the target graph). The keys of embedding should be nodes in the source graph, the values should be an iterable of nodes in the target graph. chain_strength (number): Desired chain coupling strength. This is the magnitude of couplings between qubits in a chain. num_reads (int, optional, default=1000): The number of reads per system call if new flux biases need to be calculated. max_age (int, optional, default=3600): The maximum age (in seconds) allowed for previously calculated flux bias offsets. Returns: dict: A dict where the keys are the nodes in the chains and the values are the flux biases.
[ "Get", "the", "flux", "bias", "offsets", "for", "sampler", "and", "embedding", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/flux_bias_offsets.py#L26-L88
19,656
dwavesystems/dwave-system
dwave/embedding/chimera.py
find_clique_embedding
def find_clique_embedding(k, m, n=None, t=None, target_edges=None): """Find an embedding for a clique in a Chimera graph. Given a target :term:`Chimera` graph size, and a clique (fully connect graph), attempts to find an embedding. Args: k (int/iterable): Clique to embed. If k is an integer, generates an embedding for a clique of size k labelled [0,k-1]. If k is an iterable, generates an embedding for a clique of size len(k), where iterable k is the variable labels. m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default 4): Size of the shore within each Chimera tile. target_edges (iterable[edge]): A list of edges in the target Chimera graph. Nodes are labelled as returned by :func:`~dwave_networkx.generators.chimera_graph`. Returns: dict: An embedding mapping a clique to the Chimera lattice. Examples: The first example finds an embedding for a :math:`K_4` complete graph in a single Chimera unit cell. The second for an alphanumerically labeled :math:`K_3` graph in 4 unit cells. >>> from dwave.embedding.chimera import find_clique_embedding ... >>> embedding = find_clique_embedding(4, 1, 1) >>> embedding # doctest: +SKIP {0: [4, 0], 1: [5, 1], 2: [6, 2], 3: [7, 3]} >>> from dwave.embedding.chimera import find_clique_embedding ... >>> embedding = find_clique_embedding(['a', 'b', 'c'], m=2, n=2, t=4) >>> embedding # doctest: +SKIP {'a': [20, 16], 'b': [21, 17], 'c': [22, 18]} """ import random _, nodes = k m, n, t, target_edges = _chimera_input(m, n, t, target_edges) # Special cases to return optimal embeddings for small k. The general clique embedder uses chains of length # at least 2, whereas cliques of size 1 and 2 can be embedded with single-qubit chains. if len(nodes) == 1: # If k == 1 we simply return a single chain consisting of a randomly sampled qubit. qubits = set().union(*target_edges) qubit = random.choice(tuple(qubits)) embedding = [[qubit]] elif len(nodes) == 2: # If k == 2 we simply return two one-qubit chains that are the endpoints of a randomly sampled coupler. if not isinstance(target_edges, list): edges = list(target_edges) edge = edges[random.randrange(len(edges))] embedding = [[edge[0]], [edge[1]]] else: # General case for k > 2. embedding = processor(target_edges, M=m, N=n, L=t).tightestNativeClique(len(nodes)) if not embedding: raise ValueError("cannot find a K{} embedding for given Chimera lattice".format(k)) return dict(zip(nodes, embedding))
python
def find_clique_embedding(k, m, n=None, t=None, target_edges=None): import random _, nodes = k m, n, t, target_edges = _chimera_input(m, n, t, target_edges) # Special cases to return optimal embeddings for small k. The general clique embedder uses chains of length # at least 2, whereas cliques of size 1 and 2 can be embedded with single-qubit chains. if len(nodes) == 1: # If k == 1 we simply return a single chain consisting of a randomly sampled qubit. qubits = set().union(*target_edges) qubit = random.choice(tuple(qubits)) embedding = [[qubit]] elif len(nodes) == 2: # If k == 2 we simply return two one-qubit chains that are the endpoints of a randomly sampled coupler. if not isinstance(target_edges, list): edges = list(target_edges) edge = edges[random.randrange(len(edges))] embedding = [[edge[0]], [edge[1]]] else: # General case for k > 2. embedding = processor(target_edges, M=m, N=n, L=t).tightestNativeClique(len(nodes)) if not embedding: raise ValueError("cannot find a K{} embedding for given Chimera lattice".format(k)) return dict(zip(nodes, embedding))
[ "def", "find_clique_embedding", "(", "k", ",", "m", ",", "n", "=", "None", ",", "t", "=", "None", ",", "target_edges", "=", "None", ")", ":", "import", "random", "_", ",", "nodes", "=", "k", "m", ",", "n", ",", "t", ",", "target_edges", "=", "_ch...
Find an embedding for a clique in a Chimera graph. Given a target :term:`Chimera` graph size, and a clique (fully connect graph), attempts to find an embedding. Args: k (int/iterable): Clique to embed. If k is an integer, generates an embedding for a clique of size k labelled [0,k-1]. If k is an iterable, generates an embedding for a clique of size len(k), where iterable k is the variable labels. m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default 4): Size of the shore within each Chimera tile. target_edges (iterable[edge]): A list of edges in the target Chimera graph. Nodes are labelled as returned by :func:`~dwave_networkx.generators.chimera_graph`. Returns: dict: An embedding mapping a clique to the Chimera lattice. Examples: The first example finds an embedding for a :math:`K_4` complete graph in a single Chimera unit cell. The second for an alphanumerically labeled :math:`K_3` graph in 4 unit cells. >>> from dwave.embedding.chimera import find_clique_embedding ... >>> embedding = find_clique_embedding(4, 1, 1) >>> embedding # doctest: +SKIP {0: [4, 0], 1: [5, 1], 2: [6, 2], 3: [7, 3]} >>> from dwave.embedding.chimera import find_clique_embedding ... >>> embedding = find_clique_embedding(['a', 'b', 'c'], m=2, n=2, t=4) >>> embedding # doctest: +SKIP {'a': [20, 16], 'b': [21, 17], 'c': [22, 18]}
[ "Find", "an", "embedding", "for", "a", "clique", "in", "a", "Chimera", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chimera.py#L27-L106
19,657
dwavesystems/dwave-system
dwave/embedding/chimera.py
find_biclique_embedding
def find_biclique_embedding(a, b, m, n=None, t=None, target_edges=None): """Find an embedding for a biclique in a Chimera graph. Given a target :term:`Chimera` graph size, and a biclique (a bipartite graph where every vertex in a set in connected to all vertices in the other set), attempts to find an embedding. Args: a (int/iterable): Left shore of the biclique to embed. If a is an integer, generates an embedding for a biclique with the left shore of size a labelled [0,a-1]. If a is an iterable, generates an embedding for a biclique with the left shore of size len(a), where iterable a is the variable labels. b (int/iterable): Right shore of the biclique to embed.If b is an integer, generates an embedding for a biclique with the right shore of size b labelled [0,b-1]. If b is an iterable, generates an embedding for a biclique with the right shore of size len(b), where iterable b provides the variable labels. m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default 4): Size of the shore within each Chimera tile. target_edges (iterable[edge]): A list of edges in the target Chimera graph. Nodes are labelled as returned by :func:`~dwave_networkx.generators.chimera_graph`. Returns: tuple: A 2-tuple containing: dict: An embedding mapping the left shore of the biclique to the Chimera lattice. dict: An embedding mapping the right shore of the biclique to the Chimera lattice Examples: This example finds an embedding for an alphanumerically labeled biclique in a single Chimera unit cell. >>> from dwave.embedding.chimera import find_biclique_embedding ... >>> left, right = find_biclique_embedding(['a', 'b', 'c'], ['d', 'e'], 1, 1) >>> print(left, right) # doctest: +SKIP {'a': [4], 'b': [5], 'c': [6]} {'d': [0], 'e': [1]} """ _, anodes = a _, bnodes = b m, n, t, target_edges = _chimera_input(m, n, t, target_edges) embedding = processor(target_edges, M=m, N=n, L=t).tightestNativeBiClique(len(anodes), len(bnodes)) if not embedding: raise ValueError("cannot find a K{},{} embedding for given Chimera lattice".format(a, b)) left, right = embedding return dict(zip(anodes, left)), dict(zip(bnodes, right))
python
def find_biclique_embedding(a, b, m, n=None, t=None, target_edges=None): _, anodes = a _, bnodes = b m, n, t, target_edges = _chimera_input(m, n, t, target_edges) embedding = processor(target_edges, M=m, N=n, L=t).tightestNativeBiClique(len(anodes), len(bnodes)) if not embedding: raise ValueError("cannot find a K{},{} embedding for given Chimera lattice".format(a, b)) left, right = embedding return dict(zip(anodes, left)), dict(zip(bnodes, right))
[ "def", "find_biclique_embedding", "(", "a", ",", "b", ",", "m", ",", "n", "=", "None", ",", "t", "=", "None", ",", "target_edges", "=", "None", ")", ":", "_", ",", "anodes", "=", "a", "_", ",", "bnodes", "=", "b", "m", ",", "n", ",", "t", ","...
Find an embedding for a biclique in a Chimera graph. Given a target :term:`Chimera` graph size, and a biclique (a bipartite graph where every vertex in a set in connected to all vertices in the other set), attempts to find an embedding. Args: a (int/iterable): Left shore of the biclique to embed. If a is an integer, generates an embedding for a biclique with the left shore of size a labelled [0,a-1]. If a is an iterable, generates an embedding for a biclique with the left shore of size len(a), where iterable a is the variable labels. b (int/iterable): Right shore of the biclique to embed.If b is an integer, generates an embedding for a biclique with the right shore of size b labelled [0,b-1]. If b is an iterable, generates an embedding for a biclique with the right shore of size len(b), where iterable b provides the variable labels. m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default 4): Size of the shore within each Chimera tile. target_edges (iterable[edge]): A list of edges in the target Chimera graph. Nodes are labelled as returned by :func:`~dwave_networkx.generators.chimera_graph`. Returns: tuple: A 2-tuple containing: dict: An embedding mapping the left shore of the biclique to the Chimera lattice. dict: An embedding mapping the right shore of the biclique to the Chimera lattice Examples: This example finds an embedding for an alphanumerically labeled biclique in a single Chimera unit cell. >>> from dwave.embedding.chimera import find_biclique_embedding ... >>> left, right = find_biclique_embedding(['a', 'b', 'c'], ['d', 'e'], 1, 1) >>> print(left, right) # doctest: +SKIP {'a': [4], 'b': [5], 'c': [6]} {'d': [0], 'e': [1]}
[ "Find", "an", "embedding", "for", "a", "biclique", "in", "a", "Chimera", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chimera.py#L111-L171
19,658
dwavesystems/dwave-system
dwave/embedding/chimera.py
find_grid_embedding
def find_grid_embedding(dim, m, n=None, t=4): """Find an embedding for a grid in a Chimera graph. Given a target :term:`Chimera` graph size, and grid dimensions, attempts to find an embedding. Args: dim (iterable[int]): Sizes of each grid dimension. Length can be between 1 and 3. m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default 4): Size of the shore within each Chimera tile. Returns: dict: An embedding mapping a grid to the Chimera lattice. Examples: This example finds an embedding for a 2x3 grid in a 12x12 lattice of Chimera unit cells. >>> from dwave.embedding.chimera import find_grid_embedding ... >>> embedding = find_grid_embedding([2, 3], m=12, n=12, t=4) >>> embedding # doctest: +SKIP {(0, 0): [0, 4], (0, 1): [8, 12], (0, 2): [16, 20], (1, 0): [96, 100], (1, 1): [104, 108], (1, 2): [112, 116]} """ m, n, t, target_edges = _chimera_input(m, n, t, None) indexer = dnx.generators.chimera.chimera_coordinates(m, n, t) dim = list(dim) num_dim = len(dim) if num_dim == 1: def _key(row, col, aisle): return row dim.extend([1, 1]) elif num_dim == 2: def _key(row, col, aisle): return row, col dim.append(1) elif num_dim == 3: def _key(row, col, aisle): return row, col, aisle else: raise ValueError("find_grid_embedding supports between one and three dimensions") rows, cols, aisles = dim if rows > m or cols > n or aisles > t: msg = ("the largest grid that find_grid_embedding can fit in a ({}, {}, {}) Chimera-lattice " "is {}x{}x{}; given grid is {}x{}x{}").format(m, n, t, m, n, t, rows, cols, aisles) raise ValueError(msg) return {_key(row, col, aisle): [indexer.int((row, col, 0, aisle)), indexer.int((row, col, 1, aisle))] for row in range(dim[0]) for col in range(dim[1]) for aisle in range(dim[2])}
python
def find_grid_embedding(dim, m, n=None, t=4): m, n, t, target_edges = _chimera_input(m, n, t, None) indexer = dnx.generators.chimera.chimera_coordinates(m, n, t) dim = list(dim) num_dim = len(dim) if num_dim == 1: def _key(row, col, aisle): return row dim.extend([1, 1]) elif num_dim == 2: def _key(row, col, aisle): return row, col dim.append(1) elif num_dim == 3: def _key(row, col, aisle): return row, col, aisle else: raise ValueError("find_grid_embedding supports between one and three dimensions") rows, cols, aisles = dim if rows > m or cols > n or aisles > t: msg = ("the largest grid that find_grid_embedding can fit in a ({}, {}, {}) Chimera-lattice " "is {}x{}x{}; given grid is {}x{}x{}").format(m, n, t, m, n, t, rows, cols, aisles) raise ValueError(msg) return {_key(row, col, aisle): [indexer.int((row, col, 0, aisle)), indexer.int((row, col, 1, aisle))] for row in range(dim[0]) for col in range(dim[1]) for aisle in range(dim[2])}
[ "def", "find_grid_embedding", "(", "dim", ",", "m", ",", "n", "=", "None", ",", "t", "=", "4", ")", ":", "m", ",", "n", ",", "t", ",", "target_edges", "=", "_chimera_input", "(", "m", ",", "n", ",", "t", ",", "None", ")", "indexer", "=", "dnx",...
Find an embedding for a grid in a Chimera graph. Given a target :term:`Chimera` graph size, and grid dimensions, attempts to find an embedding. Args: dim (iterable[int]): Sizes of each grid dimension. Length can be between 1 and 3. m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default 4): Size of the shore within each Chimera tile. Returns: dict: An embedding mapping a grid to the Chimera lattice. Examples: This example finds an embedding for a 2x3 grid in a 12x12 lattice of Chimera unit cells. >>> from dwave.embedding.chimera import find_grid_embedding ... >>> embedding = find_grid_embedding([2, 3], m=12, n=12, t=4) >>> embedding # doctest: +SKIP {(0, 0): [0, 4], (0, 1): [8, 12], (0, 2): [16, 20], (1, 0): [96, 100], (1, 1): [104, 108], (1, 2): [112, 116]}
[ "Find", "an", "embedding", "for", "a", "grid", "in", "a", "Chimera", "graph", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/chimera.py#L174-L234
19,659
dwavesystems/dwave-system
dwave/system/composites/cutoffcomposite.py
CutOffComposite.sample
def sample(self, bqm, **parameters): """Cutoff and sample from the provided binary quadratic model. Removes interactions smaller than a given cutoff. Isolated variables (after the cutoff) are also removed. Note that if the problem had isolated variables before the cutoff, they will also be affected. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet` """ child = self.child cutoff = self._cutoff cutoff_vartype = self._cutoff_vartype comp = self._comparison if cutoff_vartype is dimod.SPIN: original = bqm.spin else: original = bqm.binary # remove all of the interactions less than cutoff new = type(bqm)(original.linear, ((u, v, bias) for (u, v), bias in original.quadratic.items() if not comp(abs(bias), cutoff)), original.offset, original.vartype) # next we check for isolated qubits and remove them, we could do this as # part of the construction but the assumption is there should not be # a large number in the 'typical' case isolated = [v for v in new if not new.adj[v]] new.remove_variables_from(isolated) if isolated and len(new) == 0: # in this case all variables are isolated, so we just put one back # to serve as the basis v = isolated.pop() new.linear[v] = original.linear[v] # get the samples from the child sampler and put them into the original vartype sampleset = child.sample(new, **parameters).change_vartype(bqm.vartype, inplace=True) # we now need to add the isolated back in, in a way that minimizes # the energy. There are lots of ways to do this but for now we'll just # do one if isolated: samples, variables = _restore_isolated(sampleset, bqm, isolated) else: samples = sampleset.record.sample variables = sampleset.variables vectors = sampleset.data_vectors vectors.pop('energy') # we're going to recalculate the energy anyway return dimod.SampleSet.from_samples_bqm((samples, variables), bqm, **vectors)
python
def sample(self, bqm, **parameters): child = self.child cutoff = self._cutoff cutoff_vartype = self._cutoff_vartype comp = self._comparison if cutoff_vartype is dimod.SPIN: original = bqm.spin else: original = bqm.binary # remove all of the interactions less than cutoff new = type(bqm)(original.linear, ((u, v, bias) for (u, v), bias in original.quadratic.items() if not comp(abs(bias), cutoff)), original.offset, original.vartype) # next we check for isolated qubits and remove them, we could do this as # part of the construction but the assumption is there should not be # a large number in the 'typical' case isolated = [v for v in new if not new.adj[v]] new.remove_variables_from(isolated) if isolated and len(new) == 0: # in this case all variables are isolated, so we just put one back # to serve as the basis v = isolated.pop() new.linear[v] = original.linear[v] # get the samples from the child sampler and put them into the original vartype sampleset = child.sample(new, **parameters).change_vartype(bqm.vartype, inplace=True) # we now need to add the isolated back in, in a way that minimizes # the energy. There are lots of ways to do this but for now we'll just # do one if isolated: samples, variables = _restore_isolated(sampleset, bqm, isolated) else: samples = sampleset.record.sample variables = sampleset.variables vectors = sampleset.data_vectors vectors.pop('energy') # we're going to recalculate the energy anyway return dimod.SampleSet.from_samples_bqm((samples, variables), bqm, **vectors)
[ "def", "sample", "(", "self", ",", "bqm", ",", "*", "*", "parameters", ")", ":", "child", "=", "self", ".", "child", "cutoff", "=", "self", ".", "_cutoff", "cutoff_vartype", "=", "self", ".", "_cutoff_vartype", "comp", "=", "self", ".", "_comparison", ...
Cutoff and sample from the provided binary quadratic model. Removes interactions smaller than a given cutoff. Isolated variables (after the cutoff) are also removed. Note that if the problem had isolated variables before the cutoff, they will also be affected. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet`
[ "Cutoff", "and", "sample", "from", "the", "provided", "binary", "quadratic", "model", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/composites/cutoffcomposite.py#L79-L144
19,660
dwavesystems/dwave-system
dwave/system/composites/cutoffcomposite.py
PolyCutOffComposite.sample_poly
def sample_poly(self, poly, **kwargs): """Cutoff and sample from the provided binary polynomial. Removes interactions smaller than a given cutoff. Isolated variables (after the cutoff) are also removed. Note that if the problem had isolated variables before the cutoff, they will also be affected. Args: poly (:obj:`dimod.BinaryPolynomial`): Binary polynomial to be sampled from. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet` """ child = self.child cutoff = self._cutoff cutoff_vartype = self._cutoff_vartype comp = self._comparison if cutoff_vartype is dimod.SPIN: original = poly.to_spin(copy=False) else: original = poly.to_binary(copy=False) # remove all of the terms of order >= 2 that have a bias less than cutoff new = type(poly)(((term, bias) for term, bias in original.items() if len(term) > 1 and not comp(abs(bias), cutoff)), cutoff_vartype) # also include the linear biases for the variables in new for v in new.variables: term = v, if term in original: new[term] = original[term] # everything else is isolated isolated = list(original.variables.difference(new.variables)) if isolated and len(new) == 0: # in this case all variables are isolated, so we just put one back # to serve as the basis term = isolated.pop(), new[term] = original[term] # get the samples from the child sampler and put them into the original vartype sampleset = child.sample_poly(new, **kwargs).change_vartype(poly.vartype, inplace=True) # we now need to add the isolated back in, in a way that minimizes # the energy. There are lots of ways to do this but for now we'll just # do one if isolated: samples, variables = _restore_isolated_higherorder(sampleset, poly, isolated) else: samples = sampleset.record.sample variables = sampleset.variables vectors = sampleset.data_vectors vectors.pop('energy') # we're going to recalculate the energy anyway return dimod.SampleSet.from_samples_bqm((samples, variables), poly, **vectors)
python
def sample_poly(self, poly, **kwargs): child = self.child cutoff = self._cutoff cutoff_vartype = self._cutoff_vartype comp = self._comparison if cutoff_vartype is dimod.SPIN: original = poly.to_spin(copy=False) else: original = poly.to_binary(copy=False) # remove all of the terms of order >= 2 that have a bias less than cutoff new = type(poly)(((term, bias) for term, bias in original.items() if len(term) > 1 and not comp(abs(bias), cutoff)), cutoff_vartype) # also include the linear biases for the variables in new for v in new.variables: term = v, if term in original: new[term] = original[term] # everything else is isolated isolated = list(original.variables.difference(new.variables)) if isolated and len(new) == 0: # in this case all variables are isolated, so we just put one back # to serve as the basis term = isolated.pop(), new[term] = original[term] # get the samples from the child sampler and put them into the original vartype sampleset = child.sample_poly(new, **kwargs).change_vartype(poly.vartype, inplace=True) # we now need to add the isolated back in, in a way that minimizes # the energy. There are lots of ways to do this but for now we'll just # do one if isolated: samples, variables = _restore_isolated_higherorder(sampleset, poly, isolated) else: samples = sampleset.record.sample variables = sampleset.variables vectors = sampleset.data_vectors vectors.pop('energy') # we're going to recalculate the energy anyway return dimod.SampleSet.from_samples_bqm((samples, variables), poly, **vectors)
[ "def", "sample_poly", "(", "self", ",", "poly", ",", "*", "*", "kwargs", ")", ":", "child", "=", "self", ".", "child", "cutoff", "=", "self", ".", "_cutoff", "cutoff_vartype", "=", "self", ".", "_cutoff_vartype", "comp", "=", "self", ".", "_comparison", ...
Cutoff and sample from the provided binary polynomial. Removes interactions smaller than a given cutoff. Isolated variables (after the cutoff) are also removed. Note that if the problem had isolated variables before the cutoff, they will also be affected. Args: poly (:obj:`dimod.BinaryPolynomial`): Binary polynomial to be sampled from. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet`
[ "Cutoff", "and", "sample", "from", "the", "provided", "binary", "polynomial", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/composites/cutoffcomposite.py#L231-L296
19,661
dwavesystems/dwave-system
dwave/embedding/diagnostic.py
diagnose_embedding
def diagnose_embedding(emb, source, target): """A detailed diagnostic for minor embeddings. This diagnostic produces a generator, which lists all issues with `emb`. The errors are yielded in the form ExceptionClass, arg1, arg2,... where the arguments following the class are used to construct the exception object. User-friendly variants of this function are :func:`is_valid_embedding`, which returns a bool, and :func:`verify_embedding` which raises the first observed error. All exceptions are subclasses of :exc:`.EmbeddingError`. Args: emb (dict): Dictionary mapping source nodes to arrays of target nodes. source (list/:obj:`networkx.Graph`): Graph to be embedded as a NetworkX graph or a list of edges. target (list/:obj:`networkx.Graph`): Graph being embedded into as a NetworkX graph or a list of edges. Yields: One of: :exc:`.MissingChainError`, snode: a source node label that does not occur as a key of `emb`, or for which emb[snode] is empty :exc:`.ChainOverlapError`, tnode, snode0, snode0: a target node which occurs in both `emb[snode0]` and `emb[snode1]` :exc:`.DisconnectedChainError`, snode: a source node label whose chain is not a connected subgraph of `target` :exc:`.InvalidNodeError`, tnode, snode: a source node label and putative target node label which is not a node of `target` :exc:`.MissingEdgeError`, snode0, snode1: a pair of source node labels defining an edge which is not present between their chains """ if not hasattr(source, 'edges'): source = nx.Graph(source) if not hasattr(target, 'edges'): target = nx.Graph(target) label = {} embedded = set() for x in source: try: embx = emb[x] missing_chain = len(embx) == 0 except KeyError: missing_chain = True if missing_chain: yield MissingChainError, x continue all_present = True for q in embx: if label.get(q, x) != x: yield ChainOverlapError, q, x, label[q] elif q not in target: all_present = False yield InvalidNodeError, x, q else: label[q] = x if all_present: embedded.add(x) if not nx.is_connected(target.subgraph(embx)): yield DisconnectedChainError, x yielded = nx.Graph() for p, q in target.subgraph(label).edges(): yielded.add_edge(label[p], label[q]) for x, y in source.edges(): if x == y: continue if x in embedded and y in embedded and not yielded.has_edge(x, y): yield MissingEdgeError, x, y
python
def diagnose_embedding(emb, source, target): if not hasattr(source, 'edges'): source = nx.Graph(source) if not hasattr(target, 'edges'): target = nx.Graph(target) label = {} embedded = set() for x in source: try: embx = emb[x] missing_chain = len(embx) == 0 except KeyError: missing_chain = True if missing_chain: yield MissingChainError, x continue all_present = True for q in embx: if label.get(q, x) != x: yield ChainOverlapError, q, x, label[q] elif q not in target: all_present = False yield InvalidNodeError, x, q else: label[q] = x if all_present: embedded.add(x) if not nx.is_connected(target.subgraph(embx)): yield DisconnectedChainError, x yielded = nx.Graph() for p, q in target.subgraph(label).edges(): yielded.add_edge(label[p], label[q]) for x, y in source.edges(): if x == y: continue if x in embedded and y in embedded and not yielded.has_edge(x, y): yield MissingEdgeError, x, y
[ "def", "diagnose_embedding", "(", "emb", ",", "source", ",", "target", ")", ":", "if", "not", "hasattr", "(", "source", ",", "'edges'", ")", ":", "source", "=", "nx", ".", "Graph", "(", "source", ")", "if", "not", "hasattr", "(", "target", ",", "'edg...
A detailed diagnostic for minor embeddings. This diagnostic produces a generator, which lists all issues with `emb`. The errors are yielded in the form ExceptionClass, arg1, arg2,... where the arguments following the class are used to construct the exception object. User-friendly variants of this function are :func:`is_valid_embedding`, which returns a bool, and :func:`verify_embedding` which raises the first observed error. All exceptions are subclasses of :exc:`.EmbeddingError`. Args: emb (dict): Dictionary mapping source nodes to arrays of target nodes. source (list/:obj:`networkx.Graph`): Graph to be embedded as a NetworkX graph or a list of edges. target (list/:obj:`networkx.Graph`): Graph being embedded into as a NetworkX graph or a list of edges. Yields: One of: :exc:`.MissingChainError`, snode: a source node label that does not occur as a key of `emb`, or for which emb[snode] is empty :exc:`.ChainOverlapError`, tnode, snode0, snode0: a target node which occurs in both `emb[snode0]` and `emb[snode1]` :exc:`.DisconnectedChainError`, snode: a source node label whose chain is not a connected subgraph of `target` :exc:`.InvalidNodeError`, tnode, snode: a source node label and putative target node label which is not a node of `target` :exc:`.MissingEdgeError`, snode0, snode1: a pair of source node labels defining an edge which is not present between their chains
[ "A", "detailed", "diagnostic", "for", "minor", "embeddings", "." ]
86a1698f15ccd8b0ece0ed868ee49292d3f67f5b
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/diagnostic.py#L23-L96
19,662
Jaza/flask-restplus-patched
flask_restplus_patched/namespace.py
Namespace.model
def model(self, name=None, model=None, mask=None, **kwargs): """ Model registration decorator. """ if isinstance(model, (flask_marshmallow.Schema, flask_marshmallow.base_fields.FieldABC)): if not name: name = model.__class__.__name__ api_model = Model(name, model, mask=mask) api_model.__apidoc__ = kwargs return self.add_model(name, api_model) return super(Namespace, self).model(name=name, model=model, **kwargs)
python
def model(self, name=None, model=None, mask=None, **kwargs): if isinstance(model, (flask_marshmallow.Schema, flask_marshmallow.base_fields.FieldABC)): if not name: name = model.__class__.__name__ api_model = Model(name, model, mask=mask) api_model.__apidoc__ = kwargs return self.add_model(name, api_model) return super(Namespace, self).model(name=name, model=model, **kwargs)
[ "def", "model", "(", "self", ",", "name", "=", "None", ",", "model", "=", "None", ",", "mask", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "model", ",", "(", "flask_marshmallow", ".", "Schema", ",", "flask_marshmallow", "...
Model registration decorator.
[ "Model", "registration", "decorator", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/namespace.py#L62-L72
19,663
Jaza/flask-restplus-patched
flask_restplus_patched/namespace.py
Namespace.parameters
def parameters(self, parameters, locations=None): """ Endpoint parameters registration decorator. """ def decorator(func): if locations is None and parameters.many: _locations = ('json', ) else: _locations = locations if _locations is not None: parameters.context['in'] = _locations return self.doc(params=parameters)( self.response(code=HTTPStatus.UNPROCESSABLE_ENTITY)( self.WEBARGS_PARSER.use_args(parameters, locations=_locations)( func ) ) ) return decorator
python
def parameters(self, parameters, locations=None): def decorator(func): if locations is None and parameters.many: _locations = ('json', ) else: _locations = locations if _locations is not None: parameters.context['in'] = _locations return self.doc(params=parameters)( self.response(code=HTTPStatus.UNPROCESSABLE_ENTITY)( self.WEBARGS_PARSER.use_args(parameters, locations=_locations)( func ) ) ) return decorator
[ "def", "parameters", "(", "self", ",", "parameters", ",", "locations", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "locations", "is", "None", "and", "parameters", ".", "many", ":", "_locations", "=", "(", "'json'", ",", ")",...
Endpoint parameters registration decorator.
[ "Endpoint", "parameters", "registration", "decorator", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/namespace.py#L74-L94
19,664
Jaza/flask-restplus-patched
flask_restplus_patched/namespace.py
Namespace.response
def response(self, model=None, code=HTTPStatus.OK, description=None, **kwargs): """ Endpoint response OpenAPI documentation decorator. It automatically documents HTTPError%(code)d responses with relevant schemas. Arguments: model (flask_marshmallow.Schema) - it can be a class or an instance of the class, which will be used for OpenAPI documentation purposes. It can be omitted if ``code`` argument is set to an error HTTP status code. code (int) - HTTP status code which is documented. description (str) Example: >>> @namespace.response(BaseTeamSchema(many=True)) ... @namespace.response(code=HTTPStatus.FORBIDDEN) ... def get_teams(): ... if not user.is_admin: ... abort(HTTPStatus.FORBIDDEN) ... return Team.query.all() """ code = HTTPStatus(code) if code is HTTPStatus.NO_CONTENT: assert model is None if model is None and code not in {HTTPStatus.ACCEPTED, HTTPStatus.NO_CONTENT}: if code.value not in http_exceptions.default_exceptions: raise ValueError("`model` parameter is required for code %d" % code) model = self.model( name='HTTPError%d' % code, model=DefaultHTTPErrorSchema(http_code=code) ) if description is None: description = code.description def response_serializer_decorator(func): """ This decorator handles responses to serialize the returned value with a given model. """ def dump_wrapper(*args, **kwargs): # pylint: disable=missing-docstring response = func(*args, **kwargs) extra_headers = None if response is None: if model is not None: raise ValueError("Response cannot not be None with HTTP status %d" % code) return flask.Response(status=code) elif isinstance(response, flask.Response) or model is None: return response elif isinstance(response, tuple): response, _code, extra_headers = unpack(response) else: _code = code if HTTPStatus(_code) is code: response = model.dump(response).data return response, _code, extra_headers return dump_wrapper def decorator(func_or_class): if code.value in http_exceptions.default_exceptions: # If the code is handled by raising an exception, it will # produce a response later, so we don't need to apply a useless # wrapper. decorated_func_or_class = func_or_class elif isinstance(func_or_class, type): # Handle Resource classes decoration # pylint: disable=protected-access func_or_class._apply_decorator_to_methods(response_serializer_decorator) decorated_func_or_class = func_or_class else: decorated_func_or_class = wraps(func_or_class)( response_serializer_decorator(func_or_class) ) if model is None: api_model = None else: if isinstance(model, Model): api_model = model else: api_model = self.model(model=model) if getattr(model, 'many', False): api_model = [api_model] doc_decorator = self.doc( responses={ code.value: (description, api_model) } ) return doc_decorator(decorated_func_or_class) return decorator
python
def response(self, model=None, code=HTTPStatus.OK, description=None, **kwargs): code = HTTPStatus(code) if code is HTTPStatus.NO_CONTENT: assert model is None if model is None and code not in {HTTPStatus.ACCEPTED, HTTPStatus.NO_CONTENT}: if code.value not in http_exceptions.default_exceptions: raise ValueError("`model` parameter is required for code %d" % code) model = self.model( name='HTTPError%d' % code, model=DefaultHTTPErrorSchema(http_code=code) ) if description is None: description = code.description def response_serializer_decorator(func): """ This decorator handles responses to serialize the returned value with a given model. """ def dump_wrapper(*args, **kwargs): # pylint: disable=missing-docstring response = func(*args, **kwargs) extra_headers = None if response is None: if model is not None: raise ValueError("Response cannot not be None with HTTP status %d" % code) return flask.Response(status=code) elif isinstance(response, flask.Response) or model is None: return response elif isinstance(response, tuple): response, _code, extra_headers = unpack(response) else: _code = code if HTTPStatus(_code) is code: response = model.dump(response).data return response, _code, extra_headers return dump_wrapper def decorator(func_or_class): if code.value in http_exceptions.default_exceptions: # If the code is handled by raising an exception, it will # produce a response later, so we don't need to apply a useless # wrapper. decorated_func_or_class = func_or_class elif isinstance(func_or_class, type): # Handle Resource classes decoration # pylint: disable=protected-access func_or_class._apply_decorator_to_methods(response_serializer_decorator) decorated_func_or_class = func_or_class else: decorated_func_or_class = wraps(func_or_class)( response_serializer_decorator(func_or_class) ) if model is None: api_model = None else: if isinstance(model, Model): api_model = model else: api_model = self.model(model=model) if getattr(model, 'many', False): api_model = [api_model] doc_decorator = self.doc( responses={ code.value: (description, api_model) } ) return doc_decorator(decorated_func_or_class) return decorator
[ "def", "response", "(", "self", ",", "model", "=", "None", ",", "code", "=", "HTTPStatus", ".", "OK", ",", "description", "=", "None", ",", "*", "*", "kwargs", ")", ":", "code", "=", "HTTPStatus", "(", "code", ")", "if", "code", "is", "HTTPStatus", ...
Endpoint response OpenAPI documentation decorator. It automatically documents HTTPError%(code)d responses with relevant schemas. Arguments: model (flask_marshmallow.Schema) - it can be a class or an instance of the class, which will be used for OpenAPI documentation purposes. It can be omitted if ``code`` argument is set to an error HTTP status code. code (int) - HTTP status code which is documented. description (str) Example: >>> @namespace.response(BaseTeamSchema(many=True)) ... @namespace.response(code=HTTPStatus.FORBIDDEN) ... def get_teams(): ... if not user.is_admin: ... abort(HTTPStatus.FORBIDDEN) ... return Team.query.all()
[ "Endpoint", "response", "OpenAPI", "documentation", "decorator", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/namespace.py#L96-L192
19,665
Jaza/flask-restplus-patched
flask_restplus_patched/resource.py
Resource._apply_decorator_to_methods
def _apply_decorator_to_methods(cls, decorator): """ This helper can apply a given decorator to all methods on the current Resource. NOTE: In contrast to ``Resource.method_decorators``, which has a similar use-case, this method applies decorators directly and override methods in-place, while the decorators listed in ``Resource.method_decorators`` are applied on every request which is quite a waste of resources. """ for method in cls.methods: method_name = method.lower() decorated_method_func = decorator(getattr(cls, method_name)) setattr(cls, method_name, decorated_method_func)
python
def _apply_decorator_to_methods(cls, decorator): for method in cls.methods: method_name = method.lower() decorated_method_func = decorator(getattr(cls, method_name)) setattr(cls, method_name, decorated_method_func)
[ "def", "_apply_decorator_to_methods", "(", "cls", ",", "decorator", ")", ":", "for", "method", "in", "cls", ".", "methods", ":", "method_name", "=", "method", ".", "lower", "(", ")", "decorated_method_func", "=", "decorator", "(", "getattr", "(", "cls", ",",...
This helper can apply a given decorator to all methods on the current Resource. NOTE: In contrast to ``Resource.method_decorators``, which has a similar use-case, this method applies decorators directly and override methods in-place, while the decorators listed in ``Resource.method_decorators`` are applied on every request which is quite a waste of resources.
[ "This", "helper", "can", "apply", "a", "given", "decorator", "to", "all", "methods", "on", "the", "current", "Resource", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/resource.py#L16-L30
19,666
Jaza/flask-restplus-patched
flask_restplus_patched/resource.py
Resource.options
def options(self, *args, **kwargs): """ Check which methods are allowed. Use this method if you need to know what operations are allowed to be performed on this endpoint, e.g. to decide wether to display a button in your UI. The list of allowed methods is provided in `Allow` response header. """ # This is a generic implementation of OPTIONS method for resources. # This method checks every permissions provided as decorators for other # methods to provide information about what methods `current_user` can # use. method_funcs = [getattr(self, m.lower()) for m in self.methods] allowed_methods = [] request_oauth_backup = getattr(flask.request, 'oauth', None) for method_func in method_funcs: if getattr(method_func, '_access_restriction_decorators', None): if not hasattr(method_func, '_cached_fake_method_func'): fake_method_func = lambda *args, **kwargs: True # `__name__` is used in `login_required` decorator, so it # is required to fake this also fake_method_func.__name__ = 'options' # Decorate the fake method with the registered access # restriction decorators for decorator in method_func._access_restriction_decorators: fake_method_func = decorator(fake_method_func) # Cache the `fake_method_func` to avoid redoing this over # and over again method_func.__dict__['_cached_fake_method_func'] = fake_method_func else: fake_method_func = method_func._cached_fake_method_func flask.request.oauth = None try: fake_method_func(self, *args, **kwargs) except HTTPException: # This method is not allowed, so skip it continue allowed_methods.append(method_func.__name__.upper()) flask.request.oauth = request_oauth_backup return flask.Response( status=HTTPStatus.NO_CONTENT, headers={'Allow': ", ".join(allowed_methods)} )
python
def options(self, *args, **kwargs): # This is a generic implementation of OPTIONS method for resources. # This method checks every permissions provided as decorators for other # methods to provide information about what methods `current_user` can # use. method_funcs = [getattr(self, m.lower()) for m in self.methods] allowed_methods = [] request_oauth_backup = getattr(flask.request, 'oauth', None) for method_func in method_funcs: if getattr(method_func, '_access_restriction_decorators', None): if not hasattr(method_func, '_cached_fake_method_func'): fake_method_func = lambda *args, **kwargs: True # `__name__` is used in `login_required` decorator, so it # is required to fake this also fake_method_func.__name__ = 'options' # Decorate the fake method with the registered access # restriction decorators for decorator in method_func._access_restriction_decorators: fake_method_func = decorator(fake_method_func) # Cache the `fake_method_func` to avoid redoing this over # and over again method_func.__dict__['_cached_fake_method_func'] = fake_method_func else: fake_method_func = method_func._cached_fake_method_func flask.request.oauth = None try: fake_method_func(self, *args, **kwargs) except HTTPException: # This method is not allowed, so skip it continue allowed_methods.append(method_func.__name__.upper()) flask.request.oauth = request_oauth_backup return flask.Response( status=HTTPStatus.NO_CONTENT, headers={'Allow': ", ".join(allowed_methods)} )
[ "def", "options", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# This is a generic implementation of OPTIONS method for resources.", "# This method checks every permissions provided as decorators for other", "# methods to provide information about what methods `cu...
Check which methods are allowed. Use this method if you need to know what operations are allowed to be performed on this endpoint, e.g. to decide wether to display a button in your UI. The list of allowed methods is provided in `Allow` response header.
[ "Check", "which", "methods", "are", "allowed", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/resource.py#L32-L81
19,667
Jaza/flask-restplus-patched
flask_restplus_patched/parameters.py
PatchJSONParameters.validate_patch_structure
def validate_patch_structure(self, data): """ Common validation of PATCH structure Provide check that 'value' present in all operations expect it. Provide check if 'path' is present. 'path' can be absent if provided without '/' at the start. Supposed that if 'path' is present than it is prepended with '/'. Removing '/' in the beginning to simplify usage in resource. """ if data['op'] not in self.NO_VALUE_OPERATIONS and 'value' not in data: raise ValidationError('value is required') if 'path' not in data: raise ValidationError('Path is required and must always begin with /') else: data['field_name'] = data['path'][1:]
python
def validate_patch_structure(self, data): if data['op'] not in self.NO_VALUE_OPERATIONS and 'value' not in data: raise ValidationError('value is required') if 'path' not in data: raise ValidationError('Path is required and must always begin with /') else: data['field_name'] = data['path'][1:]
[ "def", "validate_patch_structure", "(", "self", ",", "data", ")", ":", "if", "data", "[", "'op'", "]", "not", "in", "self", ".", "NO_VALUE_OPERATIONS", "and", "'value'", "not", "in", "data", ":", "raise", "ValidationError", "(", "'value is required'", ")", "...
Common validation of PATCH structure Provide check that 'value' present in all operations expect it. Provide check if 'path' is present. 'path' can be absent if provided without '/' at the start. Supposed that if 'path' is present than it is prepended with '/'. Removing '/' in the beginning to simplify usage in resource.
[ "Common", "validation", "of", "PATCH", "structure" ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/parameters.py#L97-L114
19,668
Jaza/flask-restplus-patched
flask_restplus_patched/parameters.py
PatchJSONParameters.perform_patch
def perform_patch(cls, operations, obj, state=None): """ Performs all necessary operations by calling class methods with corresponding names. """ if state is None: state = {} for operation in operations: if not cls._process_patch_operation(operation, obj=obj, state=state): log.info( "%s patching has been stopped because of unknown operation %s", obj.__class__.__name__, operation ) raise ValidationError( "Failed to update %s details. Operation %s could not succeed." % ( obj.__class__.__name__, operation ) ) return True
python
def perform_patch(cls, operations, obj, state=None): if state is None: state = {} for operation in operations: if not cls._process_patch_operation(operation, obj=obj, state=state): log.info( "%s patching has been stopped because of unknown operation %s", obj.__class__.__name__, operation ) raise ValidationError( "Failed to update %s details. Operation %s could not succeed." % ( obj.__class__.__name__, operation ) ) return True
[ "def", "perform_patch", "(", "cls", ",", "operations", ",", "obj", ",", "state", "=", "None", ")", ":", "if", "state", "is", "None", ":", "state", "=", "{", "}", "for", "operation", "in", "operations", ":", "if", "not", "cls", ".", "_process_patch_oper...
Performs all necessary operations by calling class methods with corresponding names.
[ "Performs", "all", "necessary", "operations", "by", "calling", "class", "methods", "with", "corresponding", "names", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/parameters.py#L117-L137
19,669
Jaza/flask-restplus-patched
flask_restplus_patched/parameters.py
PatchJSONParameters.replace
def replace(cls, obj, field, value, state): """ This is method for replace operation. It is separated to provide a possibility to easily override it in your Parameters. Args: obj (object): an instance to change. field (str): field name value (str): new value state (dict): inter-operations state storage Returns: processing_status (bool): True """ if not hasattr(obj, field): raise ValidationError("Field '%s' does not exist, so it cannot be patched" % field) setattr(obj, field, value) return True
python
def replace(cls, obj, field, value, state): if not hasattr(obj, field): raise ValidationError("Field '%s' does not exist, so it cannot be patched" % field) setattr(obj, field, value) return True
[ "def", "replace", "(", "cls", ",", "obj", ",", "field", ",", "value", ",", "state", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "field", ")", ":", "raise", "ValidationError", "(", "\"Field '%s' does not exist, so it cannot be patched\"", "%", "field", ...
This is method for replace operation. It is separated to provide a possibility to easily override it in your Parameters. Args: obj (object): an instance to change. field (str): field name value (str): new value state (dict): inter-operations state storage Returns: processing_status (bool): True
[ "This", "is", "method", "for", "replace", "operation", ".", "It", "is", "separated", "to", "provide", "a", "possibility", "to", "easily", "override", "it", "in", "your", "Parameters", "." ]
38b4a030f28e6aec374d105173aa5e9b6bd51e5e
https://github.com/Jaza/flask-restplus-patched/blob/38b4a030f28e6aec374d105173aa5e9b6bd51e5e/flask_restplus_patched/parameters.py#L173-L190
19,670
chaoss/grimoirelab-elk
grimoire_elk/enriched/discourse.py
DiscourseEnrich.__related_categories
def __related_categories(self, category_id): """ Get all related categories to a given one """ related = [] for cat in self.categories_tree: if category_id in self.categories_tree[cat]: related.append(self.categories[cat]) return related
python
def __related_categories(self, category_id): related = [] for cat in self.categories_tree: if category_id in self.categories_tree[cat]: related.append(self.categories[cat]) return related
[ "def", "__related_categories", "(", "self", ",", "category_id", ")", ":", "related", "=", "[", "]", "for", "cat", "in", "self", ".", "categories_tree", ":", "if", "category_id", "in", "self", ".", "categories_tree", "[", "cat", "]", ":", "related", ".", ...
Get all related categories to a given one
[ "Get", "all", "related", "categories", "to", "a", "given", "one" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/discourse.py#L148-L154
19,671
chaoss/grimoirelab-elk
grimoire_elk/track_items.py
_create_projects_file
def _create_projects_file(project_name, data_source, items): """ Create a projects file from the items origin data """ repositories = [] for item in items: if item['origin'] not in repositories: repositories.append(item['origin']) projects = { project_name: { data_source: repositories } } projects_file, projects_file_path = tempfile.mkstemp(prefix='track_items_') with open(projects_file_path, "w") as pfile: json.dump(projects, pfile, indent=True) return projects_file_path
python
def _create_projects_file(project_name, data_source, items): repositories = [] for item in items: if item['origin'] not in repositories: repositories.append(item['origin']) projects = { project_name: { data_source: repositories } } projects_file, projects_file_path = tempfile.mkstemp(prefix='track_items_') with open(projects_file_path, "w") as pfile: json.dump(projects, pfile, indent=True) return projects_file_path
[ "def", "_create_projects_file", "(", "project_name", ",", "data_source", ",", "items", ")", ":", "repositories", "=", "[", "]", "for", "item", "in", "items", ":", "if", "item", "[", "'origin'", "]", "not", "in", "repositories", ":", "repositories", ".", "a...
Create a projects file from the items origin data
[ "Create", "a", "projects", "file", "from", "the", "items", "origin", "data" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/track_items.py#L194-L212
19,672
chaoss/grimoirelab-elk
grimoire_elk/enriched/dockerhub.py
DockerHubEnrich.enrich_items
def enrich_items(self, ocean_backend, events=False): """ A custom enrich items is needed because apart from the enriched events from raw items, a image item with the last data for an image must be created """ max_items = self.elastic.max_items_bulk current = 0 total = 0 bulk_json = "" items = ocean_backend.fetch() images_items = {} url = self.elastic.index_url + '/items/_bulk' logger.debug("Adding items to %s (in %i packs)", self.elastic.anonymize_url(url), max_items) for item in items: if current >= max_items: total += self.elastic.safe_put_bulk(url, bulk_json) json_size = sys.getsizeof(bulk_json) / (1024 * 1024) logger.debug("Added %i items to %s (%0.2f MB)", total, self.elastic.anonymize_url(url), json_size) bulk_json = "" current = 0 rich_item = self.get_rich_item(item) data_json = json.dumps(rich_item) bulk_json += '{"index" : {"_id" : "%s" } }\n' % \ (item[self.get_field_unique_id()]) bulk_json += data_json + "\n" # Bulk document current += 1 if rich_item['id'] not in images_items: # Let's transform the rich_event in a rich_image rich_item['is_docker_image'] = 1 rich_item['is_event'] = 0 images_items[rich_item['id']] = rich_item else: image_date = images_items[rich_item['id']]['last_updated'] if image_date <= rich_item['last_updated']: # This event is newer for the image rich_item['is_docker_image'] = 1 rich_item['is_event'] = 0 images_items[rich_item['id']] = rich_item if current > 0: total += self.elastic.safe_put_bulk(url, bulk_json) if total == 0: # No items enriched, nothing to upload to ES return total # Time to upload the images enriched items. The id is uuid+"_image" # Normally we are enriching events for a unique image so all images # data can be upload in one query for image in images_items: data = images_items[image] data_json = json.dumps(data) bulk_json += '{"index" : {"_id" : "%s" } }\n' % \ (data['id'] + "_image") bulk_json += data_json + "\n" # Bulk document total += self.elastic.safe_put_bulk(url, bulk_json) return total
python
def enrich_items(self, ocean_backend, events=False): max_items = self.elastic.max_items_bulk current = 0 total = 0 bulk_json = "" items = ocean_backend.fetch() images_items = {} url = self.elastic.index_url + '/items/_bulk' logger.debug("Adding items to %s (in %i packs)", self.elastic.anonymize_url(url), max_items) for item in items: if current >= max_items: total += self.elastic.safe_put_bulk(url, bulk_json) json_size = sys.getsizeof(bulk_json) / (1024 * 1024) logger.debug("Added %i items to %s (%0.2f MB)", total, self.elastic.anonymize_url(url), json_size) bulk_json = "" current = 0 rich_item = self.get_rich_item(item) data_json = json.dumps(rich_item) bulk_json += '{"index" : {"_id" : "%s" } }\n' % \ (item[self.get_field_unique_id()]) bulk_json += data_json + "\n" # Bulk document current += 1 if rich_item['id'] not in images_items: # Let's transform the rich_event in a rich_image rich_item['is_docker_image'] = 1 rich_item['is_event'] = 0 images_items[rich_item['id']] = rich_item else: image_date = images_items[rich_item['id']]['last_updated'] if image_date <= rich_item['last_updated']: # This event is newer for the image rich_item['is_docker_image'] = 1 rich_item['is_event'] = 0 images_items[rich_item['id']] = rich_item if current > 0: total += self.elastic.safe_put_bulk(url, bulk_json) if total == 0: # No items enriched, nothing to upload to ES return total # Time to upload the images enriched items. The id is uuid+"_image" # Normally we are enriching events for a unique image so all images # data can be upload in one query for image in images_items: data = images_items[image] data_json = json.dumps(data) bulk_json += '{"index" : {"_id" : "%s" } }\n' % \ (data['id'] + "_image") bulk_json += data_json + "\n" # Bulk document total += self.elastic.safe_put_bulk(url, bulk_json) return total
[ "def", "enrich_items", "(", "self", ",", "ocean_backend", ",", "events", "=", "False", ")", ":", "max_items", "=", "self", ".", "elastic", ".", "max_items_bulk", "current", "=", "0", "total", "=", "0", "bulk_json", "=", "\"\"", "items", "=", "ocean_backend...
A custom enrich items is needed because apart from the enriched events from raw items, a image item with the last data for an image must be created
[ "A", "custom", "enrich", "items", "is", "needed", "because", "apart", "from", "the", "enriched", "events", "from", "raw", "items", "a", "image", "item", "with", "the", "last", "data", "for", "an", "image", "must", "be", "created" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/dockerhub.py#L125-L188
19,673
chaoss/grimoirelab-elk
utils/gh2k.py
get_owner_repos_url
def get_owner_repos_url(owner, token): """ The owner could be a org or a user. It waits if need to have rate limit. Also it fixes a djando issue changing - with _ """ url_org = GITHUB_API_URL + "/orgs/" + owner + "/repos" url_user = GITHUB_API_URL + "/users/" + owner + "/repos" url_owner = url_org # Use org by default try: r = requests.get(url_org, params=get_payload(), headers=get_headers(token)) r.raise_for_status() except requests.exceptions.HTTPError as e: if r.status_code == 403: rate_limit_reset_ts = datetime.fromtimestamp(int(r.headers['X-RateLimit-Reset'])) seconds_to_reset = (rate_limit_reset_ts - datetime.utcnow()).seconds + 1 logging.info("GitHub rate limit exhausted. Waiting %i secs for rate limit reset." % (seconds_to_reset)) sleep(seconds_to_reset) else: # owner is not an org, try with a user url_owner = url_user return url_owner
python
def get_owner_repos_url(owner, token): url_org = GITHUB_API_URL + "/orgs/" + owner + "/repos" url_user = GITHUB_API_URL + "/users/" + owner + "/repos" url_owner = url_org # Use org by default try: r = requests.get(url_org, params=get_payload(), headers=get_headers(token)) r.raise_for_status() except requests.exceptions.HTTPError as e: if r.status_code == 403: rate_limit_reset_ts = datetime.fromtimestamp(int(r.headers['X-RateLimit-Reset'])) seconds_to_reset = (rate_limit_reset_ts - datetime.utcnow()).seconds + 1 logging.info("GitHub rate limit exhausted. Waiting %i secs for rate limit reset." % (seconds_to_reset)) sleep(seconds_to_reset) else: # owner is not an org, try with a user url_owner = url_user return url_owner
[ "def", "get_owner_repos_url", "(", "owner", ",", "token", ")", ":", "url_org", "=", "GITHUB_API_URL", "+", "\"/orgs/\"", "+", "owner", "+", "\"/repos\"", "url_user", "=", "GITHUB_API_URL", "+", "\"/users/\"", "+", "owner", "+", "\"/repos\"", "url_owner", "=", ...
The owner could be a org or a user. It waits if need to have rate limit. Also it fixes a djando issue changing - with _
[ "The", "owner", "could", "be", "a", "org", "or", "a", "user", ".", "It", "waits", "if", "need", "to", "have", "rate", "limit", ".", "Also", "it", "fixes", "a", "djando", "issue", "changing", "-", "with", "_" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/gh2k.py#L98-L123
19,674
chaoss/grimoirelab-elk
utils/gh2k.py
get_repositores
def get_repositores(owner_url, token, nrepos): """ owner could be an org or and user """ all_repos = [] url = owner_url while True: logging.debug("Getting repos from: %s" % (url)) try: r = requests.get(url, params=get_payload(), headers=get_headers(token)) r.raise_for_status() all_repos += r.json() logging.debug("Rate limit: %s" % (r.headers['X-RateLimit-Remaining'])) if 'next' not in r.links: break url = r.links['next']['url'] # Loving requests :) except requests.exceptions.ConnectionError: logging.error("Can not connect to GitHub") break # Remove forks nrepos_recent = [repo for repo in all_repos if not repo['fork']] # Sort by updated_at and limit to nrepos nrepos_sorted = sorted(nrepos_recent, key=lambda repo: parser.parse(repo['updated_at']), reverse=True) nrepos_sorted = nrepos_sorted[0:nrepos] # First the small repositories to feedback the user quickly nrepos_sorted = sorted(nrepos_sorted, key=lambda repo: repo['size']) for repo in nrepos_sorted: logging.debug("%s %i %s" % (repo['updated_at'], repo['size'], repo['name'])) return nrepos_sorted
python
def get_repositores(owner_url, token, nrepos): all_repos = [] url = owner_url while True: logging.debug("Getting repos from: %s" % (url)) try: r = requests.get(url, params=get_payload(), headers=get_headers(token)) r.raise_for_status() all_repos += r.json() logging.debug("Rate limit: %s" % (r.headers['X-RateLimit-Remaining'])) if 'next' not in r.links: break url = r.links['next']['url'] # Loving requests :) except requests.exceptions.ConnectionError: logging.error("Can not connect to GitHub") break # Remove forks nrepos_recent = [repo for repo in all_repos if not repo['fork']] # Sort by updated_at and limit to nrepos nrepos_sorted = sorted(nrepos_recent, key=lambda repo: parser.parse(repo['updated_at']), reverse=True) nrepos_sorted = nrepos_sorted[0:nrepos] # First the small repositories to feedback the user quickly nrepos_sorted = sorted(nrepos_sorted, key=lambda repo: repo['size']) for repo in nrepos_sorted: logging.debug("%s %i %s" % (repo['updated_at'], repo['size'], repo['name'])) return nrepos_sorted
[ "def", "get_repositores", "(", "owner_url", ",", "token", ",", "nrepos", ")", ":", "all_repos", "=", "[", "]", "url", "=", "owner_url", "while", "True", ":", "logging", ".", "debug", "(", "\"Getting repos from: %s\"", "%", "(", "url", ")", ")", "try", ":...
owner could be an org or and user
[ "owner", "could", "be", "an", "org", "or", "and", "user" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/gh2k.py#L126-L161
19,675
chaoss/grimoirelab-elk
utils/gh2k.py
publish_twitter
def publish_twitter(twitter_contact, owner): """ Publish in twitter the dashboard """ dashboard_url = CAULDRON_DASH_URL + "/%s" % (owner) tweet = "@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon" \ % (twitter_contact, owner, dashboard_url) status = quote_plus(tweet) oauth = get_oauth() r = requests.post(url="https://api.twitter.com/1.1/statuses/update.json?status=" + status, auth=oauth)
python
def publish_twitter(twitter_contact, owner): dashboard_url = CAULDRON_DASH_URL + "/%s" % (owner) tweet = "@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon" \ % (twitter_contact, owner, dashboard_url) status = quote_plus(tweet) oauth = get_oauth() r = requests.post(url="https://api.twitter.com/1.1/statuses/update.json?status=" + status, auth=oauth)
[ "def", "publish_twitter", "(", "twitter_contact", ",", "owner", ")", ":", "dashboard_url", "=", "CAULDRON_DASH_URL", "+", "\"/%s\"", "%", "(", "owner", ")", "tweet", "=", "\"@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon\"", "%", ...
Publish in twitter the dashboard
[ "Publish", "in", "twitter", "the", "dashboard" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/gh2k.py#L253-L260
19,676
chaoss/grimoirelab-elk
grimoire_elk/raw/mediawiki.py
MediaWikiOcean.get_perceval_params_from_url
def get_perceval_params_from_url(cls, urls): """ Get the perceval params given the URLs for the data source """ params = [] dparam = cls.get_arthur_params_from_url(urls) params.append(dparam["url"]) return params
python
def get_perceval_params_from_url(cls, urls): params = [] dparam = cls.get_arthur_params_from_url(urls) params.append(dparam["url"]) return params
[ "def", "get_perceval_params_from_url", "(", "cls", ",", "urls", ")", ":", "params", "=", "[", "]", "dparam", "=", "cls", ".", "get_arthur_params_from_url", "(", "urls", ")", "params", ".", "append", "(", "dparam", "[", "\"url\"", "]", ")", "return", "param...
Get the perceval params given the URLs for the data source
[ "Get", "the", "perceval", "params", "given", "the", "URLs", "for", "the", "data", "source" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/raw/mediawiki.py#L66-L73
19,677
chaoss/grimoirelab-elk
grimoire_elk/enriched/sortinghat_gelk.py
SortingHat.add_identity
def add_identity(cls, db, identity, backend): """ Load and identity list from backend in Sorting Hat """ uuid = None try: uuid = api.add_identity(db, backend, identity['email'], identity['name'], identity['username']) logger.debug("New sortinghat identity %s %s,%s,%s ", uuid, identity['username'], identity['name'], identity['email']) profile = {"name": identity['name'] if identity['name'] else identity['username'], "email": identity['email']} api.edit_profile(db, uuid, **profile) except AlreadyExistsError as ex: uuid = ex.eid except InvalidValueError as ex: logger.warning("Trying to add a None identity. Ignoring it.") except UnicodeEncodeError as ex: logger.warning("UnicodeEncodeError. Ignoring it. %s %s %s", identity['email'], identity['name'], identity['username']) except Exception as ex: logger.warning("Unknown exception adding identity. Ignoring it. %s %s %s", identity['email'], identity['name'], identity['username'], exc_info=True) if 'company' in identity and identity['company'] is not None: try: api.add_organization(db, identity['company']) api.add_enrollment(db, uuid, identity['company'], datetime(1900, 1, 1), datetime(2100, 1, 1)) except AlreadyExistsError: pass return uuid
python
def add_identity(cls, db, identity, backend): uuid = None try: uuid = api.add_identity(db, backend, identity['email'], identity['name'], identity['username']) logger.debug("New sortinghat identity %s %s,%s,%s ", uuid, identity['username'], identity['name'], identity['email']) profile = {"name": identity['name'] if identity['name'] else identity['username'], "email": identity['email']} api.edit_profile(db, uuid, **profile) except AlreadyExistsError as ex: uuid = ex.eid except InvalidValueError as ex: logger.warning("Trying to add a None identity. Ignoring it.") except UnicodeEncodeError as ex: logger.warning("UnicodeEncodeError. Ignoring it. %s %s %s", identity['email'], identity['name'], identity['username']) except Exception as ex: logger.warning("Unknown exception adding identity. Ignoring it. %s %s %s", identity['email'], identity['name'], identity['username'], exc_info=True) if 'company' in identity and identity['company'] is not None: try: api.add_organization(db, identity['company']) api.add_enrollment(db, uuid, identity['company'], datetime(1900, 1, 1), datetime(2100, 1, 1)) except AlreadyExistsError: pass return uuid
[ "def", "add_identity", "(", "cls", ",", "db", ",", "identity", ",", "backend", ")", ":", "uuid", "=", "None", "try", ":", "uuid", "=", "api", ".", "add_identity", "(", "db", ",", "backend", ",", "identity", "[", "'email'", "]", ",", "identity", "[", ...
Load and identity list from backend in Sorting Hat
[ "Load", "and", "identity", "list", "from", "backend", "in", "Sorting", "Hat" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/sortinghat_gelk.py#L64-L102
19,678
chaoss/grimoirelab-elk
grimoire_elk/enriched/sortinghat_gelk.py
SortingHat.add_identities
def add_identities(cls, db, identities, backend): """ Load identities list from backend in Sorting Hat """ logger.info("Adding the identities to SortingHat") total = 0 for identity in identities: try: cls.add_identity(db, identity, backend) total += 1 except Exception as e: logger.error("Unexcepted error when adding identities: %s" % e) continue logger.info("Total identities added to SH: %i", total)
python
def add_identities(cls, db, identities, backend): logger.info("Adding the identities to SortingHat") total = 0 for identity in identities: try: cls.add_identity(db, identity, backend) total += 1 except Exception as e: logger.error("Unexcepted error when adding identities: %s" % e) continue logger.info("Total identities added to SH: %i", total)
[ "def", "add_identities", "(", "cls", ",", "db", ",", "identities", ",", "backend", ")", ":", "logger", ".", "info", "(", "\"Adding the identities to SortingHat\"", ")", "total", "=", "0", "for", "identity", "in", "identities", ":", "try", ":", "cls", ".", ...
Load identities list from backend in Sorting Hat
[ "Load", "identities", "list", "from", "backend", "in", "Sorting", "Hat" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/sortinghat_gelk.py#L105-L120
19,679
chaoss/grimoirelab-elk
grimoire_elk/enriched/sortinghat_gelk.py
SortingHat.remove_identity
def remove_identity(cls, sh_db, ident_id): """Delete an identity from SortingHat. :param sh_db: SortingHat database :param ident_id: identity identifier """ success = False try: api.delete_identity(sh_db, ident_id) logger.debug("Identity %s deleted", ident_id) success = True except Exception as e: logger.debug("Identity not deleted due to %s", str(e)) return success
python
def remove_identity(cls, sh_db, ident_id): success = False try: api.delete_identity(sh_db, ident_id) logger.debug("Identity %s deleted", ident_id) success = True except Exception as e: logger.debug("Identity not deleted due to %s", str(e)) return success
[ "def", "remove_identity", "(", "cls", ",", "sh_db", ",", "ident_id", ")", ":", "success", "=", "False", "try", ":", "api", ".", "delete_identity", "(", "sh_db", ",", "ident_id", ")", "logger", ".", "debug", "(", "\"Identity %s deleted\"", ",", "ident_id", ...
Delete an identity from SortingHat. :param sh_db: SortingHat database :param ident_id: identity identifier
[ "Delete", "an", "identity", "from", "SortingHat", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/sortinghat_gelk.py#L123-L137
19,680
chaoss/grimoirelab-elk
grimoire_elk/enriched/sortinghat_gelk.py
SortingHat.remove_unique_identity
def remove_unique_identity(cls, sh_db, uuid): """Delete a unique identity from SortingHat. :param sh_db: SortingHat database :param uuid: Unique identity identifier """ success = False try: api.delete_unique_identity(sh_db, uuid) logger.debug("Unique identity %s deleted", uuid) success = True except Exception as e: logger.debug("Unique identity not deleted due to %s", str(e)) return success
python
def remove_unique_identity(cls, sh_db, uuid): success = False try: api.delete_unique_identity(sh_db, uuid) logger.debug("Unique identity %s deleted", uuid) success = True except Exception as e: logger.debug("Unique identity not deleted due to %s", str(e)) return success
[ "def", "remove_unique_identity", "(", "cls", ",", "sh_db", ",", "uuid", ")", ":", "success", "=", "False", "try", ":", "api", ".", "delete_unique_identity", "(", "sh_db", ",", "uuid", ")", "logger", ".", "debug", "(", "\"Unique identity %s deleted\"", ",", "...
Delete a unique identity from SortingHat. :param sh_db: SortingHat database :param uuid: Unique identity identifier
[ "Delete", "a", "unique", "identity", "from", "SortingHat", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/sortinghat_gelk.py#L140-L154
19,681
chaoss/grimoirelab-elk
grimoire_elk/enriched/sortinghat_gelk.py
SortingHat.unique_identities
def unique_identities(cls, sh_db): """List the unique identities available in SortingHat. :param sh_db: SortingHat database """ try: for unique_identity in api.unique_identities(sh_db): yield unique_identity except Exception as e: logger.debug("Unique identities not returned from SortingHat due to %s", str(e))
python
def unique_identities(cls, sh_db): try: for unique_identity in api.unique_identities(sh_db): yield unique_identity except Exception as e: logger.debug("Unique identities not returned from SortingHat due to %s", str(e))
[ "def", "unique_identities", "(", "cls", ",", "sh_db", ")", ":", "try", ":", "for", "unique_identity", "in", "api", ".", "unique_identities", "(", "sh_db", ")", ":", "yield", "unique_identity", "except", "Exception", "as", "e", ":", "logger", ".", "debug", ...
List the unique identities available in SortingHat. :param sh_db: SortingHat database
[ "List", "the", "unique", "identities", "available", "in", "SortingHat", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/sortinghat_gelk.py#L157-L166
19,682
chaoss/grimoirelab-elk
grimoire_elk/enriched/puppetforge.py
PuppetForgeEnrich.get_rich_events
def get_rich_events(self, item): """ Get the enriched events related to a module """ module = item['data'] if not item['data']['releases']: return [] for release in item['data']['releases']: event = self.get_rich_item(item) # Update specific fields for this release event["uuid"] += "_" + release['slug'] event["author_url"] = 'https://forge.puppet.com/' + release['module']['owner']['username'] event["gravatar_id"] = release['module']['owner']['gravatar_id'] event["downloads"] = release['downloads'] event["slug"] = release['slug'] event["version"] = release['version'] event["uri"] = release['uri'] event["validation_score"] = release['validation_score'] event["homepage_url"] = None if 'project_page' in release['metadata']: event["homepage_url"] = release['metadata']['project_page'] event["issues_url"] = None if "issues_url" in release['metadata']: event["issues_url"] = release['metadata']['issues_url'] event["tags"] = release['tags'] event["license"] = release['metadata']['license'] event["source_url"] = release['metadata']['source'] event["summary"] = release['metadata']['summary'] event["metadata__updated_on"] = parser.parse(release['updated_at']).isoformat() if self.sortinghat: release["metadata__updated_on"] = event["metadata__updated_on"] # Needed in get_item_sh logic event.update(self.get_item_sh(release)) if self.prjs_map: event.update(self.get_item_project(event)) event.update(self.get_grimoire_fields(release["created_at"], "release")) yield event
python
def get_rich_events(self, item): module = item['data'] if not item['data']['releases']: return [] for release in item['data']['releases']: event = self.get_rich_item(item) # Update specific fields for this release event["uuid"] += "_" + release['slug'] event["author_url"] = 'https://forge.puppet.com/' + release['module']['owner']['username'] event["gravatar_id"] = release['module']['owner']['gravatar_id'] event["downloads"] = release['downloads'] event["slug"] = release['slug'] event["version"] = release['version'] event["uri"] = release['uri'] event["validation_score"] = release['validation_score'] event["homepage_url"] = None if 'project_page' in release['metadata']: event["homepage_url"] = release['metadata']['project_page'] event["issues_url"] = None if "issues_url" in release['metadata']: event["issues_url"] = release['metadata']['issues_url'] event["tags"] = release['tags'] event["license"] = release['metadata']['license'] event["source_url"] = release['metadata']['source'] event["summary"] = release['metadata']['summary'] event["metadata__updated_on"] = parser.parse(release['updated_at']).isoformat() if self.sortinghat: release["metadata__updated_on"] = event["metadata__updated_on"] # Needed in get_item_sh logic event.update(self.get_item_sh(release)) if self.prjs_map: event.update(self.get_item_project(event)) event.update(self.get_grimoire_fields(release["created_at"], "release")) yield event
[ "def", "get_rich_events", "(", "self", ",", "item", ")", ":", "module", "=", "item", "[", "'data'", "]", "if", "not", "item", "[", "'data'", "]", "[", "'releases'", "]", ":", "return", "[", "]", "for", "release", "in", "item", "[", "'data'", "]", "...
Get the enriched events related to a module
[ "Get", "the", "enriched", "events", "related", "to", "a", "module" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/puppetforge.py#L135-L176
19,683
chaoss/grimoirelab-elk
grimoire_elk/enriched/database.py
Database._connect
def _connect(self): """Connect to the MySQL database. """ try: db = pymysql.connect(user=self.user, passwd=self.passwd, host=self.host, port=self.port, db=self.shdb, use_unicode=True) return db, db.cursor() except Exception: logger.error("Database connection error") raise
python
def _connect(self): try: db = pymysql.connect(user=self.user, passwd=self.passwd, host=self.host, port=self.port, db=self.shdb, use_unicode=True) return db, db.cursor() except Exception: logger.error("Database connection error") raise
[ "def", "_connect", "(", "self", ")", ":", "try", ":", "db", "=", "pymysql", ".", "connect", "(", "user", "=", "self", ".", "user", ",", "passwd", "=", "self", ".", "passwd", ",", "host", "=", "self", ".", "host", ",", "port", "=", "self", ".", ...
Connect to the MySQL database.
[ "Connect", "to", "the", "MySQL", "database", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/database.py#L44-L55
19,684
chaoss/grimoirelab-elk
grimoire_elk/elk.py
refresh_identities
def refresh_identities(enrich_backend, author_field=None, author_values=None): """Refresh identities in enriched index. Retrieve items from the enriched index corresponding to enrich_backend, and update their identities information, with fresh data from the SortingHat database. Instead of the whole index, only items matching the filter_author filter are fitered, if that parameters is not None. :param enrich_backend: enriched backend to update :param author_field: field to match items authored by a user :param author_values: values of the authored field to match items """ def update_items(new_filter_author): for eitem in enrich_backend.fetch(new_filter_author): roles = None try: roles = enrich_backend.roles except AttributeError: pass new_identities = enrich_backend.get_item_sh_from_id(eitem, roles) eitem.update(new_identities) yield eitem logger.debug("Refreshing identities fields from %s", enrich_backend.elastic.anonymize_url(enrich_backend.elastic.index_url)) total = 0 max_ids = enrich_backend.elastic.max_items_clause logger.debug('Refreshing identities') if author_field is None: # No filter, update all items for item in update_items(None): yield item total += 1 else: to_refresh = [] for author_value in author_values: to_refresh.append(author_value) if len(to_refresh) > max_ids: filter_author = {"name": author_field, "value": to_refresh} for item in update_items(filter_author): yield item total += 1 to_refresh = [] if len(to_refresh) > 0: filter_author = {"name": author_field, "value": to_refresh} for item in update_items(filter_author): yield item total += 1 logger.info("Total eitems refreshed for identities fields %i", total)
python
def refresh_identities(enrich_backend, author_field=None, author_values=None): def update_items(new_filter_author): for eitem in enrich_backend.fetch(new_filter_author): roles = None try: roles = enrich_backend.roles except AttributeError: pass new_identities = enrich_backend.get_item_sh_from_id(eitem, roles) eitem.update(new_identities) yield eitem logger.debug("Refreshing identities fields from %s", enrich_backend.elastic.anonymize_url(enrich_backend.elastic.index_url)) total = 0 max_ids = enrich_backend.elastic.max_items_clause logger.debug('Refreshing identities') if author_field is None: # No filter, update all items for item in update_items(None): yield item total += 1 else: to_refresh = [] for author_value in author_values: to_refresh.append(author_value) if len(to_refresh) > max_ids: filter_author = {"name": author_field, "value": to_refresh} for item in update_items(filter_author): yield item total += 1 to_refresh = [] if len(to_refresh) > 0: filter_author = {"name": author_field, "value": to_refresh} for item in update_items(filter_author): yield item total += 1 logger.info("Total eitems refreshed for identities fields %i", total)
[ "def", "refresh_identities", "(", "enrich_backend", ",", "author_field", "=", "None", ",", "author_values", "=", "None", ")", ":", "def", "update_items", "(", "new_filter_author", ")", ":", "for", "eitem", "in", "enrich_backend", ".", "fetch", "(", "new_filter_a...
Refresh identities in enriched index. Retrieve items from the enriched index corresponding to enrich_backend, and update their identities information, with fresh data from the SortingHat database. Instead of the whole index, only items matching the filter_author filter are fitered, if that parameters is not None. :param enrich_backend: enriched backend to update :param author_field: field to match items authored by a user :param author_values: values of the authored field to match items
[ "Refresh", "identities", "in", "enriched", "index", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L309-L372
19,685
chaoss/grimoirelab-elk
grimoire_elk/elk.py
get_ocean_backend
def get_ocean_backend(backend_cmd, enrich_backend, no_incremental, filter_raw=None, filter_raw_should=None): """ Get the ocean backend configured to start from the last enriched date """ if no_incremental: last_enrich = None else: last_enrich = get_last_enrich(backend_cmd, enrich_backend, filter_raw=filter_raw) logger.debug("Last enrichment: %s", last_enrich) backend = None connector = get_connectors()[enrich_backend.get_connector_name()] if backend_cmd: backend_cmd = init_backend(backend_cmd) backend = backend_cmd.backend signature = inspect.signature(backend.fetch) if 'from_date' in signature.parameters: ocean_backend = connector[1](backend, from_date=last_enrich) elif 'offset' in signature.parameters: ocean_backend = connector[1](backend, offset=last_enrich) else: if last_enrich: ocean_backend = connector[1](backend, from_date=last_enrich) else: ocean_backend = connector[1](backend) else: # We can have params for non perceval backends also params = enrich_backend.backend_params if params: try: date_pos = params.index('--from-date') last_enrich = parser.parse(params[date_pos + 1]) except ValueError: pass if last_enrich: ocean_backend = connector[1](backend, from_date=last_enrich) else: ocean_backend = connector[1](backend) if filter_raw: ocean_backend.set_filter_raw(filter_raw) if filter_raw_should: ocean_backend.set_filter_raw_should(filter_raw_should) return ocean_backend
python
def get_ocean_backend(backend_cmd, enrich_backend, no_incremental, filter_raw=None, filter_raw_should=None): if no_incremental: last_enrich = None else: last_enrich = get_last_enrich(backend_cmd, enrich_backend, filter_raw=filter_raw) logger.debug("Last enrichment: %s", last_enrich) backend = None connector = get_connectors()[enrich_backend.get_connector_name()] if backend_cmd: backend_cmd = init_backend(backend_cmd) backend = backend_cmd.backend signature = inspect.signature(backend.fetch) if 'from_date' in signature.parameters: ocean_backend = connector[1](backend, from_date=last_enrich) elif 'offset' in signature.parameters: ocean_backend = connector[1](backend, offset=last_enrich) else: if last_enrich: ocean_backend = connector[1](backend, from_date=last_enrich) else: ocean_backend = connector[1](backend) else: # We can have params for non perceval backends also params = enrich_backend.backend_params if params: try: date_pos = params.index('--from-date') last_enrich = parser.parse(params[date_pos + 1]) except ValueError: pass if last_enrich: ocean_backend = connector[1](backend, from_date=last_enrich) else: ocean_backend = connector[1](backend) if filter_raw: ocean_backend.set_filter_raw(filter_raw) if filter_raw_should: ocean_backend.set_filter_raw_should(filter_raw_should) return ocean_backend
[ "def", "get_ocean_backend", "(", "backend_cmd", ",", "enrich_backend", ",", "no_incremental", ",", "filter_raw", "=", "None", ",", "filter_raw_should", "=", "None", ")", ":", "if", "no_incremental", ":", "last_enrich", "=", "None", "else", ":", "last_enrich", "=...
Get the ocean backend configured to start from the last enriched date
[ "Get", "the", "ocean", "backend", "configured", "to", "start", "from", "the", "last", "enriched", "date" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L439-L487
19,686
chaoss/grimoirelab-elk
grimoire_elk/elk.py
do_studies
def do_studies(ocean_backend, enrich_backend, studies_args, retention_time=None): """Execute studies related to a given enrich backend. If `retention_time` is not None, the study data is deleted based on the number of minutes declared in `retention_time`. :param ocean_backend: backend to access raw items :param enrich_backend: backend to access enriched items :param retention_time: maximum number of minutes wrt the current date to retain the data :param studies_args: list of studies to be executed """ for study in enrich_backend.studies: selected_studies = [(s['name'], s['params']) for s in studies_args if s['type'] == study.__name__] for (name, params) in selected_studies: logger.info("Starting study: %s, params %s", name, str(params)) try: study(ocean_backend, enrich_backend, **params) except Exception as e: logger.error("Problem executing study %s, %s", name, str(e)) raise e # identify studies which creates other indexes. If the study is onion, # it can be ignored since the index is recreated every week if name.startswith('enrich_onion'): continue index_params = [p for p in params if 'out_index' in p] for ip in index_params: index_name = params[ip] elastic = get_elastic(enrich_backend.elastic_url, index_name) elastic.delete_items(retention_time)
python
def do_studies(ocean_backend, enrich_backend, studies_args, retention_time=None): for study in enrich_backend.studies: selected_studies = [(s['name'], s['params']) for s in studies_args if s['type'] == study.__name__] for (name, params) in selected_studies: logger.info("Starting study: %s, params %s", name, str(params)) try: study(ocean_backend, enrich_backend, **params) except Exception as e: logger.error("Problem executing study %s, %s", name, str(e)) raise e # identify studies which creates other indexes. If the study is onion, # it can be ignored since the index is recreated every week if name.startswith('enrich_onion'): continue index_params = [p for p in params if 'out_index' in p] for ip in index_params: index_name = params[ip] elastic = get_elastic(enrich_backend.elastic_url, index_name) elastic.delete_items(retention_time)
[ "def", "do_studies", "(", "ocean_backend", ",", "enrich_backend", ",", "studies_args", ",", "retention_time", "=", "None", ")", ":", "for", "study", "in", "enrich_backend", ".", "studies", ":", "selected_studies", "=", "[", "(", "s", "[", "'name'", "]", ",",...
Execute studies related to a given enrich backend. If `retention_time` is not None, the study data is deleted based on the number of minutes declared in `retention_time`. :param ocean_backend: backend to access raw items :param enrich_backend: backend to access enriched items :param retention_time: maximum number of minutes wrt the current date to retain the data :param studies_args: list of studies to be executed
[ "Execute", "studies", "related", "to", "a", "given", "enrich", "backend", ".", "If", "retention_time", "is", "not", "None", "the", "study", "data", "is", "deleted", "based", "on", "the", "number", "of", "minutes", "declared", "in", "retention_time", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L490-L521
19,687
chaoss/grimoirelab-elk
grimoire_elk/elk.py
delete_orphan_unique_identities
def delete_orphan_unique_identities(es, sortinghat_db, current_data_source, active_data_sources): """Delete all unique identities which appear in SortingHat, but not in the IDENTITIES_INDEX. :param es: ElasticSearchDSL object :param sortinghat_db: instance of the SortingHat database :param current_data_source: current data source :param active_data_sources: list of active data sources """ def get_uuids_in_index(target_uuids): """Find a set of uuids in IDENTITIES_INDEX and return them if exist. :param target_uuids: target uuids """ page = es.search( index=IDENTITIES_INDEX, scroll="360m", size=SIZE_SCROLL_IDENTITIES_INDEX, body={ "query": { "bool": { "filter": [ { "terms": { "sh_uuid": target_uuids } } ] } } } ) hits = [] if page['hits']['total'] != 0: hits = page['hits']['hits'] return hits def delete_unique_identities(target_uuids): """Delete a list of uuids from SortingHat. :param target_uuids: uuids to be deleted """ count = 0 for uuid in target_uuids: success = SortingHat.remove_unique_identity(sortinghat_db, uuid) count = count + 1 if success else count return count def delete_identities(unique_ident, data_sources): """Remove the identities in non active data sources. :param unique_ident: unique identity object :param data_sources: target data sources """ count = 0 for ident in unique_ident.identities: if ident.source not in data_sources: success = SortingHat.remove_identity(sortinghat_db, ident.id) count = count + 1 if success else count return count def has_identities_in_data_sources(unique_ident, data_sources): """Check if a unique identity has identities in a set of data sources. :param unique_ident: unique identity object :param data_sources: target data sources """ in_active = False for ident in unique_ident.identities: if ident.source in data_sources: in_active = True break return in_active deleted_unique_identities = 0 deleted_identities = 0 uuids_to_process = [] # Collect all unique identities for unique_identity in SortingHat.unique_identities(sortinghat_db): # Remove a unique identity if all its identities are in non active data source if not has_identities_in_data_sources(unique_identity, active_data_sources): deleted_unique_identities += delete_unique_identities([unique_identity.uuid]) continue # Remove the identities of non active data source for a given unique identity deleted_identities += delete_identities(unique_identity, active_data_sources) # Process only the unique identities that include the current data source, since # it may be that unique identities in other data source have not been # added yet to IDENTITIES_INDEX if not has_identities_in_data_sources(unique_identity, [current_data_source]): continue # Add the uuid to the list to check its existence in the IDENTITIES_INDEX uuids_to_process.append(unique_identity.uuid) # Process the uuids in block of SIZE_SCROLL_IDENTITIES_INDEX if len(uuids_to_process) != SIZE_SCROLL_IDENTITIES_INDEX: continue # Find which uuids to be processed exist in IDENTITIES_INDEX results = get_uuids_in_index(uuids_to_process) uuids_found = [item['_source']['sh_uuid'] for item in results] # Find the uuids which exist in SortingHat but not in IDENTITIES_INDEX orphan_uuids = set(uuids_to_process) - set(uuids_found) # Delete the orphan uuids from SortingHat deleted_unique_identities += delete_unique_identities(orphan_uuids) # Reset the list uuids_to_process = [] # Check that no uuids have been left to process if uuids_to_process: # Find which uuids to be processed exist in IDENTITIES_INDEX results = get_uuids_in_index(uuids_to_process) uuids_found = [item['_source']['sh_uuid'] for item in results] # Find the uuids which exist in SortingHat but not in IDENTITIES_INDEX orphan_uuids = set(uuids_to_process) - set(uuids_found) # Delete the orphan uuids from SortingHat deleted_unique_identities += delete_unique_identities(orphan_uuids) logger.debug("[identities retention] Total orphan unique identities deleted from SH: %i", deleted_unique_identities) logger.debug("[identities retention] Total identities in non-active data sources deleted from SH: %i", deleted_identities)
python
def delete_orphan_unique_identities(es, sortinghat_db, current_data_source, active_data_sources): def get_uuids_in_index(target_uuids): """Find a set of uuids in IDENTITIES_INDEX and return them if exist. :param target_uuids: target uuids """ page = es.search( index=IDENTITIES_INDEX, scroll="360m", size=SIZE_SCROLL_IDENTITIES_INDEX, body={ "query": { "bool": { "filter": [ { "terms": { "sh_uuid": target_uuids } } ] } } } ) hits = [] if page['hits']['total'] != 0: hits = page['hits']['hits'] return hits def delete_unique_identities(target_uuids): """Delete a list of uuids from SortingHat. :param target_uuids: uuids to be deleted """ count = 0 for uuid in target_uuids: success = SortingHat.remove_unique_identity(sortinghat_db, uuid) count = count + 1 if success else count return count def delete_identities(unique_ident, data_sources): """Remove the identities in non active data sources. :param unique_ident: unique identity object :param data_sources: target data sources """ count = 0 for ident in unique_ident.identities: if ident.source not in data_sources: success = SortingHat.remove_identity(sortinghat_db, ident.id) count = count + 1 if success else count return count def has_identities_in_data_sources(unique_ident, data_sources): """Check if a unique identity has identities in a set of data sources. :param unique_ident: unique identity object :param data_sources: target data sources """ in_active = False for ident in unique_ident.identities: if ident.source in data_sources: in_active = True break return in_active deleted_unique_identities = 0 deleted_identities = 0 uuids_to_process = [] # Collect all unique identities for unique_identity in SortingHat.unique_identities(sortinghat_db): # Remove a unique identity if all its identities are in non active data source if not has_identities_in_data_sources(unique_identity, active_data_sources): deleted_unique_identities += delete_unique_identities([unique_identity.uuid]) continue # Remove the identities of non active data source for a given unique identity deleted_identities += delete_identities(unique_identity, active_data_sources) # Process only the unique identities that include the current data source, since # it may be that unique identities in other data source have not been # added yet to IDENTITIES_INDEX if not has_identities_in_data_sources(unique_identity, [current_data_source]): continue # Add the uuid to the list to check its existence in the IDENTITIES_INDEX uuids_to_process.append(unique_identity.uuid) # Process the uuids in block of SIZE_SCROLL_IDENTITIES_INDEX if len(uuids_to_process) != SIZE_SCROLL_IDENTITIES_INDEX: continue # Find which uuids to be processed exist in IDENTITIES_INDEX results = get_uuids_in_index(uuids_to_process) uuids_found = [item['_source']['sh_uuid'] for item in results] # Find the uuids which exist in SortingHat but not in IDENTITIES_INDEX orphan_uuids = set(uuids_to_process) - set(uuids_found) # Delete the orphan uuids from SortingHat deleted_unique_identities += delete_unique_identities(orphan_uuids) # Reset the list uuids_to_process = [] # Check that no uuids have been left to process if uuids_to_process: # Find which uuids to be processed exist in IDENTITIES_INDEX results = get_uuids_in_index(uuids_to_process) uuids_found = [item['_source']['sh_uuid'] for item in results] # Find the uuids which exist in SortingHat but not in IDENTITIES_INDEX orphan_uuids = set(uuids_to_process) - set(uuids_found) # Delete the orphan uuids from SortingHat deleted_unique_identities += delete_unique_identities(orphan_uuids) logger.debug("[identities retention] Total orphan unique identities deleted from SH: %i", deleted_unique_identities) logger.debug("[identities retention] Total identities in non-active data sources deleted from SH: %i", deleted_identities)
[ "def", "delete_orphan_unique_identities", "(", "es", ",", "sortinghat_db", ",", "current_data_source", ",", "active_data_sources", ")", ":", "def", "get_uuids_in_index", "(", "target_uuids", ")", ":", "\"\"\"Find a set of uuids in IDENTITIES_INDEX and return them if exist.\n\n ...
Delete all unique identities which appear in SortingHat, but not in the IDENTITIES_INDEX. :param es: ElasticSearchDSL object :param sortinghat_db: instance of the SortingHat database :param current_data_source: current data source :param active_data_sources: list of active data sources
[ "Delete", "all", "unique", "identities", "which", "appear", "in", "SortingHat", "but", "not", "in", "the", "IDENTITIES_INDEX", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L671-L804
19,688
chaoss/grimoirelab-elk
grimoire_elk/elk.py
delete_inactive_unique_identities
def delete_inactive_unique_identities(es, sortinghat_db, before_date): """Select the unique identities not seen before `before_date` and delete them from SortingHat. :param es: ElasticSearchDSL object :param sortinghat_db: instance of the SortingHat database :param before_date: datetime str to filter the identities """ page = es.search( index=IDENTITIES_INDEX, scroll="360m", size=SIZE_SCROLL_IDENTITIES_INDEX, body={ "query": { "range": { "last_seen": { "lte": before_date } } } } ) sid = page['_scroll_id'] scroll_size = page['hits']['total'] if scroll_size == 0: logging.warning("[identities retention] No inactive identities found in %s after %s!", IDENTITIES_INDEX, before_date) return count = 0 while scroll_size > 0: for item in page['hits']['hits']: to_delete = item['_source']['sh_uuid'] success = SortingHat.remove_unique_identity(sortinghat_db, to_delete) # increment the number of deleted identities only if the corresponding command was successful count = count + 1 if success else count page = es.scroll(scroll_id=sid, scroll='60m') sid = page['_scroll_id'] scroll_size = len(page['hits']['hits']) logger.debug("[identities retention] Total inactive identities deleted from SH: %i", count)
python
def delete_inactive_unique_identities(es, sortinghat_db, before_date): page = es.search( index=IDENTITIES_INDEX, scroll="360m", size=SIZE_SCROLL_IDENTITIES_INDEX, body={ "query": { "range": { "last_seen": { "lte": before_date } } } } ) sid = page['_scroll_id'] scroll_size = page['hits']['total'] if scroll_size == 0: logging.warning("[identities retention] No inactive identities found in %s after %s!", IDENTITIES_INDEX, before_date) return count = 0 while scroll_size > 0: for item in page['hits']['hits']: to_delete = item['_source']['sh_uuid'] success = SortingHat.remove_unique_identity(sortinghat_db, to_delete) # increment the number of deleted identities only if the corresponding command was successful count = count + 1 if success else count page = es.scroll(scroll_id=sid, scroll='60m') sid = page['_scroll_id'] scroll_size = len(page['hits']['hits']) logger.debug("[identities retention] Total inactive identities deleted from SH: %i", count)
[ "def", "delete_inactive_unique_identities", "(", "es", ",", "sortinghat_db", ",", "before_date", ")", ":", "page", "=", "es", ".", "search", "(", "index", "=", "IDENTITIES_INDEX", ",", "scroll", "=", "\"360m\"", ",", "size", "=", "SIZE_SCROLL_IDENTITIES_INDEX", ...
Select the unique identities not seen before `before_date` and delete them from SortingHat. :param es: ElasticSearchDSL object :param sortinghat_db: instance of the SortingHat database :param before_date: datetime str to filter the identities
[ "Select", "the", "unique", "identities", "not", "seen", "before", "before_date", "and", "delete", "them", "from", "SortingHat", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L807-L851
19,689
chaoss/grimoirelab-elk
grimoire_elk/elk.py
retain_identities
def retain_identities(retention_time, es_enrichment_url, sortinghat_db, data_source, active_data_sources): """Select the unique identities not seen before `retention_time` and delete them from SortingHat. Furthermore, it deletes also the orphan unique identities, those ones stored in SortingHat but not in IDENTITIES_INDEX. :param retention_time: maximum number of minutes wrt the current date to retain the identities :param es_enrichment_url: URL of the ElasticSearch where the enriched data is stored :param sortinghat_db: instance of the SortingHat database :param data_source: target data source (e.g., git, github, slack) :param active_data_sources: list of active data sources """ before_date = get_diff_current_date(minutes=retention_time) before_date_str = before_date.isoformat() es = Elasticsearch([es_enrichment_url], timeout=120, max_retries=20, retry_on_timeout=True, verify_certs=False) # delete the unique identities which have not been seen after `before_date` delete_inactive_unique_identities(es, sortinghat_db, before_date_str) # delete the unique identities for a given data source which are not in the IDENTITIES_INDEX delete_orphan_unique_identities(es, sortinghat_db, data_source, active_data_sources)
python
def retain_identities(retention_time, es_enrichment_url, sortinghat_db, data_source, active_data_sources): before_date = get_diff_current_date(minutes=retention_time) before_date_str = before_date.isoformat() es = Elasticsearch([es_enrichment_url], timeout=120, max_retries=20, retry_on_timeout=True, verify_certs=False) # delete the unique identities which have not been seen after `before_date` delete_inactive_unique_identities(es, sortinghat_db, before_date_str) # delete the unique identities for a given data source which are not in the IDENTITIES_INDEX delete_orphan_unique_identities(es, sortinghat_db, data_source, active_data_sources)
[ "def", "retain_identities", "(", "retention_time", ",", "es_enrichment_url", ",", "sortinghat_db", ",", "data_source", ",", "active_data_sources", ")", ":", "before_date", "=", "get_diff_current_date", "(", "minutes", "=", "retention_time", ")", "before_date_str", "=", ...
Select the unique identities not seen before `retention_time` and delete them from SortingHat. Furthermore, it deletes also the orphan unique identities, those ones stored in SortingHat but not in IDENTITIES_INDEX. :param retention_time: maximum number of minutes wrt the current date to retain the identities :param es_enrichment_url: URL of the ElasticSearch where the enriched data is stored :param sortinghat_db: instance of the SortingHat database :param data_source: target data source (e.g., git, github, slack) :param active_data_sources: list of active data sources
[ "Select", "the", "unique", "identities", "not", "seen", "before", "retention_time", "and", "delete", "them", "from", "SortingHat", ".", "Furthermore", "it", "deletes", "also", "the", "orphan", "unique", "identities", "those", "ones", "stored", "in", "SortingHat", ...
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L854-L873
19,690
chaoss/grimoirelab-elk
grimoire_elk/elk.py
init_backend
def init_backend(backend_cmd): """Init backend within the backend_cmd""" try: backend_cmd.backend except AttributeError: parsed_args = vars(backend_cmd.parsed_args) init_args = find_signature_parameters(backend_cmd.BACKEND, parsed_args) backend_cmd.backend = backend_cmd.BACKEND(**init_args) return backend_cmd
python
def init_backend(backend_cmd): try: backend_cmd.backend except AttributeError: parsed_args = vars(backend_cmd.parsed_args) init_args = find_signature_parameters(backend_cmd.BACKEND, parsed_args) backend_cmd.backend = backend_cmd.BACKEND(**init_args) return backend_cmd
[ "def", "init_backend", "(", "backend_cmd", ")", ":", "try", ":", "backend_cmd", ".", "backend", "except", "AttributeError", ":", "parsed_args", "=", "vars", "(", "backend_cmd", ".", "parsed_args", ")", "init_args", "=", "find_signature_parameters", "(", "backend_c...
Init backend within the backend_cmd
[ "Init", "backend", "within", "the", "backend_cmd" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L876-L887
19,691
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch.safe_index
def safe_index(cls, unique_id): """ Return a valid elastic index generated from unique_id """ index = unique_id if unique_id: index = unique_id.replace("/", "_").lower() return index
python
def safe_index(cls, unique_id): index = unique_id if unique_id: index = unique_id.replace("/", "_").lower() return index
[ "def", "safe_index", "(", "cls", ",", "unique_id", ")", ":", "index", "=", "unique_id", "if", "unique_id", ":", "index", "=", "unique_id", ".", "replace", "(", "\"/\"", ",", "\"_\"", ")", ".", "lower", "(", ")", "return", "index" ]
Return a valid elastic index generated from unique_id
[ "Return", "a", "valid", "elastic", "index", "generated", "from", "unique_id" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L112-L117
19,692
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch._check_instance
def _check_instance(url, insecure): """Checks if there is an instance of Elasticsearch in url. Actually, it checks if GET on the url returns a JSON document with a field tagline "You know, for search", and a field version.number. :value url: url of the instance to check :value insecure: don't verify ssl connection (boolean) :returns: major version of Ellasticsearch, as string. """ res = grimoire_con(insecure).get(url) if res.status_code != 200: logger.error("Didn't get 200 OK from url %s", url) raise ElasticConnectException else: try: version_str = res.json()['version']['number'] version_major = version_str.split('.')[0] return version_major except Exception: logger.error("Could not read proper welcome message from url %s", ElasticSearch.anonymize_url(url)) logger.error("Message read: %s", res.text) raise ElasticConnectException
python
def _check_instance(url, insecure): res = grimoire_con(insecure).get(url) if res.status_code != 200: logger.error("Didn't get 200 OK from url %s", url) raise ElasticConnectException else: try: version_str = res.json()['version']['number'] version_major = version_str.split('.')[0] return version_major except Exception: logger.error("Could not read proper welcome message from url %s", ElasticSearch.anonymize_url(url)) logger.error("Message read: %s", res.text) raise ElasticConnectException
[ "def", "_check_instance", "(", "url", ",", "insecure", ")", ":", "res", "=", "grimoire_con", "(", "insecure", ")", ".", "get", "(", "url", ")", "if", "res", ".", "status_code", "!=", "200", ":", "logger", ".", "error", "(", "\"Didn't get 200 OK from url %s...
Checks if there is an instance of Elasticsearch in url. Actually, it checks if GET on the url returns a JSON document with a field tagline "You know, for search", and a field version.number. :value url: url of the instance to check :value insecure: don't verify ssl connection (boolean) :returns: major version of Ellasticsearch, as string.
[ "Checks", "if", "there", "is", "an", "instance", "of", "Elasticsearch", "in", "url", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L120-L145
19,693
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch.safe_put_bulk
def safe_put_bulk(self, url, bulk_json): """ Bulk PUT controlling unicode issues """ headers = {"Content-Type": "application/x-ndjson"} try: res = self.requests.put(url + '?refresh=true', data=bulk_json, headers=headers) res.raise_for_status() except UnicodeEncodeError: # Related to body.encode('iso-8859-1'). mbox data logger.error("Encondig error ... converting bulk to iso-8859-1") bulk_json = bulk_json.encode('iso-8859-1', 'ignore') res = self.requests.put(url, data=bulk_json, headers=headers) res.raise_for_status() result = res.json() failed_items = [] if result['errors']: # Due to multiple errors that may be thrown when inserting bulk data, only the first error is returned failed_items = [item['index'] for item in result['items'] if 'error' in item['index']] error = str(failed_items[0]['error']) logger.error("Failed to insert data to ES: %s, %s", error, self.anonymize_url(url)) inserted_items = len(result['items']) - len(failed_items) # The exception is currently not thrown to avoid stopping ocean uploading processes try: if failed_items: raise ELKError(cause=error) except ELKError: pass logger.debug("%i items uploaded to ES (%s)", inserted_items, self.anonymize_url(url)) return inserted_items
python
def safe_put_bulk(self, url, bulk_json): headers = {"Content-Type": "application/x-ndjson"} try: res = self.requests.put(url + '?refresh=true', data=bulk_json, headers=headers) res.raise_for_status() except UnicodeEncodeError: # Related to body.encode('iso-8859-1'). mbox data logger.error("Encondig error ... converting bulk to iso-8859-1") bulk_json = bulk_json.encode('iso-8859-1', 'ignore') res = self.requests.put(url, data=bulk_json, headers=headers) res.raise_for_status() result = res.json() failed_items = [] if result['errors']: # Due to multiple errors that may be thrown when inserting bulk data, only the first error is returned failed_items = [item['index'] for item in result['items'] if 'error' in item['index']] error = str(failed_items[0]['error']) logger.error("Failed to insert data to ES: %s, %s", error, self.anonymize_url(url)) inserted_items = len(result['items']) - len(failed_items) # The exception is currently not thrown to avoid stopping ocean uploading processes try: if failed_items: raise ELKError(cause=error) except ELKError: pass logger.debug("%i items uploaded to ES (%s)", inserted_items, self.anonymize_url(url)) return inserted_items
[ "def", "safe_put_bulk", "(", "self", ",", "url", ",", "bulk_json", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/x-ndjson\"", "}", "try", ":", "res", "=", "self", ".", "requests", ".", "put", "(", "url", "+", "'?refresh=true'", ","...
Bulk PUT controlling unicode issues
[ "Bulk", "PUT", "controlling", "unicode", "issues" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L153-L187
19,694
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch.all_es_aliases
def all_es_aliases(self): """List all aliases used in ES""" r = self.requests.get(self.url + "/_aliases", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.warning("Something went wrong when retrieving aliases on %s.", self.anonymize_url(self.index_url)) logger.warning(ex) return aliases = [] for index in r.json().keys(): aliases.extend(list(r.json()[index]['aliases'].keys())) aliases = list(set(aliases)) return aliases
python
def all_es_aliases(self): r = self.requests.get(self.url + "/_aliases", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.warning("Something went wrong when retrieving aliases on %s.", self.anonymize_url(self.index_url)) logger.warning(ex) return aliases = [] for index in r.json().keys(): aliases.extend(list(r.json()[index]['aliases'].keys())) aliases = list(set(aliases)) return aliases
[ "def", "all_es_aliases", "(", "self", ")", ":", "r", "=", "self", ".", "requests", ".", "get", "(", "self", ".", "url", "+", "\"/_aliases\"", ",", "headers", "=", "HEADER_JSON", ",", "verify", "=", "False", ")", "try", ":", "r", ".", "raise_for_status"...
List all aliases used in ES
[ "List", "all", "aliases", "used", "in", "ES" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L189-L206
19,695
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch.list_aliases
def list_aliases(self): """List aliases linked to the index""" # check alias doesn't exist r = self.requests.get(self.index_url + "/_alias", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.warning("Something went wrong when retrieving aliases on %s.", self.anonymize_url(self.index_url)) logger.warning(ex) return aliases = r.json()[self.index]['aliases'] return aliases
python
def list_aliases(self): # check alias doesn't exist r = self.requests.get(self.index_url + "/_alias", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.warning("Something went wrong when retrieving aliases on %s.", self.anonymize_url(self.index_url)) logger.warning(ex) return aliases = r.json()[self.index]['aliases'] return aliases
[ "def", "list_aliases", "(", "self", ")", ":", "# check alias doesn't exist", "r", "=", "self", ".", "requests", ".", "get", "(", "self", ".", "index_url", "+", "\"/_alias\"", ",", "headers", "=", "HEADER_JSON", ",", "verify", "=", "False", ")", "try", ":",...
List aliases linked to the index
[ "List", "aliases", "linked", "to", "the", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L208-L222
19,696
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch.bulk_upload
def bulk_upload(self, items, field_id): """Upload in controlled packs items to ES using bulk API""" current = 0 new_items = 0 # total items added with bulk bulk_json = "" if not items: return new_items url = self.index_url + '/items/_bulk' logger.debug("Adding items to %s (in %i packs)", self.anonymize_url(url), self.max_items_bulk) task_init = time() for item in items: if current >= self.max_items_bulk: task_init = time() new_items += self.safe_put_bulk(url, bulk_json) current = 0 json_size = sys.getsizeof(bulk_json) / (1024 * 1024) logger.debug("bulk packet sent (%.2f sec, %i total, %.2f MB)" % (time() - task_init, new_items, json_size)) bulk_json = "" data_json = json.dumps(item) bulk_json += '{"index" : {"_id" : "%s" } }\n' % (item[field_id]) bulk_json += data_json + "\n" # Bulk document current += 1 if current > 0: new_items += self.safe_put_bulk(url, bulk_json) json_size = sys.getsizeof(bulk_json) / (1024 * 1024) logger.debug("bulk packet sent (%.2f sec prev, %i total, %.2f MB)" % (time() - task_init, new_items, json_size)) return new_items
python
def bulk_upload(self, items, field_id): current = 0 new_items = 0 # total items added with bulk bulk_json = "" if not items: return new_items url = self.index_url + '/items/_bulk' logger.debug("Adding items to %s (in %i packs)", self.anonymize_url(url), self.max_items_bulk) task_init = time() for item in items: if current >= self.max_items_bulk: task_init = time() new_items += self.safe_put_bulk(url, bulk_json) current = 0 json_size = sys.getsizeof(bulk_json) / (1024 * 1024) logger.debug("bulk packet sent (%.2f sec, %i total, %.2f MB)" % (time() - task_init, new_items, json_size)) bulk_json = "" data_json = json.dumps(item) bulk_json += '{"index" : {"_id" : "%s" } }\n' % (item[field_id]) bulk_json += data_json + "\n" # Bulk document current += 1 if current > 0: new_items += self.safe_put_bulk(url, bulk_json) json_size = sys.getsizeof(bulk_json) / (1024 * 1024) logger.debug("bulk packet sent (%.2f sec prev, %i total, %.2f MB)" % (time() - task_init, new_items, json_size)) return new_items
[ "def", "bulk_upload", "(", "self", ",", "items", ",", "field_id", ")", ":", "current", "=", "0", "new_items", "=", "0", "# total items added with bulk", "bulk_json", "=", "\"\"", "if", "not", "items", ":", "return", "new_items", "url", "=", "self", ".", "i...
Upload in controlled packs items to ES using bulk API
[ "Upload", "in", "controlled", "packs", "items", "to", "ES", "using", "bulk", "API" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L270-L305
19,697
chaoss/grimoirelab-elk
grimoire_elk/elastic.py
ElasticSearch.all_properties
def all_properties(self): """Get all properties of a given index""" properties = {} r = self.requests.get(self.index_url + "/_mapping", headers=HEADER_JSON, verify=False) try: r.raise_for_status() r_json = r.json() if 'items' not in r_json[self.index]['mappings']: return properties if 'properties' not in r_json[self.index]['mappings']['items']: return properties properties = r_json[self.index]['mappings']['items']['properties'] except requests.exceptions.HTTPError as ex: logger.error("Error all attributes for %s.", self.anonymize_url(self.index_url)) logger.error(ex) return return properties
python
def all_properties(self): properties = {} r = self.requests.get(self.index_url + "/_mapping", headers=HEADER_JSON, verify=False) try: r.raise_for_status() r_json = r.json() if 'items' not in r_json[self.index]['mappings']: return properties if 'properties' not in r_json[self.index]['mappings']['items']: return properties properties = r_json[self.index]['mappings']['items']['properties'] except requests.exceptions.HTTPError as ex: logger.error("Error all attributes for %s.", self.anonymize_url(self.index_url)) logger.error(ex) return return properties
[ "def", "all_properties", "(", "self", ")", ":", "properties", "=", "{", "}", "r", "=", "self", ".", "requests", ".", "get", "(", "self", ".", "index_url", "+", "\"/_mapping\"", ",", "headers", "=", "HEADER_JSON", ",", "verify", "=", "False", ")", "try"...
Get all properties of a given index
[ "Get", "all", "properties", "of", "a", "given", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L507-L528
19,698
chaoss/grimoirelab-elk
grimoire_elk/utils.py
get_kibiter_version
def get_kibiter_version(url): """ Return kibiter major number version The url must point to the Elasticsearch used by Kibiter """ config_url = '.kibana/config/_search' # Avoid having // in the URL because ES will fail if url[-1] != '/': url += "/" url += config_url r = requests.get(url) r.raise_for_status() if len(r.json()['hits']['hits']) == 0: logger.error("Can not get the Kibiter version") return None version = r.json()['hits']['hits'][0]['_id'] # 5.4.0-SNAPSHOT major_version = version.split(".", 1)[0] return major_version
python
def get_kibiter_version(url): config_url = '.kibana/config/_search' # Avoid having // in the URL because ES will fail if url[-1] != '/': url += "/" url += config_url r = requests.get(url) r.raise_for_status() if len(r.json()['hits']['hits']) == 0: logger.error("Can not get the Kibiter version") return None version = r.json()['hits']['hits'][0]['_id'] # 5.4.0-SNAPSHOT major_version = version.split(".", 1)[0] return major_version
[ "def", "get_kibiter_version", "(", "url", ")", ":", "config_url", "=", "'.kibana/config/_search'", "# Avoid having // in the URL because ES will fail", "if", "url", "[", "-", "1", "]", "!=", "'/'", ":", "url", "+=", "\"/\"", "url", "+=", "config_url", "r", "=", ...
Return kibiter major number version The url must point to the Elasticsearch used by Kibiter
[ "Return", "kibiter", "major", "number", "version" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/utils.py#L262-L284
19,699
chaoss/grimoirelab-elk
grimoire_elk/utils.py
get_params
def get_params(): """ Get params definition from ElasticOcean and from all the backends """ parser = get_params_parser() args = parser.parse_args() if not args.enrich_only and not args.only_identities and not args.only_studies: if not args.index: # Check that the raw index name is defined print("[error] --index <name> param is required when collecting items from raw") sys.exit(1) return args
python
def get_params(): parser = get_params_parser() args = parser.parse_args() if not args.enrich_only and not args.only_identities and not args.only_studies: if not args.index: # Check that the raw index name is defined print("[error] --index <name> param is required when collecting items from raw") sys.exit(1) return args
[ "def", "get_params", "(", ")", ":", "parser", "=", "get_params_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "args", ".", "enrich_only", "and", "not", "args", ".", "only_identities", "and", "not", "args", ".", "only_...
Get params definition from ElasticOcean and from all the backends
[ "Get", "params", "definition", "from", "ElasticOcean", "and", "from", "all", "the", "backends" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/utils.py#L376-L388