repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkShell.print_config
def print_config(self, _): ''' Print configuration. ''' for section in self.config.sections(): print '[%s]' % section items = dict(self.config.items(section)) for k in items: print "%(a)s=%(b)s" % {'a': k, 'b': items[k]} print ''
python
def print_config(self, _): ''' Print configuration. ''' for section in self.config.sections(): print '[%s]' % section items = dict(self.config.items(section)) for k in items: print "%(a)s=%(b)s" % {'a': k, 'b': items[k]} print ''
[ "def", "print_config", "(", "self", ",", "_", ")", ":", "for", "section", "in", "self", ".", "config", ".", "sections", "(", ")", ":", "print", "'[%s]'", "%", "section", "items", "=", "dict", "(", "self", ".", "config", ".", "items", "(", "section", ...
Print configuration.
[ "Print", "configuration", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L525-L532
train
205,000
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkShell.reload_config
def reload_config(self, _): ''' Reload config. ''' restart_server = False if (self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe'): user_input = raw_input("Reloading configuration requires the server " "to restart. Really reload? y or n: ") if user_input != 'y': return restart_server = True self.config.load_config() if restart_server: self.server_restart()
python
def reload_config(self, _): ''' Reload config. ''' restart_server = False if (self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe'): user_input = raw_input("Reloading configuration requires the server " "to restart. Really reload? y or n: ") if user_input != 'y': return restart_server = True self.config.load_config() if restart_server: self.server_restart()
[ "def", "reload_config", "(", "self", ",", "_", ")", ":", "restart_server", "=", "False", "if", "(", "self", ".", "server", ".", "is_server_running", "(", ")", "==", "'yes'", "or", "self", ".", "server", ".", "is_server_running", "(", ")", "==", "'maybe'"...
Reload config.
[ "Reload", "config", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L534-L546
train
205,001
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkShell.do_status
def do_status(self, _): ''' Notify user of server status. ''' server_status = self.server.is_server_running() if server_status == 'yes': print 'Server: ' + colorize('currently online', 'green') elif server_status == 'no': print 'Server: ' + colorize('currently offline', 'red') elif server_status == 'maybe': print 'Server: ' + colorize('status unknown', 'yellow') elif server_status == 'blocked': print 'Server: ' + colorize('blocked', 'red')
python
def do_status(self, _): ''' Notify user of server status. ''' server_status = self.server.is_server_running() if server_status == 'yes': print 'Server: ' + colorize('currently online', 'green') elif server_status == 'no': print 'Server: ' + colorize('currently offline', 'red') elif server_status == 'maybe': print 'Server: ' + colorize('status unknown', 'yellow') elif server_status == 'blocked': print 'Server: ' + colorize('blocked', 'red')
[ "def", "do_status", "(", "self", ",", "_", ")", ":", "server_status", "=", "self", ".", "server", ".", "is_server_running", "(", ")", "if", "server_status", "==", "'yes'", ":", "print", "'Server: '", "+", "colorize", "(", "'currently online'", ",", "'green'"...
Notify user of server status.
[ "Notify", "user", "of", "server", "status", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L548-L558
train
205,002
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkShell.db_use_local_file
def db_use_local_file(self, arg, filename=None): ''' Use local file for DB. ''' # interactive = False # Never used if filename is None: # interactive = True # Never used filename = raw_input('Enter the filename of the local SQLLite ' 'database you would like to use ' '[default=participants.db]: ') if filename == '': filename = 'participants.db' base_url = "sqlite:///" + filename self.config.set("Database Parameters", "database_url", base_url) print "Updated database setting (database_url): \n\t", \ self.config.get("Database Parameters", "database_url") if self.server.is_server_running() == 'yes': self.server_restart()
python
def db_use_local_file(self, arg, filename=None): ''' Use local file for DB. ''' # interactive = False # Never used if filename is None: # interactive = True # Never used filename = raw_input('Enter the filename of the local SQLLite ' 'database you would like to use ' '[default=participants.db]: ') if filename == '': filename = 'participants.db' base_url = "sqlite:///" + filename self.config.set("Database Parameters", "database_url", base_url) print "Updated database setting (database_url): \n\t", \ self.config.get("Database Parameters", "database_url") if self.server.is_server_running() == 'yes': self.server_restart()
[ "def", "db_use_local_file", "(", "self", ",", "arg", ",", "filename", "=", "None", ")", ":", "# interactive = False # Never used", "if", "filename", "is", "None", ":", "# interactive = True # Never used", "filename", "=", "raw_input", "(", "'Enter the filename of the ...
Use local file for DB.
[ "Use", "local", "file", "for", "DB", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L574-L589
train
205,003
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkShell.do_download_datafiles
def do_download_datafiles(self, _): ''' Download datafiles. ''' contents = {"trialdata": lambda p: p.get_trial_data(), "eventdata": \ lambda p: p.get_event_data(), "questiondata": lambda p: \ p.get_question_data()} query = Participant.query.all() for k in contents: ret = "".join([contents[k](p) for p in query]) temp_file = open(k + '.csv', 'w') temp_file.write(ret) temp_file.close()
python
def do_download_datafiles(self, _): ''' Download datafiles. ''' contents = {"trialdata": lambda p: p.get_trial_data(), "eventdata": \ lambda p: p.get_event_data(), "questiondata": lambda p: \ p.get_question_data()} query = Participant.query.all() for k in contents: ret = "".join([contents[k](p) for p in query]) temp_file = open(k + '.csv', 'w') temp_file.write(ret) temp_file.close()
[ "def", "do_download_datafiles", "(", "self", ",", "_", ")", ":", "contents", "=", "{", "\"trialdata\"", ":", "lambda", "p", ":", "p", ".", "get_trial_data", "(", ")", ",", "\"eventdata\"", ":", "lambda", "p", ":", "p", ".", "get_event_data", "(", ")", ...
Download datafiles.
[ "Download", "datafiles", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L591-L601
train
205,004
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkShell.complete_server
def complete_server(self, text, line, begidx, endidx): ''' Tab-complete server command ''' return [i for i in PsiturkShell.server_commands if i.startswith(text)]
python
def complete_server(self, text, line, begidx, endidx): ''' Tab-complete server command ''' return [i for i in PsiturkShell.server_commands if i.startswith(text)]
[ "def", "complete_server", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "return", "[", "i", "for", "i", "in", "PsiturkShell", ".", "server_commands", "if", "i", ".", "startswith", "(", "text", ")", "]" ]
Tab-complete server command
[ "Tab", "-", "complete", "server", "command" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L660-L662
train
205,005
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkNetworkShell.do_quit
def do_quit(self, _): '''Override do_quit for network clean up.''' if (self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe'): user_input = raw_input("Quitting shell will shut down experiment " "server. Really quit? y or n: ") if user_input == 'y': self.server_off() else: return False return True
python
def do_quit(self, _): '''Override do_quit for network clean up.''' if (self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe'): user_input = raw_input("Quitting shell will shut down experiment " "server. Really quit? y or n: ") if user_input == 'y': self.server_off() else: return False return True
[ "def", "do_quit", "(", "self", ",", "_", ")", ":", "if", "(", "self", ".", "server", ".", "is_server_running", "(", ")", "==", "'yes'", "or", "self", ".", "server", ".", "is_server_running", "(", ")", "==", "'maybe'", ")", ":", "user_input", "=", "ra...
Override do_quit for network clean up.
[ "Override", "do_quit", "for", "network", "clean", "up", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L758-L768
train
205,006
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkNetworkShell.clean_up
def clean_up(self): ''' Clean up child and orphaned processes. ''' if self.tunnel.is_open: print 'Closing tunnel...' self.tunnel.close() print 'Done.' else: pass
python
def clean_up(self): ''' Clean up child and orphaned processes. ''' if self.tunnel.is_open: print 'Closing tunnel...' self.tunnel.close() print 'Done.' else: pass
[ "def", "clean_up", "(", "self", ")", ":", "if", "self", ".", "tunnel", ".", "is_open", ":", "print", "'Closing tunnel...'", "self", ".", "tunnel", ".", "close", "(", ")", "print", "'Done.'", "else", ":", "pass" ]
Clean up child and orphaned processes.
[ "Clean", "up", "child", "and", "orphaned", "processes", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L787-L794
train
205,007
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkNetworkShell.get_intro_prompt
def get_intro_prompt(self): ''' Overloads intro prompt with network-aware version if you can reach psiTurk.org, request system status message''' server_msg = self.web_services.get_system_status() return server_msg + colorize('psiTurk version ' + version_number + '\nType "help" for more information.', 'green', False)
python
def get_intro_prompt(self): ''' Overloads intro prompt with network-aware version if you can reach psiTurk.org, request system status message''' server_msg = self.web_services.get_system_status() return server_msg + colorize('psiTurk version ' + version_number + '\nType "help" for more information.', 'green', False)
[ "def", "get_intro_prompt", "(", "self", ")", ":", "server_msg", "=", "self", ".", "web_services", ".", "get_system_status", "(", ")", "return", "server_msg", "+", "colorize", "(", "'psiTurk version '", "+", "version_number", "+", "'\\nType \"help\" for more informatio...
Overloads intro prompt with network-aware version if you can reach psiTurk.org, request system status message
[ "Overloads", "intro", "prompt", "with", "network", "-", "aware", "version", "if", "you", "can", "reach", "psiTurk", ".", "org", "request", "system", "status", "message" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L801-L807
train
205,008
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkNetworkShell.complete_db
def complete_db(self, text, line, begidx, endidx): ''' Tab-complete db command ''' return [i for i in PsiturkNetworkShell.db_commands if \ i.startswith(text)]
python
def complete_db(self, text, line, begidx, endidx): ''' Tab-complete db command ''' return [i for i in PsiturkNetworkShell.db_commands if \ i.startswith(text)]
[ "def", "complete_db", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "return", "[", "i", "for", "i", "in", "PsiturkNetworkShell", ".", "db_commands", "if", "i", ".", "startswith", "(", "text", ")", "]" ]
Tab-complete db command
[ "Tab", "-", "complete", "db", "command" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L917-L920
train
205,009
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkNetworkShell.complete_hit
def complete_hit(self, text, line, begidx, endidx): ''' Tab-complete hit command. ''' return [i for i in PsiturkNetworkShell.hit_commands if \ i.startswith(text)]
python
def complete_hit(self, text, line, begidx, endidx): ''' Tab-complete hit command. ''' return [i for i in PsiturkNetworkShell.hit_commands if \ i.startswith(text)]
[ "def", "complete_hit", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "return", "[", "i", "for", "i", "in", "PsiturkNetworkShell", ".", "hit_commands", "if", "i", ".", "startswith", "(", "text", ")", "]" ]
Tab-complete hit command.
[ "Tab", "-", "complete", "hit", "command", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L1017-L1020
train
205,010
NYUCCL/psiTurk
psiturk/psiturk_shell.py
PsiturkNetworkShell.complete_worker
def complete_worker(self, text, line, begidx, endidx): ''' Tab-complete worker command. ''' return [i for i in PsiturkNetworkShell.worker_commands if \ i.startswith(text)]
python
def complete_worker(self, text, line, begidx, endidx): ''' Tab-complete worker command. ''' return [i for i in PsiturkNetworkShell.worker_commands if \ i.startswith(text)]
[ "def", "complete_worker", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "return", "[", "i", "for", "i", "in", "PsiturkNetworkShell", ".", "worker_commands", "if", "i", ".", "startswith", "(", "text", ")", "]" ]
Tab-complete worker command.
[ "Tab", "-", "complete", "worker", "command", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L1055-L1058
train
205,011
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.get_db_instance_info
def get_db_instance_info(self, dbid): ''' Get DB instance info ''' if not self.connect_to_aws_rds(): return False try: instances = self.rdsc.describe_db_instances(dbid).get('DBInstances') except: return False else: myinstance = instances[0] return myinstance
python
def get_db_instance_info(self, dbid): ''' Get DB instance info ''' if not self.connect_to_aws_rds(): return False try: instances = self.rdsc.describe_db_instances(dbid).get('DBInstances') except: return False else: myinstance = instances[0] return myinstance
[ "def", "get_db_instance_info", "(", "self", ",", "dbid", ")", ":", "if", "not", "self", ".", "connect_to_aws_rds", "(", ")", ":", "return", "False", "try", ":", "instances", "=", "self", ".", "rdsc", ".", "describe_db_instances", "(", "dbid", ")", ".", "...
Get DB instance info
[ "Get", "DB", "instance", "info" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L160-L170
train
205,012
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.allow_access_to_instance
def allow_access_to_instance(self, _, ip_address): ''' Allow access to instance. ''' if not self.connect_to_aws_rds(): return False try: conn = boto.ec2.connect_to_region( self.region, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key ) sgs = conn.get_all_security_groups('default') default_sg = sgs[0] default_sg.authorize(ip_protocol='tcp', from_port=3306, to_port=3306, cidr_ip=str(ip_address)+'/32') except EC2ResponseError, exception: if exception.error_code == "InvalidPermission.Duplicate": return True # ok it already exists else: return False else: return True
python
def allow_access_to_instance(self, _, ip_address): ''' Allow access to instance. ''' if not self.connect_to_aws_rds(): return False try: conn = boto.ec2.connect_to_region( self.region, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key ) sgs = conn.get_all_security_groups('default') default_sg = sgs[0] default_sg.authorize(ip_protocol='tcp', from_port=3306, to_port=3306, cidr_ip=str(ip_address)+'/32') except EC2ResponseError, exception: if exception.error_code == "InvalidPermission.Duplicate": return True # ok it already exists else: return False else: return True
[ "def", "allow_access_to_instance", "(", "self", ",", "_", ",", "ip_address", ")", ":", "if", "not", "self", ".", "connect_to_aws_rds", "(", ")", ":", "return", "False", "try", ":", "conn", "=", "boto", ".", "ec2", ".", "connect_to_region", "(", "self", "...
Allow access to instance.
[ "Allow", "access", "to", "instance", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L172-L192
train
205,013
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.validate_instance_id
def validate_instance_id(self, instid): ''' Validate instance ID ''' # 1-63 alphanumeric characters, first must be a letter. if re.match('[\w-]+$', instid) is not None: if len(instid) <= 63 and len(instid) >= 1: if instid[0].isalpha(): return True return "*** Error: Instance ids must be 1-63 alphanumeric characters, \ first is a letter."
python
def validate_instance_id(self, instid): ''' Validate instance ID ''' # 1-63 alphanumeric characters, first must be a letter. if re.match('[\w-]+$', instid) is not None: if len(instid) <= 63 and len(instid) >= 1: if instid[0].isalpha(): return True return "*** Error: Instance ids must be 1-63 alphanumeric characters, \ first is a letter."
[ "def", "validate_instance_id", "(", "self", ",", "instid", ")", ":", "# 1-63 alphanumeric characters, first must be a letter.", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "instid", ")", "is", "not", "None", ":", "if", "len", "(", "instid", ")", "<=", "6...
Validate instance ID
[ "Validate", "instance", "ID" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L218-L226
train
205,014
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.validate_instance_username
def validate_instance_username(self, username): ''' Validate instance username ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', username) is not None: if len(username) <= 16 and len(username) >= 1: if username[0].isalpha(): if username not in MYSQL_RESERVED_WORDS: return True return '*** Error: Usernames must be 1-16 alphanumeric chracters, \ first a letter, cannot be reserved MySQL word.'
python
def validate_instance_username(self, username): ''' Validate instance username ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', username) is not None: if len(username) <= 16 and len(username) >= 1: if username[0].isalpha(): if username not in MYSQL_RESERVED_WORDS: return True return '*** Error: Usernames must be 1-16 alphanumeric chracters, \ first a letter, cannot be reserved MySQL word.'
[ "def", "validate_instance_username", "(", "self", ",", "username", ")", ":", "# 1-16 alphanumeric characters - first character must be a letter -", "# cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "username", ")", "is", "not", "None", ...
Validate instance username
[ "Validate", "instance", "username" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L238-L248
train
205,015
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.validate_instance_password
def validate_instance_password(self, password): ''' Validate instance passwords ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', password) is not None: if len(password) <= 41 and len(password) >= 8: return True return '*** Error: Passwords must be 8-41 alphanumeric characters'
python
def validate_instance_password(self, password): ''' Validate instance passwords ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', password) is not None: if len(password) <= 41 and len(password) >= 8: return True return '*** Error: Passwords must be 8-41 alphanumeric characters'
[ "def", "validate_instance_password", "(", "self", ",", "password", ")", ":", "# 1-16 alphanumeric characters - first character must be a letter -", "# cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "password", ")", "is", "not", "None", ...
Validate instance passwords
[ "Validate", "instance", "passwords" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L250-L257
train
205,016
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.validate_instance_dbname
def validate_instance_dbname(self, dbname): ''' Validate instance database name ''' # 1-64 alphanumeric characters, cannot be a reserved MySQL word if re.match('[\w-]+$', dbname) is not None: if len(dbname) <= 41 and len(dbname) >= 1: if dbname.lower() not in MYSQL_RESERVED_WORDS: return True return '*** Error: Database names must be 1-64 alphanumeric characters,\ cannot be a reserved MySQL word.'
python
def validate_instance_dbname(self, dbname): ''' Validate instance database name ''' # 1-64 alphanumeric characters, cannot be a reserved MySQL word if re.match('[\w-]+$', dbname) is not None: if len(dbname) <= 41 and len(dbname) >= 1: if dbname.lower() not in MYSQL_RESERVED_WORDS: return True return '*** Error: Database names must be 1-64 alphanumeric characters,\ cannot be a reserved MySQL word.'
[ "def", "validate_instance_dbname", "(", "self", ",", "dbname", ")", ":", "# 1-64 alphanumeric characters, cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "dbname", ")", "is", "not", "None", ":", "if", "len", "(", "dbname", ")", ...
Validate instance database name
[ "Validate", "instance", "database", "name" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L259-L267
train
205,017
NYUCCL/psiTurk
psiturk/amt_services.py
RDSServices.create_db_instance
def create_db_instance(self, params): ''' Create db instance ''' if not self.connect_to_aws_rds(): return False try: database = self.rdsc.create_dbinstance( id=params['id'], allocated_storage=params['size'], instance_class='db.t1.micro', engine='MySQL', master_username=params['username'], master_password=params['password'], db_name=params['dbname'], multi_az=False ) except: return False else: return True
python
def create_db_instance(self, params): ''' Create db instance ''' if not self.connect_to_aws_rds(): return False try: database = self.rdsc.create_dbinstance( id=params['id'], allocated_storage=params['size'], instance_class='db.t1.micro', engine='MySQL', master_username=params['username'], master_password=params['password'], db_name=params['dbname'], multi_az=False ) except: return False else: return True
[ "def", "create_db_instance", "(", "self", ",", "params", ")", ":", "if", "not", "self", ".", "connect_to_aws_rds", "(", ")", ":", "return", "False", "try", ":", "database", "=", "self", ".", "rdsc", ".", "create_dbinstance", "(", "id", "=", "params", "["...
Create db instance
[ "Create", "db", "instance" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L269-L287
train
205,018
NYUCCL/psiTurk
psiturk/amt_services.py
MTurkServices.get_all_hits
def get_all_hits(self): ''' Get all HITs ''' if not self.connect_to_turk(): return False try: hits = [] paginator = self.mtc.get_paginator('list_hits') for page in paginator.paginate(): hits.extend(page['HITs']) except Exception as e: print e return False hits_data = self._hit_xml_to_object(hits) return hits_data
python
def get_all_hits(self): ''' Get all HITs ''' if not self.connect_to_turk(): return False try: hits = [] paginator = self.mtc.get_paginator('list_hits') for page in paginator.paginate(): hits.extend(page['HITs']) except Exception as e: print e return False hits_data = self._hit_xml_to_object(hits) return hits_data
[ "def", "get_all_hits", "(", "self", ")", ":", "if", "not", "self", ".", "connect_to_turk", "(", ")", ":", "return", "False", "try", ":", "hits", "=", "[", "]", "paginator", "=", "self", ".", "mtc", ".", "get_paginator", "(", "'list_hits'", ")", "for", ...
Get all HITs
[ "Get", "all", "HITs" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L329-L342
train
205,019
NYUCCL/psiTurk
psiturk/amt_services.py
MTurkServices.setup_mturk_connection
def setup_mturk_connection(self): ''' Connect to turk ''' if ((self.aws_access_key_id == 'YourAccessKeyId') or (self.aws_secret_access_key == 'YourSecretAccessKey')): print "AWS access key not set in ~/.psiturkconfig; please enter a valid access key." assert False if self.is_sandbox: endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com' else: endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com' self.mtc = boto3.client('mturk', region_name='us-east-1', aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, endpoint_url=endpoint_url) return True
python
def setup_mturk_connection(self): ''' Connect to turk ''' if ((self.aws_access_key_id == 'YourAccessKeyId') or (self.aws_secret_access_key == 'YourSecretAccessKey')): print "AWS access key not set in ~/.psiturkconfig; please enter a valid access key." assert False if self.is_sandbox: endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com' else: endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com' self.mtc = boto3.client('mturk', region_name='us-east-1', aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, endpoint_url=endpoint_url) return True
[ "def", "setup_mturk_connection", "(", "self", ")", ":", "if", "(", "(", "self", ".", "aws_access_key_id", "==", "'YourAccessKeyId'", ")", "or", "(", "self", ".", "aws_secret_access_key", "==", "'YourSecretAccessKey'", ")", ")", ":", "print", "\"AWS access key not ...
Connect to turk
[ "Connect", "to", "turk" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L436-L453
train
205,020
NYUCCL/psiTurk
psiturk/amt_services.py
MTurkServices.get_hit_status
def get_hit_status(self, hitid): ''' Get HIT status ''' hitdata = self.get_hit(hitid) if not hitdata: return False return hitdata['HITStatus']
python
def get_hit_status(self, hitid): ''' Get HIT status ''' hitdata = self.get_hit(hitid) if not hitdata: return False return hitdata['HITStatus']
[ "def", "get_hit_status", "(", "self", ",", "hitid", ")", ":", "hitdata", "=", "self", ".", "get_hit", "(", "hitid", ")", "if", "not", "hitdata", ":", "return", "False", "return", "hitdata", "[", "'HITStatus'", "]" ]
Get HIT status
[ "Get", "HIT", "status" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L652-L658
train
205,021
NYUCCL/psiTurk
psiturk/psiturk_org_services.py
ExperimentExchangeServices.query_records_no_auth
def query_records_no_auth(self, name, query=''): ''' Query records without authorization ''' #headers = {'key': username, 'secret': password} req = requests.get(self.api_server + '/api/' + name + "/" + query) return req
python
def query_records_no_auth(self, name, query=''): ''' Query records without authorization ''' #headers = {'key': username, 'secret': password} req = requests.get(self.api_server + '/api/' + name + "/" + query) return req
[ "def", "query_records_no_auth", "(", "self", ",", "name", ",", "query", "=", "''", ")", ":", "#headers = {'key': username, 'secret': password}", "req", "=", "requests", ".", "get", "(", "self", ".", "api_server", "+", "'/api/'", "+", "name", "+", "\"/\"", "+",...
Query records without authorization
[ "Query", "records", "without", "authorization" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_org_services.py#L176-L180
train
205,022
NYUCCL/psiTurk
psiturk/psiturk_org_services.py
TunnelServices.get_tunnel_ad_url
def get_tunnel_ad_url(self): ''' Get tunnel hostname from psiturk.org ''' req = requests.get('https://api.psiturk.org/api/tunnel', auth=(self.access_key, self.secret_key)) if req.status_code in [401, 403, 500]: print(req.content) return False else: return req.json()['tunnel_hostname']
python
def get_tunnel_ad_url(self): ''' Get tunnel hostname from psiturk.org ''' req = requests.get('https://api.psiturk.org/api/tunnel', auth=(self.access_key, self.secret_key)) if req.status_code in [401, 403, 500]: print(req.content) return False else: return req.json()['tunnel_hostname']
[ "def", "get_tunnel_ad_url", "(", "self", ")", ":", "req", "=", "requests", ".", "get", "(", "'https://api.psiturk.org/api/tunnel'", ",", "auth", "=", "(", "self", ".", "access_key", ",", "self", ".", "secret_key", ")", ")", "if", "req", ".", "status_code", ...
Get tunnel hostname from psiturk.org
[ "Get", "tunnel", "hostname", "from", "psiturk", ".", "org" ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_org_services.py#L256-L264
train
205,023
NYUCCL/psiTurk
psiturk/psiturk_org_services.py
TunnelServices.change_tunnel_ad_url
def change_tunnel_ad_url(self): ''' Change tunnel ad url. ''' if self.is_open: self.close() req = requests.delete('https://api.psiturk.org/api/tunnel/', auth=(self.access_key, self.secret_key)) # the request content here actually will include the tunnel_hostname # if needed or wanted. if req.status_code in [401, 403, 500]: print(req.content) return False
python
def change_tunnel_ad_url(self): ''' Change tunnel ad url. ''' if self.is_open: self.close() req = requests.delete('https://api.psiturk.org/api/tunnel/', auth=(self.access_key, self.secret_key)) # the request content here actually will include the tunnel_hostname # if needed or wanted. if req.status_code in [401, 403, 500]: print(req.content) return False
[ "def", "change_tunnel_ad_url", "(", "self", ")", ":", "if", "self", ".", "is_open", ":", "self", ".", "close", "(", ")", "req", "=", "requests", ".", "delete", "(", "'https://api.psiturk.org/api/tunnel/'", ",", "auth", "=", "(", "self", ".", "access_key", ...
Change tunnel ad url.
[ "Change", "tunnel", "ad", "url", "." ]
7170b992a0b5f56c165929cf87b3d3a1f3336c36
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_org_services.py#L266-L276
train
205,024
dwavesystems/dwave_networkx
dwave_networkx/algorithms/tsp.py
traveling_salesman
def traveling_salesman(G, sampler=None, lagrange=2, weight='weight', **sampler_args): """Returns an approximate minimum traveling salesperson route. Defines a QUBO with ground states corresponding to the minimum routes and uses the sampler to sample from it. A route is a cycle in the graph that reaches each node exactly once. A minimum route is a route with the smallest total edge weight. Parameters ---------- G : NetworkX graph The graph on which to find a minimum traveling salesperson route. This should be a complete graph with non-zero weights on every edge. sampler : A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (visit every city once) versus objective (shortest distance route). weight : optional (default 'weight') The name of the edge attribute containing the weight. sampler_args : Additional keyword parameters are passed to the sampler. Returns ------- route : list List of nodes in order to be visited on a route Examples -------- This example uses a `dimod <https://github.com/dwavesystems/dimod>`_ sampler to find a minimum route in a five-cities problem. >>> import dwave_networkx as dnx >>> import networkx as nx >>> import dimod ... >>> G = nx.complete_graph(4) >>> G.add_weighted_edges_from({(0, 1, 1), (0, 2, 2), (0, 3, 3), (1, 2, 3), ... (1, 3, 4), (2, 3, 5)}) >>> dnx.traveling_salesman(G, dimod.ExactSolver()) [2, 1, 0, 3] Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # Get a QUBO representation of the problem Q = traveling_salesman_qubo(G, lagrange, weight) # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample, in order by stop number sample = next(iter(response)) route = [] for entry in sample: if sample[entry] > 0: route.append(entry) route.sort(key=lambda x: x[1]) return list((x[0] for x in route))
python
def traveling_salesman(G, sampler=None, lagrange=2, weight='weight', **sampler_args): """Returns an approximate minimum traveling salesperson route. Defines a QUBO with ground states corresponding to the minimum routes and uses the sampler to sample from it. A route is a cycle in the graph that reaches each node exactly once. A minimum route is a route with the smallest total edge weight. Parameters ---------- G : NetworkX graph The graph on which to find a minimum traveling salesperson route. This should be a complete graph with non-zero weights on every edge. sampler : A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (visit every city once) versus objective (shortest distance route). weight : optional (default 'weight') The name of the edge attribute containing the weight. sampler_args : Additional keyword parameters are passed to the sampler. Returns ------- route : list List of nodes in order to be visited on a route Examples -------- This example uses a `dimod <https://github.com/dwavesystems/dimod>`_ sampler to find a minimum route in a five-cities problem. >>> import dwave_networkx as dnx >>> import networkx as nx >>> import dimod ... >>> G = nx.complete_graph(4) >>> G.add_weighted_edges_from({(0, 1, 1), (0, 2, 2), (0, 3, 3), (1, 2, 3), ... (1, 3, 4), (2, 3, 5)}) >>> dnx.traveling_salesman(G, dimod.ExactSolver()) [2, 1, 0, 3] Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # Get a QUBO representation of the problem Q = traveling_salesman_qubo(G, lagrange, weight) # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample, in order by stop number sample = next(iter(response)) route = [] for entry in sample: if sample[entry] > 0: route.append(entry) route.sort(key=lambda x: x[1]) return list((x[0] for x in route))
[ "def", "traveling_salesman", "(", "G", ",", "sampler", "=", "None", ",", "lagrange", "=", "2", ",", "weight", "=", "'weight'", ",", "*", "*", "sampler_args", ")", ":", "# Get a QUBO representation of the problem", "Q", "=", "traveling_salesman_qubo", "(", "G", ...
Returns an approximate minimum traveling salesperson route. Defines a QUBO with ground states corresponding to the minimum routes and uses the sampler to sample from it. A route is a cycle in the graph that reaches each node exactly once. A minimum route is a route with the smallest total edge weight. Parameters ---------- G : NetworkX graph The graph on which to find a minimum traveling salesperson route. This should be a complete graph with non-zero weights on every edge. sampler : A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (visit every city once) versus objective (shortest distance route). weight : optional (default 'weight') The name of the edge attribute containing the weight. sampler_args : Additional keyword parameters are passed to the sampler. Returns ------- route : list List of nodes in order to be visited on a route Examples -------- This example uses a `dimod <https://github.com/dwavesystems/dimod>`_ sampler to find a minimum route in a five-cities problem. >>> import dwave_networkx as dnx >>> import networkx as nx >>> import dimod ... >>> G = nx.complete_graph(4) >>> G.add_weighted_edges_from({(0, 1, 1), (0, 2, 2), (0, 3, 3), (1, 2, 3), ... (1, 3, 4), (2, 3, 5)}) >>> dnx.traveling_salesman(G, dimod.ExactSolver()) [2, 1, 0, 3] Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample.
[ "Returns", "an", "approximate", "minimum", "traveling", "salesperson", "route", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/tsp.py#L30-L107
train
205,025
dwavesystems/dwave_networkx
dwave_networkx/algorithms/tsp.py
traveling_salesman_qubo
def traveling_salesman_qubo(G, lagrange=2, weight='weight'): """Return the QUBO with ground states corresponding to a minimum TSP route. If :math:`|G|` is the number of nodes in the graph, the resulting qubo will have: * :math:`|G|^2` variables/nodes * :math:`2 |G|^2 (|G| - 1)` interactions/edges Parameters ---------- G : NetworkX graph A complete graph in which each edge has a attribute giving its weight. lagrange : number, optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). weight : optional (default 'weight') The name of the edge attribute containing the weight. Returns ------- QUBO : dict The QUBO with ground states corresponding to a minimum travelling salesperson route. """ N = G.number_of_nodes() # some input checking if N in (1, 2) or len(G.edges) != N*(N-1)//2: msg = "graph must be a complete graph with at least 3 nodes or empty" raise ValueError(msg) # Creating the QUBO Q = defaultdict(float) # Constraint that each row has exactly one 1 for node in G: for pos_1 in range(N): Q[((node, pos_1), (node, pos_1))] -= lagrange for pos_2 in range(pos_1+1, N): Q[((node, pos_1), (node, pos_2))] += 2.0*lagrange # Constraint that each col has exactly one 1 for pos in range(N): for node_1 in G: Q[((node_1, pos), (node_1, pos))] -= lagrange for node_2 in set(G)-{node_1}: Q[((node_1, pos), (node_2, pos))] += 2.0*lagrange # Objective that minimizes distance for u, v in itertools.combinations(G.nodes, 2): for pos in range(N): nextpos = (pos + 1) % N # going from u -> v Q[((u, pos), (v, nextpos))] += G[u][v][weight] # going from v -> u Q[((v, pos), (u, nextpos))] += G[u][v][weight] return Q
python
def traveling_salesman_qubo(G, lagrange=2, weight='weight'): """Return the QUBO with ground states corresponding to a minimum TSP route. If :math:`|G|` is the number of nodes in the graph, the resulting qubo will have: * :math:`|G|^2` variables/nodes * :math:`2 |G|^2 (|G| - 1)` interactions/edges Parameters ---------- G : NetworkX graph A complete graph in which each edge has a attribute giving its weight. lagrange : number, optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). weight : optional (default 'weight') The name of the edge attribute containing the weight. Returns ------- QUBO : dict The QUBO with ground states corresponding to a minimum travelling salesperson route. """ N = G.number_of_nodes() # some input checking if N in (1, 2) or len(G.edges) != N*(N-1)//2: msg = "graph must be a complete graph with at least 3 nodes or empty" raise ValueError(msg) # Creating the QUBO Q = defaultdict(float) # Constraint that each row has exactly one 1 for node in G: for pos_1 in range(N): Q[((node, pos_1), (node, pos_1))] -= lagrange for pos_2 in range(pos_1+1, N): Q[((node, pos_1), (node, pos_2))] += 2.0*lagrange # Constraint that each col has exactly one 1 for pos in range(N): for node_1 in G: Q[((node_1, pos), (node_1, pos))] -= lagrange for node_2 in set(G)-{node_1}: Q[((node_1, pos), (node_2, pos))] += 2.0*lagrange # Objective that minimizes distance for u, v in itertools.combinations(G.nodes, 2): for pos in range(N): nextpos = (pos + 1) % N # going from u -> v Q[((u, pos), (v, nextpos))] += G[u][v][weight] # going from v -> u Q[((v, pos), (u, nextpos))] += G[u][v][weight] return Q
[ "def", "traveling_salesman_qubo", "(", "G", ",", "lagrange", "=", "2", ",", "weight", "=", "'weight'", ")", ":", "N", "=", "G", ".", "number_of_nodes", "(", ")", "# some input checking", "if", "N", "in", "(", "1", ",", "2", ")", "or", "len", "(", "G"...
Return the QUBO with ground states corresponding to a minimum TSP route. If :math:`|G|` is the number of nodes in the graph, the resulting qubo will have: * :math:`|G|^2` variables/nodes * :math:`2 |G|^2 (|G| - 1)` interactions/edges Parameters ---------- G : NetworkX graph A complete graph in which each edge has a attribute giving its weight. lagrange : number, optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). weight : optional (default 'weight') The name of the edge attribute containing the weight. Returns ------- QUBO : dict The QUBO with ground states corresponding to a minimum travelling salesperson route.
[ "Return", "the", "QUBO", "with", "ground", "states", "corresponding", "to", "a", "minimum", "TSP", "route", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/tsp.py#L110-L172
train
205,026
dwavesystems/dwave_networkx
dwave_networkx/generators/markov.py
markov_network
def markov_network(potentials): """Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a dictionary of potentials. The potential dict should map each possible assignment of the nodes/edges to their energy. Returns ------- MN : :obj:`networkx.Graph` A markov network as a graph where each node/edge stores its potential dict as above. Examples -------- >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> MN['a']['b']['potential'][(0, 0)] -1 .. _Markov Random Field: https://en.wikipedia.org/wiki/Markov_random_field """ G = nx.Graph() G.name = 'markov_network({!r})'.format(potentials) # we use 'clique' because the keys of potentials can be either nodes or # edges, but in either case they are fully connected. for clique, phis in potentials.items(): num_vars = len(clique) # because this data potentially wont be used for a while, let's do some # input checking now and save some debugging issues later if not isinstance(phis, abc.Mapping): raise TypeError("phis should be a dict") elif not all(config in phis for config in itertools.product((0, 1), repeat=num_vars)): raise ValueError("not all potentials provided for {!r}".format(clique)) if num_vars == 1: u, = clique G.add_node(u, potential=phis) elif num_vars == 2: u, v = clique # in python<=3.5 the edge order might not be consistent so we store # the relevant order of the variables relative to the potentials G.add_edge(u, v, potential=phis, order=(u, v)) else: # developer note: in principle supporting larger cliques can be done # using higher-order, but it would make the use of networkx graphs # far more difficult raise ValueError("Only supports cliques up to size 2") return G
python
def markov_network(potentials): """Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a dictionary of potentials. The potential dict should map each possible assignment of the nodes/edges to their energy. Returns ------- MN : :obj:`networkx.Graph` A markov network as a graph where each node/edge stores its potential dict as above. Examples -------- >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> MN['a']['b']['potential'][(0, 0)] -1 .. _Markov Random Field: https://en.wikipedia.org/wiki/Markov_random_field """ G = nx.Graph() G.name = 'markov_network({!r})'.format(potentials) # we use 'clique' because the keys of potentials can be either nodes or # edges, but in either case they are fully connected. for clique, phis in potentials.items(): num_vars = len(clique) # because this data potentially wont be used for a while, let's do some # input checking now and save some debugging issues later if not isinstance(phis, abc.Mapping): raise TypeError("phis should be a dict") elif not all(config in phis for config in itertools.product((0, 1), repeat=num_vars)): raise ValueError("not all potentials provided for {!r}".format(clique)) if num_vars == 1: u, = clique G.add_node(u, potential=phis) elif num_vars == 2: u, v = clique # in python<=3.5 the edge order might not be consistent so we store # the relevant order of the variables relative to the potentials G.add_edge(u, v, potential=phis, order=(u, v)) else: # developer note: in principle supporting larger cliques can be done # using higher-order, but it would make the use of networkx graphs # far more difficult raise ValueError("Only supports cliques up to size 2") return G
[ "def", "markov_network", "(", "potentials", ")", ":", "G", "=", "nx", ".", "Graph", "(", ")", "G", ".", "name", "=", "'markov_network({!r})'", ".", "format", "(", "potentials", ")", "# we use 'clique' because the keys of potentials can be either nodes or", "# edges, b...
Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a dictionary of potentials. The potential dict should map each possible assignment of the nodes/edges to their energy. Returns ------- MN : :obj:`networkx.Graph` A markov network as a graph where each node/edge stores its potential dict as above. Examples -------- >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> MN['a']['b']['potential'][(0, 0)] -1 .. _Markov Random Field: https://en.wikipedia.org/wiki/Markov_random_field
[ "Creates", "a", "Markov", "Network", "from", "potentials", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/markov.py#L63-L126
train
205,027
dwavesystems/dwave_networkx
dwave_networkx/algorithms/max_cut.py
maximum_cut
def maximum_cut(G, sampler=None, **sampler_args): """Returns an approximate maximum cut. Defines an Ising problem with ground states corresponding to a maximum cut and uses the sampler to sample from it. A maximum cut is a subset S of the vertices of G such that the number of edges between S and the complementary subset is as large as possible. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum cut for a graph of a Chimera unit cell created using the `chimera_graph()` function. >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> cut = dnx.maximum_cut(G, samplerSA) Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # In order to form the Ising problem, we want to increase the # energy by 1 for each edge between two nodes of the same color. # The linear biases can all be 0. h = {v: 0. for v in G} J = {(u, v): 1 for u, v in G.edges} # draw the lowest energy sample from the sampler response = sampler.sample_ising(h, J, **sampler_args) sample = next(iter(response)) return set(v for v in G if sample[v] >= 0)
python
def maximum_cut(G, sampler=None, **sampler_args): """Returns an approximate maximum cut. Defines an Ising problem with ground states corresponding to a maximum cut and uses the sampler to sample from it. A maximum cut is a subset S of the vertices of G such that the number of edges between S and the complementary subset is as large as possible. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum cut for a graph of a Chimera unit cell created using the `chimera_graph()` function. >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> cut = dnx.maximum_cut(G, samplerSA) Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # In order to form the Ising problem, we want to increase the # energy by 1 for each edge between two nodes of the same color. # The linear biases can all be 0. h = {v: 0. for v in G} J = {(u, v): 1 for u, v in G.edges} # draw the lowest energy sample from the sampler response = sampler.sample_ising(h, J, **sampler_args) sample = next(iter(response)) return set(v for v in G if sample[v] >= 0)
[ "def", "maximum_cut", "(", "G", ",", "sampler", "=", "None", ",", "*", "*", "sampler_args", ")", ":", "# In order to form the Ising problem, we want to increase the", "# energy by 1 for each edge between two nodes of the same color.", "# The linear biases can all be 0.", "h", "="...
Returns an approximate maximum cut. Defines an Ising problem with ground states corresponding to a maximum cut and uses the sampler to sample from it. A maximum cut is a subset S of the vertices of G such that the number of edges between S and the complementary subset is as large as possible. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum cut for a graph of a Chimera unit cell created using the `chimera_graph()` function. >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> cut = dnx.maximum_cut(G, samplerSA) Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample.
[ "Returns", "an", "approximate", "maximum", "cut", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/max_cut.py#L8-L71
train
205,028
dwavesystems/dwave_networkx
dwave_networkx/algorithms/max_cut.py
weighted_maximum_cut
def weighted_maximum_cut(G, sampler=None, **sampler_args): """Returns an approximate weighted maximum cut. Defines an Ising problem with ground states corresponding to a weighted maximum cut and uses the sampler to sample from it. A weighted maximum cut is a subset S of the vertices of G that maximizes the sum of the edge weights between S and its complementary subset. Parameters ---------- G : NetworkX graph The graph on which to find a weighted maximum cut. Each edge in G should have a numeric `weight` attribute. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a weighted maximum cut for a graph of a Chimera unit cell. The graph is created using the `chimera_graph()` function with weights added to all its edges such that those incident to nodes {6, 7} have weight -1 while the others are +1. A weighted maximum cut should cut as many of the latter and few of the former as possible. >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> for u, v in G.edges: ....: if (u >= 6) | (v >=6): ....: G[u][v]['weight']=-1 ....: else: G[u][v]['weight']=1 ....: >>> dnx.weighted_maximum_cut(G, samplerSA) {4, 5} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # In order to form the Ising problem, we want to increase the # energy by 1 for each edge between two nodes of the same color. # The linear biases can all be 0. h = {v: 0. for v in G} try: J = {(u, v): G[u][v]['weight'] for u, v in G.edges} except KeyError: raise DWaveNetworkXException("edges must have 'weight' attribute") # draw the lowest energy sample from the sampler response = sampler.sample_ising(h, J, **sampler_args) sample = next(iter(response)) return set(v for v in G if sample[v] >= 0)
python
def weighted_maximum_cut(G, sampler=None, **sampler_args): """Returns an approximate weighted maximum cut. Defines an Ising problem with ground states corresponding to a weighted maximum cut and uses the sampler to sample from it. A weighted maximum cut is a subset S of the vertices of G that maximizes the sum of the edge weights between S and its complementary subset. Parameters ---------- G : NetworkX graph The graph on which to find a weighted maximum cut. Each edge in G should have a numeric `weight` attribute. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a weighted maximum cut for a graph of a Chimera unit cell. The graph is created using the `chimera_graph()` function with weights added to all its edges such that those incident to nodes {6, 7} have weight -1 while the others are +1. A weighted maximum cut should cut as many of the latter and few of the former as possible. >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> for u, v in G.edges: ....: if (u >= 6) | (v >=6): ....: G[u][v]['weight']=-1 ....: else: G[u][v]['weight']=1 ....: >>> dnx.weighted_maximum_cut(G, samplerSA) {4, 5} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # In order to form the Ising problem, we want to increase the # energy by 1 for each edge between two nodes of the same color. # The linear biases can all be 0. h = {v: 0. for v in G} try: J = {(u, v): G[u][v]['weight'] for u, v in G.edges} except KeyError: raise DWaveNetworkXException("edges must have 'weight' attribute") # draw the lowest energy sample from the sampler response = sampler.sample_ising(h, J, **sampler_args) sample = next(iter(response)) return set(v for v in G if sample[v] >= 0)
[ "def", "weighted_maximum_cut", "(", "G", ",", "sampler", "=", "None", ",", "*", "*", "sampler_args", ")", ":", "# In order to form the Ising problem, we want to increase the", "# energy by 1 for each edge between two nodes of the same color.", "# The linear biases can all be 0.", "...
Returns an approximate weighted maximum cut. Defines an Ising problem with ground states corresponding to a weighted maximum cut and uses the sampler to sample from it. A weighted maximum cut is a subset S of the vertices of G that maximizes the sum of the edge weights between S and its complementary subset. Parameters ---------- G : NetworkX graph The graph on which to find a weighted maximum cut. Each edge in G should have a numeric `weight` attribute. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a weighted maximum cut for a graph of a Chimera unit cell. The graph is created using the `chimera_graph()` function with weights added to all its edges such that those incident to nodes {6, 7} have weight -1 while the others are +1. A weighted maximum cut should cut as many of the latter and few of the former as possible. >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> for u, v in G.edges: ....: if (u >= 6) | (v >=6): ....: G[u][v]['weight']=-1 ....: else: G[u][v]['weight']=1 ....: >>> dnx.weighted_maximum_cut(G, samplerSA) {4, 5} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample.
[ "Returns", "an", "approximate", "weighted", "maximum", "cut", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/max_cut.py#L74-L150
train
205,029
dwavesystems/dwave_networkx
dwave_networkx/generators/pegasus.py
get_pegasus_to_nice_fn
def get_pegasus_to_nice_fn(*args, **kwargs): """ Returns a coordinate translation function from the 4-term pegasus_index coordinates to the 5-term "nice" coordinates. Details on the returned function, pegasus_to_nice(u,w,k,z) Inputs are 4-tuples of ints, return is a 5-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- pegasus_to_nice_fn(chimera_coordinates): a function A function that accepts augmented chimera coordinates and returns corresponding Pegasus coordinates. """ if args or kwargs: warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore") def p2n0(u, w, k, z): return (0, w-1 if u else z, z if u else w, u, k-4 if u else k-4) def p2n1(u, w, k, z): return (1, w-1 if u else z, z if u else w, u, k if u else k-8) def p2n2(u, w, k, z): return (2, w if u else z, z if u else w-1, u, k-8 if u else k) def p2n(u, w, k, z): return [p2n0, p2n1, p2n2][(2-u-(2*u-1)*(k//4)) % 3](u, w, k, z) return p2n
python
def get_pegasus_to_nice_fn(*args, **kwargs): """ Returns a coordinate translation function from the 4-term pegasus_index coordinates to the 5-term "nice" coordinates. Details on the returned function, pegasus_to_nice(u,w,k,z) Inputs are 4-tuples of ints, return is a 5-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- pegasus_to_nice_fn(chimera_coordinates): a function A function that accepts augmented chimera coordinates and returns corresponding Pegasus coordinates. """ if args or kwargs: warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore") def p2n0(u, w, k, z): return (0, w-1 if u else z, z if u else w, u, k-4 if u else k-4) def p2n1(u, w, k, z): return (1, w-1 if u else z, z if u else w, u, k if u else k-8) def p2n2(u, w, k, z): return (2, w if u else z, z if u else w-1, u, k-8 if u else k) def p2n(u, w, k, z): return [p2n0, p2n1, p2n2][(2-u-(2*u-1)*(k//4)) % 3](u, w, k, z) return p2n
[ "def", "get_pegasus_to_nice_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "warnings", ".", "warn", "(", "\"Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore\"", ")", "def", "p2n0", "(", ...
Returns a coordinate translation function from the 4-term pegasus_index coordinates to the 5-term "nice" coordinates. Details on the returned function, pegasus_to_nice(u,w,k,z) Inputs are 4-tuples of ints, return is a 5-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- pegasus_to_nice_fn(chimera_coordinates): a function A function that accepts augmented chimera coordinates and returns corresponding Pegasus coordinates.
[ "Returns", "a", "coordinate", "translation", "function", "from", "the", "4", "-", "term", "pegasus_index", "coordinates", "to", "the", "5", "-", "term", "nice", "coordinates", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/pegasus.py#L599-L621
train
205,030
dwavesystems/dwave_networkx
dwave_networkx/generators/pegasus.py
get_nice_to_pegasus_fn
def get_nice_to_pegasus_fn(*args, **kwargs): """ Returns a coordinate translation function from the 5-term "nice" coordinates to the 4-term pegasus_index coordinates. Details on the returned function, nice_to_pegasus(t, y, x, u, k) Inputs are 5-tuples of ints, return is a 4-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- nice_to_pegasus_fn(pegasus_coordinates): a function A function that accepts Pegasus coordinates and returns the corresponding augmented chimera coordinates """ if args or kwargs: warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore") def c2p0(y, x, u, k): return (u, y+1 if u else x, 4+k if u else 4+k, x if u else y) def c2p1(y, x, u, k): return (u, y+1 if u else x, k if u else 8+k, x if u else y) def c2p2(y, x, u, k): return (u, y if u else x + 1, 8+k if u else k, x if u else y) def n2p(t, y, x, u, k): return [c2p0, c2p1, c2p2][t](y, x, u, k) return n2p
python
def get_nice_to_pegasus_fn(*args, **kwargs): """ Returns a coordinate translation function from the 5-term "nice" coordinates to the 4-term pegasus_index coordinates. Details on the returned function, nice_to_pegasus(t, y, x, u, k) Inputs are 5-tuples of ints, return is a 4-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- nice_to_pegasus_fn(pegasus_coordinates): a function A function that accepts Pegasus coordinates and returns the corresponding augmented chimera coordinates """ if args or kwargs: warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore") def c2p0(y, x, u, k): return (u, y+1 if u else x, 4+k if u else 4+k, x if u else y) def c2p1(y, x, u, k): return (u, y+1 if u else x, k if u else 8+k, x if u else y) def c2p2(y, x, u, k): return (u, y if u else x + 1, 8+k if u else k, x if u else y) def n2p(t, y, x, u, k): return [c2p0, c2p1, c2p2][t](y, x, u, k) return n2p
[ "def", "get_nice_to_pegasus_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "warnings", ".", "warn", "(", "\"Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore\"", ")", "def", "c2p0", "(", ...
Returns a coordinate translation function from the 5-term "nice" coordinates to the 4-term pegasus_index coordinates. Details on the returned function, nice_to_pegasus(t, y, x, u, k) Inputs are 5-tuples of ints, return is a 4-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- nice_to_pegasus_fn(pegasus_coordinates): a function A function that accepts Pegasus coordinates and returns the corresponding augmented chimera coordinates
[ "Returns", "a", "coordinate", "translation", "function", "from", "the", "5", "-", "term", "nice", "coordinates", "to", "the", "4", "-", "term", "pegasus_index", "coordinates", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/pegasus.py#L624-L646
train
205,031
dwavesystems/dwave_networkx
dwave_networkx/generators/pegasus.py
pegasus_coordinates.tuple
def tuple(self, r): """ Converts the linear_index `q` into an pegasus_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The pegasus_index node label corresponding to r """ m, m1 = self.args r, z = divmod(r, m1) r, k = divmod(r, 12) u, w = divmod(r, m) return u, w, k, z
python
def tuple(self, r): """ Converts the linear_index `q` into an pegasus_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The pegasus_index node label corresponding to r """ m, m1 = self.args r, z = divmod(r, m1) r, k = divmod(r, 12) u, w = divmod(r, m) return u, w, k, z
[ "def", "tuple", "(", "self", ",", "r", ")", ":", "m", ",", "m1", "=", "self", ".", "args", "r", ",", "z", "=", "divmod", "(", "r", ",", "m1", ")", "r", ",", "k", "=", "divmod", "(", "r", ",", "12", ")", "u", ",", "w", "=", "divmod", "("...
Converts the linear_index `q` into an pegasus_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The pegasus_index node label corresponding to r
[ "Converts", "the", "linear_index", "q", "into", "an", "pegasus_index" ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/pegasus.py#L479-L498
train
205,032
dwavesystems/dwave_networkx
dwave_networkx/generators/pegasus.py
pegasus_coordinates.ints
def ints(self, qlist): """ Converts a sequence of pegasus_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The pegasus_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist """ m, m1 = self.args return (((m * u + w) * 12 + k) * m1 + z for (u, w, k, z) in qlist)
python
def ints(self, qlist): """ Converts a sequence of pegasus_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The pegasus_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist """ m, m1 = self.args return (((m * u + w) * 12 + k) * m1 + z for (u, w, k, z) in qlist)
[ "def", "ints", "(", "self", ",", "qlist", ")", ":", "m", ",", "m1", "=", "self", ".", "args", "return", "(", "(", "(", "m", "*", "u", "+", "w", ")", "*", "12", "+", "k", ")", "*", "m1", "+", "z", "for", "(", "u", ",", "w", ",", "k", "...
Converts a sequence of pegasus_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The pegasus_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist
[ "Converts", "a", "sequence", "of", "pegasus_index", "node", "labels", "into", "linear_index", "node", "labels", "preserving", "order" ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/pegasus.py#L500-L517
train
205,033
dwavesystems/dwave_networkx
dwave_networkx/generators/pegasus.py
pegasus_coordinates.tuples
def tuples(self, rlist): """ Converts a sequence of linear_index node labels into pegasus_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The pegasus_index node lables corresponding to rlist """ m, m1 = self.args for r in rlist: r, z = divmod(r, m1) r, k = divmod(r, 12) u, w = divmod(r, m) yield u, w, k, z
python
def tuples(self, rlist): """ Converts a sequence of linear_index node labels into pegasus_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The pegasus_index node lables corresponding to rlist """ m, m1 = self.args for r in rlist: r, z = divmod(r, m1) r, k = divmod(r, 12) u, w = divmod(r, m) yield u, w, k, z
[ "def", "tuples", "(", "self", ",", "rlist", ")", ":", "m", ",", "m1", "=", "self", ".", "args", "for", "r", "in", "rlist", ":", "r", ",", "z", "=", "divmod", "(", "r", ",", "m1", ")", "r", ",", "k", "=", "divmod", "(", "r", ",", "12", ")"...
Converts a sequence of linear_index node labels into pegasus_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The pegasus_index node lables corresponding to rlist
[ "Converts", "a", "sequence", "of", "linear_index", "node", "labels", "into", "pegasus_index", "node", "labels", "preserving", "order" ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/pegasus.py#L519-L540
train
205,034
dwavesystems/dwave_networkx
dwave_networkx/generators/pegasus.py
pegasus_coordinates.__pair_repack
def __pair_repack(self, f, plist): """ Flattens a sequence of pairs to pass through `f`, and then re-pairs the result. Parameters ---------- f : callable A function that accepts a sequence and returns a sequence plist: A sequence of pairs Returns ------- qlist : sequence Equivalent to (tuple(f(p)) for p in plist) """ ulist = f(u for p in plist for u in p) for u in ulist: v = next(ulist) yield u, v
python
def __pair_repack(self, f, plist): """ Flattens a sequence of pairs to pass through `f`, and then re-pairs the result. Parameters ---------- f : callable A function that accepts a sequence and returns a sequence plist: A sequence of pairs Returns ------- qlist : sequence Equivalent to (tuple(f(p)) for p in plist) """ ulist = f(u for p in plist for u in p) for u in ulist: v = next(ulist) yield u, v
[ "def", "__pair_repack", "(", "self", ",", "f", ",", "plist", ")", ":", "ulist", "=", "f", "(", "u", "for", "p", "in", "plist", "for", "u", "in", "p", ")", "for", "u", "in", "ulist", ":", "v", "=", "next", "(", "ulist", ")", "yield", "u", ",",...
Flattens a sequence of pairs to pass through `f`, and then re-pairs the result. Parameters ---------- f : callable A function that accepts a sequence and returns a sequence plist: A sequence of pairs Returns ------- qlist : sequence Equivalent to (tuple(f(p)) for p in plist)
[ "Flattens", "a", "sequence", "of", "pairs", "to", "pass", "through", "f", "and", "then", "re", "-", "pairs", "the", "result", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/pegasus.py#L542-L562
train
205,035
dwavesystems/dwave_networkx
dwave_networkx/algorithms/markov.py
sample_markov_network
def sample_markov_network(MN, sampler=None, fixed_variables=None, return_sampleset=False, **sampler_args): """Samples from a markov network using the provided sampler. Parameters ---------- G : NetworkX graph A Markov Network as returned by :func:`.markov_network` sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. fixed_variables : dict A dictionary of variable assignments to be fixed in the markov network. return_sampleset : bool (optional, default=False) If True, returns a :obj:`dimod.SampleSet` rather than a list of samples. **sampler_args Additional keyword parameters are passed to the sampler. Returns ------- samples : list[dict]/:obj:`dimod.SampleSet` A list of samples ordered from low-to-high energy or a sample set. Examples -------- >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler) >>> samples[0] {'a': 0, 'b': 0} >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler, return_sampleset=True) >>> samples.first Sample(sample={'a': 0, 'b': 0}, energy=-1.0, num_occurrences=1) >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}, ... ('b', 'c'): {(0, 0): -9, ... (0, 1): 1.2, ... (1, 0): 7.2, ... (1, 1): 5}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler, fixed_variables={'b': 0}) >>> samples[0] {'a': 0, 'c': 0, 'b': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ bqm = markov_network_bqm(MN) # use the FixedVar fv_sampler = dimod.FixedVariableComposite(sampler) sampleset = fv_sampler.sample(bqm, fixed_variables=fixed_variables, **sampler_args) if return_sampleset: return sampleset else: return list(map(dict, sampleset.samples()))
python
def sample_markov_network(MN, sampler=None, fixed_variables=None, return_sampleset=False, **sampler_args): """Samples from a markov network using the provided sampler. Parameters ---------- G : NetworkX graph A Markov Network as returned by :func:`.markov_network` sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. fixed_variables : dict A dictionary of variable assignments to be fixed in the markov network. return_sampleset : bool (optional, default=False) If True, returns a :obj:`dimod.SampleSet` rather than a list of samples. **sampler_args Additional keyword parameters are passed to the sampler. Returns ------- samples : list[dict]/:obj:`dimod.SampleSet` A list of samples ordered from low-to-high energy or a sample set. Examples -------- >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler) >>> samples[0] {'a': 0, 'b': 0} >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler, return_sampleset=True) >>> samples.first Sample(sample={'a': 0, 'b': 0}, energy=-1.0, num_occurrences=1) >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}, ... ('b', 'c'): {(0, 0): -9, ... (0, 1): 1.2, ... (1, 0): 7.2, ... (1, 1): 5}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler, fixed_variables={'b': 0}) >>> samples[0] {'a': 0, 'c': 0, 'b': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ bqm = markov_network_bqm(MN) # use the FixedVar fv_sampler = dimod.FixedVariableComposite(sampler) sampleset = fv_sampler.sample(bqm, fixed_variables=fixed_variables, **sampler_args) if return_sampleset: return sampleset else: return list(map(dict, sampleset.samples()))
[ "def", "sample_markov_network", "(", "MN", ",", "sampler", "=", "None", ",", "fixed_variables", "=", "None", ",", "return_sampleset", "=", "False", ",", "*", "*", "sampler_args", ")", ":", "bqm", "=", "markov_network_bqm", "(", "MN", ")", "# use the FixedVar",...
Samples from a markov network using the provided sampler. Parameters ---------- G : NetworkX graph A Markov Network as returned by :func:`.markov_network` sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. fixed_variables : dict A dictionary of variable assignments to be fixed in the markov network. return_sampleset : bool (optional, default=False) If True, returns a :obj:`dimod.SampleSet` rather than a list of samples. **sampler_args Additional keyword parameters are passed to the sampler. Returns ------- samples : list[dict]/:obj:`dimod.SampleSet` A list of samples ordered from low-to-high energy or a sample set. Examples -------- >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler) >>> samples[0] {'a': 0, 'b': 0} >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler, return_sampleset=True) >>> samples.first Sample(sample={'a': 0, 'b': 0}, energy=-1.0, num_occurrences=1) >>> import dimod ... >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}, ... ('b', 'c'): {(0, 0): -9, ... (0, 1): 1.2, ... (1, 0): 7.2, ... (1, 1): 5}} >>> MN = dnx.markov_network(potentials) >>> sampler = dimod.ExactSolver() >>> samples = dnx.sample_markov_network(MN, sampler, fixed_variables={'b': 0}) >>> samples[0] {'a': 0, 'c': 0, 'b': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample.
[ "Samples", "from", "a", "markov", "network", "using", "the", "provided", "sampler", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/markov.py#L57-L153
train
205,036
dwavesystems/dwave_networkx
dwave_networkx/algorithms/markov.py
markov_network_bqm
def markov_network_bqm(MN): """Construct a binary quadratic model for a markov network. Parameters ---------- G : NetworkX graph A Markov Network as returned by :func:`.markov_network` Returns ------- bqm : :obj:`dimod.BinaryQuadraticModel` A binary quadratic model. """ bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY) # the variable potentials for v, ddict in MN.nodes(data=True, default=None): potential = ddict.get('potential', None) if potential is None: continue # for single nodes we don't need to worry about order phi0 = potential[(0,)] phi1 = potential[(1,)] bqm.add_variable(v, phi1 - phi0) bqm.add_offset(phi0) # the interaction potentials for u, v, ddict in MN.edges(data=True, default=None): potential = ddict.get('potential', None) if potential is None: continue # in python<=3.5 the edge order might not be consistent so we use the # one that was stored order = ddict['order'] u, v = order phi00 = potential[(0, 0)] phi01 = potential[(0, 1)] phi10 = potential[(1, 0)] phi11 = potential[(1, 1)] bqm.add_variable(u, phi10 - phi00) bqm.add_variable(v, phi01 - phi00) bqm.add_interaction(u, v, phi11 - phi10 - phi01 + phi00) bqm.add_offset(phi00) return bqm
python
def markov_network_bqm(MN): """Construct a binary quadratic model for a markov network. Parameters ---------- G : NetworkX graph A Markov Network as returned by :func:`.markov_network` Returns ------- bqm : :obj:`dimod.BinaryQuadraticModel` A binary quadratic model. """ bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY) # the variable potentials for v, ddict in MN.nodes(data=True, default=None): potential = ddict.get('potential', None) if potential is None: continue # for single nodes we don't need to worry about order phi0 = potential[(0,)] phi1 = potential[(1,)] bqm.add_variable(v, phi1 - phi0) bqm.add_offset(phi0) # the interaction potentials for u, v, ddict in MN.edges(data=True, default=None): potential = ddict.get('potential', None) if potential is None: continue # in python<=3.5 the edge order might not be consistent so we use the # one that was stored order = ddict['order'] u, v = order phi00 = potential[(0, 0)] phi01 = potential[(0, 1)] phi10 = potential[(1, 0)] phi11 = potential[(1, 1)] bqm.add_variable(u, phi10 - phi00) bqm.add_variable(v, phi01 - phi00) bqm.add_interaction(u, v, phi11 - phi10 - phi01 + phi00) bqm.add_offset(phi00) return bqm
[ "def", "markov_network_bqm", "(", "MN", ")", ":", "bqm", "=", "dimod", ".", "BinaryQuadraticModel", ".", "empty", "(", "dimod", ".", "BINARY", ")", "# the variable potentials", "for", "v", ",", "ddict", "in", "MN", ".", "nodes", "(", "data", "=", "True", ...
Construct a binary quadratic model for a markov network. Parameters ---------- G : NetworkX graph A Markov Network as returned by :func:`.markov_network` Returns ------- bqm : :obj:`dimod.BinaryQuadraticModel` A binary quadratic model.
[ "Construct", "a", "binary", "quadratic", "model", "for", "a", "markov", "network", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/markov.py#L156-L211
train
205,037
dwavesystems/dwave_networkx
dwave_networkx/drawing/chimera_layout.py
chimera_layout
def chimera_layout(G, scale=1., center=None, dim=2): """Positions the nodes of graph G in a Chimera cross topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. If every node in G has a `chimera_index` attribute, those are used to place the nodes. Otherwise makes a best-effort attempt to find positions. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.chimera_graph(1) >>> pos = dnx.chimera_layout(G) """ if not isinstance(G, nx.Graph): empty_graph = nx.Graph() empty_graph.add_edges_from(G) G = empty_graph # now we get chimera coordinates for the translation # first, check if we made it if G.graph.get("family") == "chimera": m = G.graph['rows'] n = G.graph['columns'] t = G.graph['tile'] # get a node placement function xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim) if G.graph.get('labels') == 'coordinate': pos = {v: xy_coords(*v) for v in G.nodes()} elif G.graph.get('data'): pos = {v: xy_coords(*dat['chimera_index']) for v, dat in G.nodes(data=True)} else: coord = chimera_coordinates(m, n, t) pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()} else: # best case scenario, each node in G has a chimera_index attribute. Otherwise # we will try to determine it using the find_chimera_indices function. if all('chimera_index' in dat for __, dat in G.nodes(data=True)): chimera_indices = {v: dat['chimera_index'] for v, dat in G.nodes(data=True)} else: chimera_indices = find_chimera_indices(G) # we could read these off of the name attribute for G, but we would want the values in # the nodes to override the name in case of conflict. m = max(idx[0] for idx in itervalues(chimera_indices)) + 1 n = max(idx[1] for idx in itervalues(chimera_indices)) + 1 t = max(idx[3] for idx in itervalues(chimera_indices)) + 1 xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim) # compute our coordinates pos = {v: xy_coords(i, j, u, k) for v, (i, j, u, k) in iteritems(chimera_indices)} return pos
python
def chimera_layout(G, scale=1., center=None, dim=2): """Positions the nodes of graph G in a Chimera cross topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. If every node in G has a `chimera_index` attribute, those are used to place the nodes. Otherwise makes a best-effort attempt to find positions. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.chimera_graph(1) >>> pos = dnx.chimera_layout(G) """ if not isinstance(G, nx.Graph): empty_graph = nx.Graph() empty_graph.add_edges_from(G) G = empty_graph # now we get chimera coordinates for the translation # first, check if we made it if G.graph.get("family") == "chimera": m = G.graph['rows'] n = G.graph['columns'] t = G.graph['tile'] # get a node placement function xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim) if G.graph.get('labels') == 'coordinate': pos = {v: xy_coords(*v) for v in G.nodes()} elif G.graph.get('data'): pos = {v: xy_coords(*dat['chimera_index']) for v, dat in G.nodes(data=True)} else: coord = chimera_coordinates(m, n, t) pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()} else: # best case scenario, each node in G has a chimera_index attribute. Otherwise # we will try to determine it using the find_chimera_indices function. if all('chimera_index' in dat for __, dat in G.nodes(data=True)): chimera_indices = {v: dat['chimera_index'] for v, dat in G.nodes(data=True)} else: chimera_indices = find_chimera_indices(G) # we could read these off of the name attribute for G, but we would want the values in # the nodes to override the name in case of conflict. m = max(idx[0] for idx in itervalues(chimera_indices)) + 1 n = max(idx[1] for idx in itervalues(chimera_indices)) + 1 t = max(idx[3] for idx in itervalues(chimera_indices)) + 1 xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim) # compute our coordinates pos = {v: xy_coords(i, j, u, k) for v, (i, j, u, k) in iteritems(chimera_indices)} return pos
[ "def", "chimera_layout", "(", "G", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ")", ":", "if", "not", "isinstance", "(", "G", ",", "nx", ".", "Graph", ")", ":", "empty_graph", "=", "nx", ".", "Graph", "(", ")", "e...
Positions the nodes of graph G in a Chimera cross topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. If every node in G has a `chimera_index` attribute, those are used to place the nodes. Otherwise makes a best-effort attempt to find positions. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.chimera_graph(1) >>> pos = dnx.chimera_layout(G)
[ "Positions", "the", "nodes", "of", "graph", "G", "in", "a", "Chimera", "cross", "topology", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/chimera_layout.py#L44-L119
train
205,038
dwavesystems/dwave_networkx
dwave_networkx/drawing/chimera_layout.py
chimera_node_placer_2d
def chimera_node_placer_2d(m, n, t, scale=1., center=None, dim=2): """Generates a function that converts Chimera indices to x, y coordinates for a plot. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int Number of columns in the Chimera lattice. t : int Size of the shore within each Chimera tile. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- xy_coords : function A function that maps a Chimera index (i, j, u, k) in an (m, n, t) Chimera lattice to x,y coordinates such as used by a plot. """ import numpy as np tile_center = t // 2 tile_length = t + 3 # 1 for middle of cross, 2 for spacing between tiles # want the enter plot to fill in [0, 1] when scale=1 scale /= max(m, n) * tile_length - 3 grid_offsets = {} if center is None: center = np.zeros(dim) else: center = np.asarray(center) paddims = dim - 2 if paddims < 0: raise ValueError("layout must have at least two dimensions") if len(center) != dim: raise ValueError("length of center coordinates must match dimension of layout") def _xy_coords(i, j, u, k): # row, col, shore, shore index # first get the coordinatiates within the tile if k < tile_center: p = k else: p = k + 1 if u: xy = np.array([tile_center, -1 * p]) else: xy = np.array([p, -1 * tile_center]) # next offset the corrdinates based on the which tile if i > 0 or j > 0: if (i, j) in grid_offsets: xy += grid_offsets[(i, j)] else: off = np.array([j * tile_length, -1 * i * tile_length]) xy += off grid_offsets[(i, j)] = off # convention for Chimera-lattice pictures is to invert the y-axis return np.hstack((xy * scale, np.zeros(paddims))) + center return _xy_coords
python
def chimera_node_placer_2d(m, n, t, scale=1., center=None, dim=2): """Generates a function that converts Chimera indices to x, y coordinates for a plot. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int Number of columns in the Chimera lattice. t : int Size of the shore within each Chimera tile. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- xy_coords : function A function that maps a Chimera index (i, j, u, k) in an (m, n, t) Chimera lattice to x,y coordinates such as used by a plot. """ import numpy as np tile_center = t // 2 tile_length = t + 3 # 1 for middle of cross, 2 for spacing between tiles # want the enter plot to fill in [0, 1] when scale=1 scale /= max(m, n) * tile_length - 3 grid_offsets = {} if center is None: center = np.zeros(dim) else: center = np.asarray(center) paddims = dim - 2 if paddims < 0: raise ValueError("layout must have at least two dimensions") if len(center) != dim: raise ValueError("length of center coordinates must match dimension of layout") def _xy_coords(i, j, u, k): # row, col, shore, shore index # first get the coordinatiates within the tile if k < tile_center: p = k else: p = k + 1 if u: xy = np.array([tile_center, -1 * p]) else: xy = np.array([p, -1 * tile_center]) # next offset the corrdinates based on the which tile if i > 0 or j > 0: if (i, j) in grid_offsets: xy += grid_offsets[(i, j)] else: off = np.array([j * tile_length, -1 * i * tile_length]) xy += off grid_offsets[(i, j)] = off # convention for Chimera-lattice pictures is to invert the y-axis return np.hstack((xy * scale, np.zeros(paddims))) + center return _xy_coords
[ "def", "chimera_node_placer_2d", "(", "m", ",", "n", ",", "t", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ")", ":", "import", "numpy", "as", "np", "tile_center", "=", "t", "//", "2", "tile_length", "=", "t", "+", "...
Generates a function that converts Chimera indices to x, y coordinates for a plot. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int Number of columns in the Chimera lattice. t : int Size of the shore within each Chimera tile. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- xy_coords : function A function that maps a Chimera index (i, j, u, k) in an (m, n, t) Chimera lattice to x,y coordinates such as used by a plot.
[ "Generates", "a", "function", "that", "converts", "Chimera", "indices", "to", "x", "y", "coordinates", "for", "a", "plot", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/chimera_layout.py#L122-L203
train
205,039
dwavesystems/dwave_networkx
dwave_networkx/drawing/chimera_layout.py
draw_chimera_embedding
def draw_chimera_embedding(G, *args, **kwargs): """Draws an embedding onto the chimera graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. """ draw_embedding(G, chimera_layout(G), *args, **kwargs)
python
def draw_chimera_embedding(G, *args, **kwargs): """Draws an embedding onto the chimera graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. """ draw_embedding(G, chimera_layout(G), *args, **kwargs)
[ "def", "draw_chimera_embedding", "(", "G", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "draw_embedding", "(", "G", ",", "chimera_layout", "(", "G", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Draws an embedding onto the chimera graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
[ "Draws", "an", "embedding", "onto", "the", "chimera", "graph", "G", "according", "to", "layout", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/chimera_layout.py#L246-L292
train
205,040
dwavesystems/dwave_networkx
dwave_networkx/generators/chimera.py
find_chimera_indices
def find_chimera_indices(G): """Attempts to determine the Chimera indices of the nodes in graph G. See the `chimera_graph()` function for a definition of a Chimera graph and Chimera indices. Parameters ---------- G : NetworkX graph Should be a single-tile Chimera graph. Returns ------- chimera_indices : dict A dict of the form {node: (i, j, u, k), ...} where (i, j, u, k) is a 4-tuple of integer Chimera indices. Examples -------- >>> G = dnx.chimera_graph(1, 1, 4) >>> chimera_indices = dnx.find_chimera_indices(G) >>> G = nx.Graph() >>> G.add_edges_from([(0, 2), (1, 2), (1, 3), (0, 3)]) >>> chimera_indices = dnx.find_chimera_indices(G) >>> nx.set_node_attributes(G, chimera_indices, 'chimera_index') """ # if the nodes are orderable, we want the lowest-order one. try: nlist = sorted(G.nodes) except TypeError: nlist = G.nodes() n_nodes = len(nlist) # create the object that will store the indices chimera_indices = {} # ok, let's first check for the simple cases if n_nodes == 0: return chimera_indices elif n_nodes == 1: raise DWaveNetworkXException( 'Singleton graphs are not Chimera-structured') elif n_nodes == 2: return {nlist[0]: (0, 0, 0, 0), nlist[1]: (0, 0, 1, 0)} # next, let's get the bicoloring of the graph; this raises an exception if the graph is # not bipartite coloring = color(G) # we want the color of the node to be the u term in the Chimera-index, so we want the # first node in nlist to be color 0 if coloring[nlist[0]] == 1: coloring = {v: 1 - coloring[v] for v in coloring} # we also want the diameter of the graph # claim: diameter(G) == m + n for |G| > 2 dia = diameter(G) # we have already handled the |G| <= 2 case, so we know, for diameter == 2, that the Chimera # graph is a single tile if dia == 2: shore_indices = [0, 0] for v in nlist: u = coloring[v] chimera_indices[v] = (0, 0, u, shore_indices[u]) shore_indices[u] += 1 return chimera_indices # NB: max degree == shore size <==> one tile raise Exception('not yet implemented for Chimera graphs with more than one tile')
python
def find_chimera_indices(G): """Attempts to determine the Chimera indices of the nodes in graph G. See the `chimera_graph()` function for a definition of a Chimera graph and Chimera indices. Parameters ---------- G : NetworkX graph Should be a single-tile Chimera graph. Returns ------- chimera_indices : dict A dict of the form {node: (i, j, u, k), ...} where (i, j, u, k) is a 4-tuple of integer Chimera indices. Examples -------- >>> G = dnx.chimera_graph(1, 1, 4) >>> chimera_indices = dnx.find_chimera_indices(G) >>> G = nx.Graph() >>> G.add_edges_from([(0, 2), (1, 2), (1, 3), (0, 3)]) >>> chimera_indices = dnx.find_chimera_indices(G) >>> nx.set_node_attributes(G, chimera_indices, 'chimera_index') """ # if the nodes are orderable, we want the lowest-order one. try: nlist = sorted(G.nodes) except TypeError: nlist = G.nodes() n_nodes = len(nlist) # create the object that will store the indices chimera_indices = {} # ok, let's first check for the simple cases if n_nodes == 0: return chimera_indices elif n_nodes == 1: raise DWaveNetworkXException( 'Singleton graphs are not Chimera-structured') elif n_nodes == 2: return {nlist[0]: (0, 0, 0, 0), nlist[1]: (0, 0, 1, 0)} # next, let's get the bicoloring of the graph; this raises an exception if the graph is # not bipartite coloring = color(G) # we want the color of the node to be the u term in the Chimera-index, so we want the # first node in nlist to be color 0 if coloring[nlist[0]] == 1: coloring = {v: 1 - coloring[v] for v in coloring} # we also want the diameter of the graph # claim: diameter(G) == m + n for |G| > 2 dia = diameter(G) # we have already handled the |G| <= 2 case, so we know, for diameter == 2, that the Chimera # graph is a single tile if dia == 2: shore_indices = [0, 0] for v in nlist: u = coloring[v] chimera_indices[v] = (0, 0, u, shore_indices[u]) shore_indices[u] += 1 return chimera_indices # NB: max degree == shore size <==> one tile raise Exception('not yet implemented for Chimera graphs with more than one tile')
[ "def", "find_chimera_indices", "(", "G", ")", ":", "# if the nodes are orderable, we want the lowest-order one.", "try", ":", "nlist", "=", "sorted", "(", "G", ".", "nodes", ")", "except", "TypeError", ":", "nlist", "=", "G", ".", "nodes", "(", ")", "n_nodes", ...
Attempts to determine the Chimera indices of the nodes in graph G. See the `chimera_graph()` function for a definition of a Chimera graph and Chimera indices. Parameters ---------- G : NetworkX graph Should be a single-tile Chimera graph. Returns ------- chimera_indices : dict A dict of the form {node: (i, j, u, k), ...} where (i, j, u, k) is a 4-tuple of integer Chimera indices. Examples -------- >>> G = dnx.chimera_graph(1, 1, 4) >>> chimera_indices = dnx.find_chimera_indices(G) >>> G = nx.Graph() >>> G.add_edges_from([(0, 2), (1, 2), (1, 3), (0, 3)]) >>> chimera_indices = dnx.find_chimera_indices(G) >>> nx.set_node_attributes(G, chimera_indices, 'chimera_index')
[ "Attempts", "to", "determine", "the", "Chimera", "indices", "of", "the", "nodes", "in", "graph", "G", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/chimera.py#L207-L283
train
205,041
dwavesystems/dwave_networkx
dwave_networkx/generators/chimera.py
chimera_elimination_order
def chimera_elimination_order(m, n=None, t=None): """Provides a variable elimination order for a Chimera graph. A graph defined by chimera_graph(m,n,t) has treewidth max(m,n)*t. This function outputs a variable elimination order inducing a tree decomposition of that width. Parameters ---------- 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 ------- order : list An elimination order that induces the treewidth of chimera_graph(m,n,t). Examples -------- >>> G = dnx.chimera_elimination_order(1, 1, 4) # a single Chimera tile """ if n is None: n = m if t is None: t = 4 index_flip = m > n if index_flip: m, n = n, m def chimeraI(m0, n0, k0, l0): if index_flip: return m*2*t*n0 + 2*t*m0 + t*(1-k0) + l0 else: return n*2*t*m0 + 2*t*n0 + t*k0 + l0 order = [] for n_i in range(n): for t_i in range(t): for m_i in range(m): order.append(chimeraI(m_i, n_i, 0, t_i)) for n_i in range(n): for m_i in range(m): for t_i in range(t): order.append(chimeraI(m_i, n_i, 1, t_i)) return order
python
def chimera_elimination_order(m, n=None, t=None): """Provides a variable elimination order for a Chimera graph. A graph defined by chimera_graph(m,n,t) has treewidth max(m,n)*t. This function outputs a variable elimination order inducing a tree decomposition of that width. Parameters ---------- 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 ------- order : list An elimination order that induces the treewidth of chimera_graph(m,n,t). Examples -------- >>> G = dnx.chimera_elimination_order(1, 1, 4) # a single Chimera tile """ if n is None: n = m if t is None: t = 4 index_flip = m > n if index_flip: m, n = n, m def chimeraI(m0, n0, k0, l0): if index_flip: return m*2*t*n0 + 2*t*m0 + t*(1-k0) + l0 else: return n*2*t*m0 + 2*t*n0 + t*k0 + l0 order = [] for n_i in range(n): for t_i in range(t): for m_i in range(m): order.append(chimeraI(m_i, n_i, 0, t_i)) for n_i in range(n): for m_i in range(m): for t_i in range(t): order.append(chimeraI(m_i, n_i, 1, t_i)) return order
[ "def", "chimera_elimination_order", "(", "m", ",", "n", "=", "None", ",", "t", "=", "None", ")", ":", "if", "n", "is", "None", ":", "n", "=", "m", "if", "t", "is", "None", ":", "t", "=", "4", "index_flip", "=", "m", ">", "n", "if", "index_flip"...
Provides a variable elimination order for a Chimera graph. A graph defined by chimera_graph(m,n,t) has treewidth max(m,n)*t. This function outputs a variable elimination order inducing a tree decomposition of that width. Parameters ---------- 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 ------- order : list An elimination order that induces the treewidth of chimera_graph(m,n,t). Examples -------- >>> G = dnx.chimera_elimination_order(1, 1, 4) # a single Chimera tile
[ "Provides", "a", "variable", "elimination", "order", "for", "a", "Chimera", "graph", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/chimera.py#L286-L341
train
205,042
dwavesystems/dwave_networkx
dwave_networkx/generators/chimera.py
chimera_coordinates.tuple
def tuple(self, r): """ Converts the linear_index `q` into an chimera_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The chimera_index node label corresponding to r """ m, n, t = self.args r, k = divmod(r, t) r, u = divmod(r, 2) i, j = divmod(r, n) return i, j, u, k
python
def tuple(self, r): """ Converts the linear_index `q` into an chimera_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The chimera_index node label corresponding to r """ m, n, t = self.args r, k = divmod(r, t) r, u = divmod(r, 2) i, j = divmod(r, n) return i, j, u, k
[ "def", "tuple", "(", "self", ",", "r", ")", ":", "m", ",", "n", ",", "t", "=", "self", ".", "args", "r", ",", "k", "=", "divmod", "(", "r", ",", "t", ")", "r", ",", "u", "=", "divmod", "(", "r", ",", "2", ")", "i", ",", "j", "=", "div...
Converts the linear_index `q` into an chimera_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The chimera_index node label corresponding to r
[ "Converts", "the", "linear_index", "q", "into", "an", "chimera_index" ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/chimera.py#L380-L399
train
205,043
dwavesystems/dwave_networkx
dwave_networkx/generators/chimera.py
chimera_coordinates.ints
def ints(self, qlist): """ Converts a sequence of chimera_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The chimera_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist """ m, n, t = self.args return (((n*i + j)*2 + u)*t + k for (i, j, u, k) in qlist)
python
def ints(self, qlist): """ Converts a sequence of chimera_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The chimera_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist """ m, n, t = self.args return (((n*i + j)*2 + u)*t + k for (i, j, u, k) in qlist)
[ "def", "ints", "(", "self", ",", "qlist", ")", ":", "m", ",", "n", ",", "t", "=", "self", ".", "args", "return", "(", "(", "(", "n", "*", "i", "+", "j", ")", "*", "2", "+", "u", ")", "*", "t", "+", "k", "for", "(", "i", ",", "j", ",",...
Converts a sequence of chimera_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The chimera_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist
[ "Converts", "a", "sequence", "of", "chimera_index", "node", "labels", "into", "linear_index", "node", "labels", "preserving", "order" ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/chimera.py#L401-L418
train
205,044
dwavesystems/dwave_networkx
dwave_networkx/generators/chimera.py
chimera_coordinates.tuples
def tuples(self, rlist): """ Converts a sequence of linear_index node labels into chimera_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The chimera_lindex node lables corresponding to rlist """ m, n, t = self.args for r in rlist: r, k = divmod(r, t) r, u = divmod(r, 2) i, j = divmod(r, n) yield i, j, u, k
python
def tuples(self, rlist): """ Converts a sequence of linear_index node labels into chimera_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The chimera_lindex node lables corresponding to rlist """ m, n, t = self.args for r in rlist: r, k = divmod(r, t) r, u = divmod(r, 2) i, j = divmod(r, n) yield i, j, u, k
[ "def", "tuples", "(", "self", ",", "rlist", ")", ":", "m", ",", "n", ",", "t", "=", "self", ".", "args", "for", "r", "in", "rlist", ":", "r", ",", "k", "=", "divmod", "(", "r", ",", "t", ")", "r", ",", "u", "=", "divmod", "(", "r", ",", ...
Converts a sequence of linear_index node labels into chimera_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The chimera_lindex node lables corresponding to rlist
[ "Converts", "a", "sequence", "of", "linear_index", "node", "labels", "into", "chimera_index", "node", "labels", "preserving", "order" ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/generators/chimera.py#L420-L441
train
205,045
dwavesystems/dwave_networkx
dwave_networkx/algorithms/social.py
structural_imbalance
def structural_imbalance(S, sampler=None, **sampler_args): """Returns an approximate set of frustrated edges and a bicoloring. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters ---------- S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrainted Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- frustrated_edges : dict A dictionary of the edges that violate the edge sign. The imbalance of the network is the length of frustrated_edges. colors: dict A bicoloring of the nodes into two factions. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- >>> import dimod >>> sampler = dimod.ExactSolver() >>> S = nx.Graph() >>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly >>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile >>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler) >>> print(frustrated_edges) {} >>> print(colors) # doctest: +SKIP {'Alice': 0, 'Bob': 0, 'Eve': 1} >>> S.add_edge('Ted', 'Bob', sign=1) # Ted is friendly with all >>> S.add_edge('Ted', 'Alice', sign=1) >>> S.add_edge('Ted', 'Eve', sign=1) >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler) >>> print(frustrated_edges) {('Ted', 'Eve'): {'sign': 1}} >>> print(colors) # doctest: +SKIP {'Bob': 1, 'Ted': 1, 'Alice': 1, 'Eve': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_ .. [FIA] Facchetti, G., Iacono G., and Altafini C. (2011). Computing global structural balance in large-scale signed social networks. PNAS, 108, no. 52, 20953-20958 """ h, J = structural_imbalance_ising(S) # use the sampler to find low energy states response = sampler.sample_ising(h, J, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # spins determine the color colors = {v: (spin + 1) // 2 for v, spin in iteritems(sample)} # frustrated edges are the ones that are violated frustrated_edges = {} for u, v, data in S.edges(data=True): sign = data['sign'] if sign > 0 and colors[u] != colors[v]: frustrated_edges[(u, v)] = data elif sign < 0 and colors[u] == colors[v]: frustrated_edges[(u, v)] = data # else: not frustrated or sign == 0, no relation to violate return frustrated_edges, colors
python
def structural_imbalance(S, sampler=None, **sampler_args): """Returns an approximate set of frustrated edges and a bicoloring. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters ---------- S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrainted Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- frustrated_edges : dict A dictionary of the edges that violate the edge sign. The imbalance of the network is the length of frustrated_edges. colors: dict A bicoloring of the nodes into two factions. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- >>> import dimod >>> sampler = dimod.ExactSolver() >>> S = nx.Graph() >>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly >>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile >>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler) >>> print(frustrated_edges) {} >>> print(colors) # doctest: +SKIP {'Alice': 0, 'Bob': 0, 'Eve': 1} >>> S.add_edge('Ted', 'Bob', sign=1) # Ted is friendly with all >>> S.add_edge('Ted', 'Alice', sign=1) >>> S.add_edge('Ted', 'Eve', sign=1) >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler) >>> print(frustrated_edges) {('Ted', 'Eve'): {'sign': 1}} >>> print(colors) # doctest: +SKIP {'Bob': 1, 'Ted': 1, 'Alice': 1, 'Eve': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_ .. [FIA] Facchetti, G., Iacono G., and Altafini C. (2011). Computing global structural balance in large-scale signed social networks. PNAS, 108, no. 52, 20953-20958 """ h, J = structural_imbalance_ising(S) # use the sampler to find low energy states response = sampler.sample_ising(h, J, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # spins determine the color colors = {v: (spin + 1) // 2 for v, spin in iteritems(sample)} # frustrated edges are the ones that are violated frustrated_edges = {} for u, v, data in S.edges(data=True): sign = data['sign'] if sign > 0 and colors[u] != colors[v]: frustrated_edges[(u, v)] = data elif sign < 0 and colors[u] == colors[v]: frustrated_edges[(u, v)] = data # else: not frustrated or sign == 0, no relation to violate return frustrated_edges, colors
[ "def", "structural_imbalance", "(", "S", ",", "sampler", "=", "None", ",", "*", "*", "sampler_args", ")", ":", "h", ",", "J", "=", "structural_imbalance_ising", "(", "S", ")", "# use the sampler to find low energy states", "response", "=", "sampler", ".", "sampl...
Returns an approximate set of frustrated edges and a bicoloring. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters ---------- S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrainted Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- frustrated_edges : dict A dictionary of the edges that violate the edge sign. The imbalance of the network is the length of frustrated_edges. colors: dict A bicoloring of the nodes into two factions. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- >>> import dimod >>> sampler = dimod.ExactSolver() >>> S = nx.Graph() >>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly >>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile >>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler) >>> print(frustrated_edges) {} >>> print(colors) # doctest: +SKIP {'Alice': 0, 'Bob': 0, 'Eve': 1} >>> S.add_edge('Ted', 'Bob', sign=1) # Ted is friendly with all >>> S.add_edge('Ted', 'Alice', sign=1) >>> S.add_edge('Ted', 'Eve', sign=1) >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler) >>> print(frustrated_edges) {('Ted', 'Eve'): {'sign': 1}} >>> print(colors) # doctest: +SKIP {'Bob': 1, 'Ted': 1, 'Alice': 1, 'Eve': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_ .. [FIA] Facchetti, G., Iacono G., and Altafini C. (2011). Computing global structural balance in large-scale signed social networks. PNAS, 108, no. 52, 20953-20958
[ "Returns", "an", "approximate", "set", "of", "frustrated", "edges", "and", "a", "bicoloring", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/social.py#L29-L133
train
205,046
dwavesystems/dwave_networkx
dwave_networkx/algorithms/social.py
structural_imbalance_ising
def structural_imbalance_ising(S): """Construct the Ising problem to calculate the structural imbalance of a signed social network. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters ---------- S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. Returns ------- h : dict The linear biases of the Ising problem. Each variable in the Ising problem represent a node in the signed social network. The solution that minimized the Ising problem will assign each variable a value, either -1 or 1. This bi-coloring defines the factions. J : dict The quadratic biases of the Ising problem. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- >>> import dimod >>> from dwave_networkx.algorithms.social import structural_imbalance_ising ... >>> S = nx.Graph() >>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly >>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile >>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile ... >>> h, J = structural_imbalance_ising(S) >>> h # doctest: +SKIP {'Alice': 0.0, 'Bob': 0.0, 'Eve': 0.0} >>> J # doctest: +SKIP {('Alice', 'Bob'): -1.0, ('Alice', 'Eve'): 1.0, ('Bob', 'Eve'): 1.0} """ h = {v: 0.0 for v in S} J = {} for u, v, data in S.edges(data=True): try: J[(u, v)] = -1. * data['sign'] except KeyError: raise ValueError(("graph should be a signed social graph," "each edge should have a 'sign' attr")) return h, J
python
def structural_imbalance_ising(S): """Construct the Ising problem to calculate the structural imbalance of a signed social network. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters ---------- S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. Returns ------- h : dict The linear biases of the Ising problem. Each variable in the Ising problem represent a node in the signed social network. The solution that minimized the Ising problem will assign each variable a value, either -1 or 1. This bi-coloring defines the factions. J : dict The quadratic biases of the Ising problem. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- >>> import dimod >>> from dwave_networkx.algorithms.social import structural_imbalance_ising ... >>> S = nx.Graph() >>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly >>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile >>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile ... >>> h, J = structural_imbalance_ising(S) >>> h # doctest: +SKIP {'Alice': 0.0, 'Bob': 0.0, 'Eve': 0.0} >>> J # doctest: +SKIP {('Alice', 'Bob'): -1.0, ('Alice', 'Eve'): 1.0, ('Bob', 'Eve'): 1.0} """ h = {v: 0.0 for v in S} J = {} for u, v, data in S.edges(data=True): try: J[(u, v)] = -1. * data['sign'] except KeyError: raise ValueError(("graph should be a signed social graph," "each edge should have a 'sign' attr")) return h, J
[ "def", "structural_imbalance_ising", "(", "S", ")", ":", "h", "=", "{", "v", ":", "0.0", "for", "v", "in", "S", "}", "J", "=", "{", "}", "for", "u", ",", "v", ",", "data", "in", "S", ".", "edges", "(", "data", "=", "True", ")", ":", "try", ...
Construct the Ising problem to calculate the structural imbalance of a signed social network. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters ---------- S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. Returns ------- h : dict The linear biases of the Ising problem. Each variable in the Ising problem represent a node in the signed social network. The solution that minimized the Ising problem will assign each variable a value, either -1 or 1. This bi-coloring defines the factions. J : dict The quadratic biases of the Ising problem. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- >>> import dimod >>> from dwave_networkx.algorithms.social import structural_imbalance_ising ... >>> S = nx.Graph() >>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly >>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile >>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile ... >>> h, J = structural_imbalance_ising(S) >>> h # doctest: +SKIP {'Alice': 0.0, 'Bob': 0.0, 'Eve': 0.0} >>> J # doctest: +SKIP {('Alice', 'Bob'): -1.0, ('Alice', 'Eve'): 1.0, ('Bob', 'Eve'): 1.0}
[ "Construct", "the", "Ising", "problem", "to", "calculate", "the", "structural", "imbalance", "of", "a", "signed", "social", "network", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/social.py#L136-L193
train
205,047
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
is_simplicial
def is_simplicial(G, n): """Determines whether a node n in G is simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is simplicial. n : node A node in graph G. Returns ------- is_simplicial : bool True if its neighbors form a clique. Examples -------- This example checks whether node 0 is simplicial for two graphs: G, a single Chimera unit cell, which is bipartite, and K_5, the :math:`K_5` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> G = dnx.chimera_graph(1, 1, 4) >>> K_5 = nx.complete_graph(5) >>> dnx.is_simplicial(G, 0) False >>> dnx.is_simplicial(K_5, 0) True """ return all(u in G[v] for u, v in itertools.combinations(G[n], 2))
python
def is_simplicial(G, n): """Determines whether a node n in G is simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is simplicial. n : node A node in graph G. Returns ------- is_simplicial : bool True if its neighbors form a clique. Examples -------- This example checks whether node 0 is simplicial for two graphs: G, a single Chimera unit cell, which is bipartite, and K_5, the :math:`K_5` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> G = dnx.chimera_graph(1, 1, 4) >>> K_5 = nx.complete_graph(5) >>> dnx.is_simplicial(G, 0) False >>> dnx.is_simplicial(K_5, 0) True """ return all(u in G[v] for u, v in itertools.combinations(G[n], 2))
[ "def", "is_simplicial", "(", "G", ",", "n", ")", ":", "return", "all", "(", "u", "in", "G", "[", "v", "]", "for", "u", ",", "v", "in", "itertools", ".", "combinations", "(", "G", "[", "n", "]", ",", "2", ")", ")" ]
Determines whether a node n in G is simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is simplicial. n : node A node in graph G. Returns ------- is_simplicial : bool True if its neighbors form a clique. Examples -------- This example checks whether node 0 is simplicial for two graphs: G, a single Chimera unit cell, which is bipartite, and K_5, the :math:`K_5` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> G = dnx.chimera_graph(1, 1, 4) >>> K_5 = nx.complete_graph(5) >>> dnx.is_simplicial(G, 0) False >>> dnx.is_simplicial(K_5, 0) True
[ "Determines", "whether", "a", "node", "n", "in", "G", "is", "simplicial", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L27-L58
train
205,048
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
is_almost_simplicial
def is_almost_simplicial(G, n): """Determines whether a node n in G is almost simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is almost simplicial. n : node A node in graph G. Returns ------- is_almost_simplicial : bool True if all but one of its neighbors induce a clique Examples -------- This example checks whether node 0 is simplicial or almost simplicial for a :math:`K_5` complete graph with one edge removed. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_5 = nx.complete_graph(5) >>> K_5.remove_edge(1,3) >>> dnx.is_simplicial(K_5, 0) False >>> dnx.is_almost_simplicial(K_5, 0) True """ for w in G[n]: if all(u in G[v] for u, v in itertools.combinations(G[n], 2) if u != w and v != w): return True return False
python
def is_almost_simplicial(G, n): """Determines whether a node n in G is almost simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is almost simplicial. n : node A node in graph G. Returns ------- is_almost_simplicial : bool True if all but one of its neighbors induce a clique Examples -------- This example checks whether node 0 is simplicial or almost simplicial for a :math:`K_5` complete graph with one edge removed. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_5 = nx.complete_graph(5) >>> K_5.remove_edge(1,3) >>> dnx.is_simplicial(K_5, 0) False >>> dnx.is_almost_simplicial(K_5, 0) True """ for w in G[n]: if all(u in G[v] for u, v in itertools.combinations(G[n], 2) if u != w and v != w): return True return False
[ "def", "is_almost_simplicial", "(", "G", ",", "n", ")", ":", "for", "w", "in", "G", "[", "n", "]", ":", "if", "all", "(", "u", "in", "G", "[", "v", "]", "for", "u", ",", "v", "in", "itertools", ".", "combinations", "(", "G", "[", "n", "]", ...
Determines whether a node n in G is almost simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is almost simplicial. n : node A node in graph G. Returns ------- is_almost_simplicial : bool True if all but one of its neighbors induce a clique Examples -------- This example checks whether node 0 is simplicial or almost simplicial for a :math:`K_5` complete graph with one edge removed. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_5 = nx.complete_graph(5) >>> K_5.remove_edge(1,3) >>> dnx.is_simplicial(K_5, 0) False >>> dnx.is_almost_simplicial(K_5, 0) True
[ "Determines", "whether", "a", "node", "n", "in", "G", "is", "almost", "simplicial", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L61-L94
train
205,049
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
minor_min_width
def minor_min_width(G): """Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- This example computes a lower bound for the treewidth of the :math:`K_7` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> dnx.minor_min_width(K_7) 6 References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} lb = 0 # lower bound on treewidth while len(adj) > 1: # get the node with the smallest degree v = min(adj, key=lambda v: len(adj[v])) # find the vertex u such that the degree of u is minimal in the neighborhood of v neighbors = adj[v] if not neighbors: # if v is a singleton, then we can just delete it del adj[v] continue def neighborhood_degree(u): Gu = adj[u] return sum(w in Gu for w in neighbors) u = min(neighbors, key=neighborhood_degree) # update the lower bound new_lb = len(adj[v]) if new_lb > lb: lb = new_lb # contract the edge between u, v adj[v] = adj[v].union(n for n in adj[u] if n != v) for n in adj[v]: adj[n].add(v) for n in adj[u]: adj[n].discard(u) del adj[u] return lb
python
def minor_min_width(G): """Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- This example computes a lower bound for the treewidth of the :math:`K_7` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> dnx.minor_min_width(K_7) 6 References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} lb = 0 # lower bound on treewidth while len(adj) > 1: # get the node with the smallest degree v = min(adj, key=lambda v: len(adj[v])) # find the vertex u such that the degree of u is minimal in the neighborhood of v neighbors = adj[v] if not neighbors: # if v is a singleton, then we can just delete it del adj[v] continue def neighborhood_degree(u): Gu = adj[u] return sum(w in Gu for w in neighbors) u = min(neighbors, key=neighborhood_degree) # update the lower bound new_lb = len(adj[v]) if new_lb > lb: lb = new_lb # contract the edge between u, v adj[v] = adj[v].union(n for n in adj[u] if n != v) for n in adj[v]: adj[n].add(v) for n in adj[u]: adj[n].discard(u) del adj[u] return lb
[ "def", "minor_min_width", "(", "G", ")", ":", "# we need only deal with the adjacency structure of G. We will also", "# be manipulating it directly so let's go ahead and make a new one", "adj", "=", "{", "v", ":", "set", "(", "G", "[", "v", "]", ")", "for", "v", "in", "...
Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- This example computes a lower bound for the treewidth of the :math:`K_7` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> dnx.minor_min_width(K_7) 6 References ---------- Based on the algorithm presented in [GD]_
[ "Computes", "a", "lower", "bound", "for", "the", "treewidth", "of", "graph", "G", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L97-L163
train
205,050
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
min_fill_heuristic
def min_fill_heuristic(G): """Computes an upper bound on the treewidth of graph G based on the min-fill heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> tw, order = dnx.min_fill_heuristic(K_4) References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} num_nodes = len(adj) # preallocate the return values order = [0] * num_nodes upper_bound = 0 for i in range(num_nodes): # get the node that adds the fewest number of edges when eliminated from the graph v = min(adj, key=lambda x: _min_fill_needed_edges(adj, x)) # if the number of neighbours of v is higher than upper_bound, update dv = len(adj[v]) if dv > upper_bound: upper_bound = dv # make v simplicial by making its neighborhood a clique then remove the # node _elim_adj(adj, v) order[i] = v return upper_bound, order
python
def min_fill_heuristic(G): """Computes an upper bound on the treewidth of graph G based on the min-fill heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> tw, order = dnx.min_fill_heuristic(K_4) References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} num_nodes = len(adj) # preallocate the return values order = [0] * num_nodes upper_bound = 0 for i in range(num_nodes): # get the node that adds the fewest number of edges when eliminated from the graph v = min(adj, key=lambda x: _min_fill_needed_edges(adj, x)) # if the number of neighbours of v is higher than upper_bound, update dv = len(adj[v]) if dv > upper_bound: upper_bound = dv # make v simplicial by making its neighborhood a clique then remove the # node _elim_adj(adj, v) order[i] = v return upper_bound, order
[ "def", "min_fill_heuristic", "(", "G", ")", ":", "# we need only deal with the adjacency structure of G. We will also", "# be manipulating it directly so let's go ahead and make a new one", "adj", "=", "{", "v", ":", "set", "(", "G", "[", "v", "]", ")", "for", "v", "in", ...
Computes an upper bound on the treewidth of graph G based on the min-fill heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> tw, order = dnx.min_fill_heuristic(K_4) References ---------- Based on the algorithm presented in [GD]_
[ "Computes", "an", "upper", "bound", "on", "the", "treewidth", "of", "graph", "G", "based", "on", "the", "min", "-", "fill", "heuristic", "for", "the", "elimination", "ordering", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L166-L222
train
205,051
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
min_width_heuristic
def min_width_heuristic(G): """Computes an upper bound on the treewidth of graph G based on the min-width heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> tw, order = dnx.min_width_heuristic(K_4) References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} num_nodes = len(adj) # preallocate the return values order = [0] * num_nodes upper_bound = 0 for i in range(num_nodes): # get the node with the smallest degree. We add random() which picks a value # in the range [0., 1.). This is ok because the lens are all integers. By # adding a small random value, we randomize which node is chosen without affecting # correctness. v = min(adj, key=lambda u: len(adj[u]) + random()) # if the number of neighbours of v is higher than upper_bound, update dv = len(adj[v]) if dv > upper_bound: upper_bound = dv # make v simplicial by making its neighborhood a clique then remove the # node _elim_adj(adj, v) order[i] = v return upper_bound, order
python
def min_width_heuristic(G): """Computes an upper bound on the treewidth of graph G based on the min-width heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> tw, order = dnx.min_width_heuristic(K_4) References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} num_nodes = len(adj) # preallocate the return values order = [0] * num_nodes upper_bound = 0 for i in range(num_nodes): # get the node with the smallest degree. We add random() which picks a value # in the range [0., 1.). This is ok because the lens are all integers. By # adding a small random value, we randomize which node is chosen without affecting # correctness. v = min(adj, key=lambda u: len(adj[u]) + random()) # if the number of neighbours of v is higher than upper_bound, update dv = len(adj[v]) if dv > upper_bound: upper_bound = dv # make v simplicial by making its neighborhood a clique then remove the # node _elim_adj(adj, v) order[i] = v return upper_bound, order
[ "def", "min_width_heuristic", "(", "G", ")", ":", "# we need only deal with the adjacency structure of G. We will also", "# be manipulating it directly so let's go ahead and make a new one", "adj", "=", "{", "v", ":", "set", "(", "G", "[", "v", "]", ")", "for", "v", "in",...
Computes an upper bound on the treewidth of graph G based on the min-width heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> tw, order = dnx.min_width_heuristic(K_4) References ---------- Based on the algorithm presented in [GD]_
[ "Computes", "an", "upper", "bound", "on", "the", "treewidth", "of", "graph", "G", "based", "on", "the", "min", "-", "width", "heuristic", "for", "the", "elimination", "ordering", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L238-L297
train
205,052
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
max_cardinality_heuristic
def max_cardinality_heuristic(G): """Computes an upper bound on the treewidth of graph G based on the max-cardinality heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. inplace : bool If True, G will be made an empty graph in the process of running the function, otherwise the function uses a copy of G. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> dnx.max_cardinality_heuristic(K_4) (3, [3, 1, 0, 2]) References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} num_nodes = len(adj) # preallocate the return values order = [0] * num_nodes upper_bound = 0 # we will need to track the nodes and how many labelled neighbors # each node has labelled_neighbors = {v: 0 for v in adj} # working backwards for i in range(num_nodes): # pick the node with the most labelled neighbors v = max(labelled_neighbors, key=lambda u: labelled_neighbors[u] + random()) del labelled_neighbors[v] # increment all of its neighbors for u in adj[v]: if u in labelled_neighbors: labelled_neighbors[u] += 1 order[-(i + 1)] = v for v in order: # if the number of neighbours of v is higher than upper_bound, update dv = len(adj[v]) if dv > upper_bound: upper_bound = dv # make v simplicial by making its neighborhood a clique then remove the node # add v to order _elim_adj(adj, v) return upper_bound, order
python
def max_cardinality_heuristic(G): """Computes an upper bound on the treewidth of graph G based on the max-cardinality heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. inplace : bool If True, G will be made an empty graph in the process of running the function, otherwise the function uses a copy of G. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> dnx.max_cardinality_heuristic(K_4) (3, [3, 1, 0, 2]) References ---------- Based on the algorithm presented in [GD]_ """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} num_nodes = len(adj) # preallocate the return values order = [0] * num_nodes upper_bound = 0 # we will need to track the nodes and how many labelled neighbors # each node has labelled_neighbors = {v: 0 for v in adj} # working backwards for i in range(num_nodes): # pick the node with the most labelled neighbors v = max(labelled_neighbors, key=lambda u: labelled_neighbors[u] + random()) del labelled_neighbors[v] # increment all of its neighbors for u in adj[v]: if u in labelled_neighbors: labelled_neighbors[u] += 1 order[-(i + 1)] = v for v in order: # if the number of neighbours of v is higher than upper_bound, update dv = len(adj[v]) if dv > upper_bound: upper_bound = dv # make v simplicial by making its neighborhood a clique then remove the node # add v to order _elim_adj(adj, v) return upper_bound, order
[ "def", "max_cardinality_heuristic", "(", "G", ")", ":", "# we need only deal with the adjacency structure of G. We will also", "# be manipulating it directly so let's go ahead and make a new one", "adj", "=", "{", "v", ":", "set", "(", "G", "[", "v", "]", ")", "for", "v", ...
Computes an upper bound on the treewidth of graph G based on the max-cardinality heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. inplace : bool If True, G will be made an empty graph in the process of running the function, otherwise the function uses a copy of G. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> dnx.max_cardinality_heuristic(K_4) (3, [3, 1, 0, 2]) References ---------- Based on the algorithm presented in [GD]_
[ "Computes", "an", "upper", "bound", "on", "the", "treewidth", "of", "graph", "G", "based", "on", "the", "max", "-", "cardinality", "heuristic", "for", "the", "elimination", "ordering", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L300-L375
train
205,053
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
_elim_adj
def _elim_adj(adj, n): """eliminates a variable, acting on the adj matrix of G, returning set of edges that were added. Parameters ---------- adj: dict A dict of the form {v: neighbors, ...} where v are vertices in a graph and neighbors is a set. Returns ---------- new_edges: set of edges that were added by eliminating v. """ neighbors = adj[n] new_edges = set() for u, v in itertools.combinations(neighbors, 2): if v not in adj[u]: adj[u].add(v) adj[v].add(u) new_edges.add((u, v)) new_edges.add((v, u)) for v in neighbors: adj[v].discard(n) del adj[n] return new_edges
python
def _elim_adj(adj, n): """eliminates a variable, acting on the adj matrix of G, returning set of edges that were added. Parameters ---------- adj: dict A dict of the form {v: neighbors, ...} where v are vertices in a graph and neighbors is a set. Returns ---------- new_edges: set of edges that were added by eliminating v. """ neighbors = adj[n] new_edges = set() for u, v in itertools.combinations(neighbors, 2): if v not in adj[u]: adj[u].add(v) adj[v].add(u) new_edges.add((u, v)) new_edges.add((v, u)) for v in neighbors: adj[v].discard(n) del adj[n] return new_edges
[ "def", "_elim_adj", "(", "adj", ",", "n", ")", ":", "neighbors", "=", "adj", "[", "n", "]", "new_edges", "=", "set", "(", ")", "for", "u", ",", "v", "in", "itertools", ".", "combinations", "(", "neighbors", ",", "2", ")", ":", "if", "v", "not", ...
eliminates a variable, acting on the adj matrix of G, returning set of edges that were added. Parameters ---------- adj: dict A dict of the form {v: neighbors, ...} where v are vertices in a graph and neighbors is a set. Returns ---------- new_edges: set of edges that were added by eliminating v.
[ "eliminates", "a", "variable", "acting", "on", "the", "adj", "matrix", "of", "G", "returning", "set", "of", "edges", "that", "were", "added", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L378-L404
train
205,054
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
elimination_order_width
def elimination_order_width(G, order): """Calculates the width of the tree decomposition induced by a variable elimination order. Parameters ---------- G : NetworkX graph The graph on which to compute the width of the tree decomposition. order : list The elimination order. Must be a list of all of the variables in G. Returns ------- treewidth : int The width of the tree decomposition induced by order. Examples -------- This example computes the width of the tree decomposition for the :math:`K_4` complete graph induced by an elimination order found through the min-width heuristic. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> dnx.min_width_heuristic(K_4) (3, [1, 2, 0, 3]) >>> dnx.elimination_order_width(K_4, [1, 2, 0, 3]) 3 """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} treewidth = 0 for v in order: # get the degree of the eliminated variable try: dv = len(adj[v]) except KeyError: raise ValueError('{} is in order but not in G'.format(v)) # the treewidth is the max of the current treewidth and the degree if dv > treewidth: treewidth = dv # eliminate v by making it simplicial (acts on adj in place) _elim_adj(adj, v) # if adj is not empty, then order did not include all of the nodes in G. if adj: raise ValueError('not all nodes in G were in order') return treewidth
python
def elimination_order_width(G, order): """Calculates the width of the tree decomposition induced by a variable elimination order. Parameters ---------- G : NetworkX graph The graph on which to compute the width of the tree decomposition. order : list The elimination order. Must be a list of all of the variables in G. Returns ------- treewidth : int The width of the tree decomposition induced by order. Examples -------- This example computes the width of the tree decomposition for the :math:`K_4` complete graph induced by an elimination order found through the min-width heuristic. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> dnx.min_width_heuristic(K_4) (3, [1, 2, 0, 3]) >>> dnx.elimination_order_width(K_4, [1, 2, 0, 3]) 3 """ # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} treewidth = 0 for v in order: # get the degree of the eliminated variable try: dv = len(adj[v]) except KeyError: raise ValueError('{} is in order but not in G'.format(v)) # the treewidth is the max of the current treewidth and the degree if dv > treewidth: treewidth = dv # eliminate v by making it simplicial (acts on adj in place) _elim_adj(adj, v) # if adj is not empty, then order did not include all of the nodes in G. if adj: raise ValueError('not all nodes in G were in order') return treewidth
[ "def", "elimination_order_width", "(", "G", ",", "order", ")", ":", "# we need only deal with the adjacency structure of G. We will also", "# be manipulating it directly so let's go ahead and make a new one", "adj", "=", "{", "v", ":", "set", "(", "G", "[", "v", "]", ")", ...
Calculates the width of the tree decomposition induced by a variable elimination order. Parameters ---------- G : NetworkX graph The graph on which to compute the width of the tree decomposition. order : list The elimination order. Must be a list of all of the variables in G. Returns ------- treewidth : int The width of the tree decomposition induced by order. Examples -------- This example computes the width of the tree decomposition for the :math:`K_4` complete graph induced by an elimination order found through the min-width heuristic. >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_4 = nx.complete_graph(4) >>> dnx.min_width_heuristic(K_4) (3, [1, 2, 0, 3]) >>> dnx.elimination_order_width(K_4, [1, 2, 0, 3]) 3
[ "Calculates", "the", "width", "of", "the", "tree", "decomposition", "induced", "by", "a", "variable", "elimination", "order", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L407-L466
train
205,055
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
treewidth_branch_and_bound
def treewidth_branch_and_bound(G, elimination_order=None, treewidth_upperbound=None): """Computes the treewidth of graph G and a corresponding perfect elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute the treewidth and perfect elimination ordering. elimination_order: list (optional, Default None) An elimination order used as an initial best-known order. If a good order is provided, it may speed up computation. If not provided, the initial order is generated using the min-fill heuristic. treewidth_upperbound : int (optional, Default None) An upper bound on the treewidth. Note that using this parameter can result in no returned order. Returns ------- treewidth : int The treewidth of graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes the treewidth for the :math:`K_7` complete graph using an optionally provided elimination order (a sequential ordering of the nodes, arbitrally chosen). >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> dnx.treewidth_branch_and_bound(K_7, [0, 1, 2, 3, 4, 5, 6]) (6, [0, 1, 2, 3, 4, 5, 6]) References ---------- .. [GD] Gogate & Dechter, "A Complete Anytime Algorithm for Treewidth", https://arxiv.org/abs/1207.4109 """ # empty graphs have treewidth 0 and the nodes can be eliminated in # any order if not any(G[v] for v in G): return 0, list(G) # variable names are chosen to match the paper # our order will be stored in vector x, named to be consistent with # the paper x = [] # the partial order f = minor_min_width(G) # our current lower bound guess, f(s) in the paper g = 0 # g(s) in the paper # we need the best current update we can find. ub, order = min_fill_heuristic(G) # if the user has provided an upperbound or an elimination order, check those against # our current best guess if elimination_order is not None: upperbound = elimination_order_width(G, elimination_order) if upperbound <= ub: ub, order = upperbound, elimination_order if treewidth_upperbound is not None and treewidth_upperbound < ub: # in this case the order might never be found ub, order = treewidth_upperbound, [] # best found encodes the ub and the order best_found = ub, order # if our upper bound is the same as f, then we are done! Otherwise begin the # algorithm assert f <= ub, "Logic error" if f < ub: # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} best_found = _branch_and_bound(adj, x, g, f, best_found) return best_found
python
def treewidth_branch_and_bound(G, elimination_order=None, treewidth_upperbound=None): """Computes the treewidth of graph G and a corresponding perfect elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute the treewidth and perfect elimination ordering. elimination_order: list (optional, Default None) An elimination order used as an initial best-known order. If a good order is provided, it may speed up computation. If not provided, the initial order is generated using the min-fill heuristic. treewidth_upperbound : int (optional, Default None) An upper bound on the treewidth. Note that using this parameter can result in no returned order. Returns ------- treewidth : int The treewidth of graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes the treewidth for the :math:`K_7` complete graph using an optionally provided elimination order (a sequential ordering of the nodes, arbitrally chosen). >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> dnx.treewidth_branch_and_bound(K_7, [0, 1, 2, 3, 4, 5, 6]) (6, [0, 1, 2, 3, 4, 5, 6]) References ---------- .. [GD] Gogate & Dechter, "A Complete Anytime Algorithm for Treewidth", https://arxiv.org/abs/1207.4109 """ # empty graphs have treewidth 0 and the nodes can be eliminated in # any order if not any(G[v] for v in G): return 0, list(G) # variable names are chosen to match the paper # our order will be stored in vector x, named to be consistent with # the paper x = [] # the partial order f = minor_min_width(G) # our current lower bound guess, f(s) in the paper g = 0 # g(s) in the paper # we need the best current update we can find. ub, order = min_fill_heuristic(G) # if the user has provided an upperbound or an elimination order, check those against # our current best guess if elimination_order is not None: upperbound = elimination_order_width(G, elimination_order) if upperbound <= ub: ub, order = upperbound, elimination_order if treewidth_upperbound is not None and treewidth_upperbound < ub: # in this case the order might never be found ub, order = treewidth_upperbound, [] # best found encodes the ub and the order best_found = ub, order # if our upper bound is the same as f, then we are done! Otherwise begin the # algorithm assert f <= ub, "Logic error" if f < ub: # we need only deal with the adjacency structure of G. We will also # be manipulating it directly so let's go ahead and make a new one adj = {v: set(G[v]) for v in G} best_found = _branch_and_bound(adj, x, g, f, best_found) return best_found
[ "def", "treewidth_branch_and_bound", "(", "G", ",", "elimination_order", "=", "None", ",", "treewidth_upperbound", "=", "None", ")", ":", "# empty graphs have treewidth 0 and the nodes can be eliminated in", "# any order", "if", "not", "any", "(", "G", "[", "v", "]", ...
Computes the treewidth of graph G and a corresponding perfect elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute the treewidth and perfect elimination ordering. elimination_order: list (optional, Default None) An elimination order used as an initial best-known order. If a good order is provided, it may speed up computation. If not provided, the initial order is generated using the min-fill heuristic. treewidth_upperbound : int (optional, Default None) An upper bound on the treewidth. Note that using this parameter can result in no returned order. Returns ------- treewidth : int The treewidth of graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes the treewidth for the :math:`K_7` complete graph using an optionally provided elimination order (a sequential ordering of the nodes, arbitrally chosen). >>> import dwave_networkx as dnx >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> dnx.treewidth_branch_and_bound(K_7, [0, 1, 2, 3, 4, 5, 6]) (6, [0, 1, 2, 3, 4, 5, 6]) References ---------- .. [GD] Gogate & Dechter, "A Complete Anytime Algorithm for Treewidth", https://arxiv.org/abs/1207.4109
[ "Computes", "the", "treewidth", "of", "graph", "G", "and", "a", "corresponding", "perfect", "elimination", "ordering", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L469-L551
train
205,056
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
_graph_reduction
def _graph_reduction(adj, x, g, f): """we can go ahead and remove any simplicial or almost-simplicial vertices from adj. """ as_list = set() as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)} while as_nodes: as_list.union(as_nodes) for n in as_nodes: # update g and f dv = len(adj[n]) if dv > g: g = dv if g > f: f = g # eliminate v x.append(n) _elim_adj(adj, n) # see if we have any more simplicial nodes as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)} return g, f, as_list
python
def _graph_reduction(adj, x, g, f): """we can go ahead and remove any simplicial or almost-simplicial vertices from adj. """ as_list = set() as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)} while as_nodes: as_list.union(as_nodes) for n in as_nodes: # update g and f dv = len(adj[n]) if dv > g: g = dv if g > f: f = g # eliminate v x.append(n) _elim_adj(adj, n) # see if we have any more simplicial nodes as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)} return g, f, as_list
[ "def", "_graph_reduction", "(", "adj", ",", "x", ",", "g", ",", "f", ")", ":", "as_list", "=", "set", "(", ")", "as_nodes", "=", "{", "v", "for", "v", "in", "adj", "if", "len", "(", "adj", "[", "v", "]", ")", "<=", "f", "and", "is_almost_simpli...
we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
[ "we", "can", "go", "ahead", "and", "remove", "any", "simplicial", "or", "almost", "-", "simplicial", "vertices", "from", "adj", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L677-L700
train
205,057
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
_theorem5p4
def _theorem5p4(adj, ub): """By Theorem 5.4, if any two vertices have ub + 1 common neighbors then we can add an edge between them. """ new_edges = set() for u, v in itertools.combinations(adj, 2): if u in adj[v]: # already an edge continue if len(adj[u].intersection(adj[v])) > ub: new_edges.add((u, v)) while new_edges: for u, v in new_edges: adj[u].add(v) adj[v].add(u) new_edges = set() for u, v in itertools.combinations(adj, 2): if u in adj[v]: continue if len(adj[u].intersection(adj[v])) > ub: new_edges.add((u, v))
python
def _theorem5p4(adj, ub): """By Theorem 5.4, if any two vertices have ub + 1 common neighbors then we can add an edge between them. """ new_edges = set() for u, v in itertools.combinations(adj, 2): if u in adj[v]: # already an edge continue if len(adj[u].intersection(adj[v])) > ub: new_edges.add((u, v)) while new_edges: for u, v in new_edges: adj[u].add(v) adj[v].add(u) new_edges = set() for u, v in itertools.combinations(adj, 2): if u in adj[v]: continue if len(adj[u].intersection(adj[v])) > ub: new_edges.add((u, v))
[ "def", "_theorem5p4", "(", "adj", ",", "ub", ")", ":", "new_edges", "=", "set", "(", ")", "for", "u", ",", "v", "in", "itertools", ".", "combinations", "(", "adj", ",", "2", ")", ":", "if", "u", "in", "adj", "[", "v", "]", ":", "# already an edge...
By Theorem 5.4, if any two vertices have ub + 1 common neighbors then we can add an edge between them.
[ "By", "Theorem", "5", ".", "4", "if", "any", "two", "vertices", "have", "ub", "+", "1", "common", "neighbors", "then", "we", "can", "add", "an", "edge", "between", "them", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L703-L727
train
205,058
dwavesystems/dwave_networkx
dwave_networkx/algorithms/elimination_ordering.py
_theorem6p1
def _theorem6p1(): """See Theorem 6.1 in paper.""" pruning_set = set() def _prune(x): if len(x) <= 2: return False # this is faster than tuple(x[-3:]) key = (tuple(x[:-2]), x[-2], x[-1]) return key in pruning_set def _explored(x): if len(x) >= 3: prunable = (tuple(x[:-2]), x[-1], x[-2]) pruning_set.add(prunable) return _prune, _explored
python
def _theorem6p1(): """See Theorem 6.1 in paper.""" pruning_set = set() def _prune(x): if len(x) <= 2: return False # this is faster than tuple(x[-3:]) key = (tuple(x[:-2]), x[-2], x[-1]) return key in pruning_set def _explored(x): if len(x) >= 3: prunable = (tuple(x[:-2]), x[-1], x[-2]) pruning_set.add(prunable) return _prune, _explored
[ "def", "_theorem6p1", "(", ")", ":", "pruning_set", "=", "set", "(", ")", "def", "_prune", "(", "x", ")", ":", "if", "len", "(", "x", ")", "<=", "2", ":", "return", "False", "# this is faster than tuple(x[-3:])", "key", "=", "(", "tuple", "(", "x", "...
See Theorem 6.1 in paper.
[ "See", "Theorem", "6", ".", "1", "in", "paper", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L730-L747
train
205,059
dwavesystems/dwave_networkx
dwave_networkx/drawing/qubit_layout.py
draw_qubit_graph
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={}, nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None, edge_vmin=None, edge_vmax=None, **kwargs): """Draws graph G according to layout. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph The graph to be drawn layout : dict A dict of coordinates associated with each node in G. Should be of the form {node: coordinate, ...}. Coordinates will be treated as vectors, and should all have the same length. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. """ if linear_biases or quadratic_biases: # if linear biases and/or quadratic biases are provided, then color accordingly. try: import matplotlib.pyplot as plt import matplotlib as mpl except ImportError: raise ImportError("Matplotlib and numpy required for draw_qubit_graph()") if nodelist is None: nodelist = G.nodes() if edgelist is None: edgelist = G.edges() if cmap is None: cmap = plt.get_cmap('coolwarm') if edge_cmap is None: edge_cmap = plt.get_cmap('coolwarm') # any edges or nodes with an unspecified bias default to 0 def edge_color(u, v): c = 0. if (u, v) in quadratic_biases: c += quadratic_biases[(u, v)] if (v, u) in quadratic_biases: c += quadratic_biases[(v, u)] return c def node_color(v): c = 0. if v in linear_biases: c += linear_biases[v] if (v, v) in quadratic_biases: c += quadratic_biases[(v, v)] return c node_color = [node_color(v) for v in nodelist] edge_color = [edge_color(u, v) for u, v in edgelist] kwargs['edge_color'] = edge_color kwargs['node_color'] = node_color # the range of the color map is shared for nodes/edges and is symmetric # around 0. vmag = max(max(abs(c) for c in node_color), max(abs(c) for c in edge_color)) if vmin is None: vmin = -1 * vmag if vmax is None: vmax = vmag if edge_vmin is None: edge_vmin = -1 * vmag if edge_vmax is None: edge_vmax = vmag draw(G, layout, nodelist=nodelist, edgelist=edgelist, cmap=cmap, edge_cmap=edge_cmap, vmin=vmin, vmax=vmax, edge_vmin=edge_vmin, edge_vmax=edge_vmax, **kwargs) # if the biases are provided, then add a legend explaining the color map if linear_biases or quadratic_biases: fig = plt.figure(1) # cax = fig.add_axes([]) cax = fig.add_axes([.9, 0.2, 0.04, 0.6]) # left, bottom, width, height mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=mpl.colors.Normalize(vmin=-1 * vmag, vmax=vmag, clip=False), orientation='vertical')
python
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={}, nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None, edge_vmin=None, edge_vmax=None, **kwargs): """Draws graph G according to layout. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph The graph to be drawn layout : dict A dict of coordinates associated with each node in G. Should be of the form {node: coordinate, ...}. Coordinates will be treated as vectors, and should all have the same length. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. """ if linear_biases or quadratic_biases: # if linear biases and/or quadratic biases are provided, then color accordingly. try: import matplotlib.pyplot as plt import matplotlib as mpl except ImportError: raise ImportError("Matplotlib and numpy required for draw_qubit_graph()") if nodelist is None: nodelist = G.nodes() if edgelist is None: edgelist = G.edges() if cmap is None: cmap = plt.get_cmap('coolwarm') if edge_cmap is None: edge_cmap = plt.get_cmap('coolwarm') # any edges or nodes with an unspecified bias default to 0 def edge_color(u, v): c = 0. if (u, v) in quadratic_biases: c += quadratic_biases[(u, v)] if (v, u) in quadratic_biases: c += quadratic_biases[(v, u)] return c def node_color(v): c = 0. if v in linear_biases: c += linear_biases[v] if (v, v) in quadratic_biases: c += quadratic_biases[(v, v)] return c node_color = [node_color(v) for v in nodelist] edge_color = [edge_color(u, v) for u, v in edgelist] kwargs['edge_color'] = edge_color kwargs['node_color'] = node_color # the range of the color map is shared for nodes/edges and is symmetric # around 0. vmag = max(max(abs(c) for c in node_color), max(abs(c) for c in edge_color)) if vmin is None: vmin = -1 * vmag if vmax is None: vmax = vmag if edge_vmin is None: edge_vmin = -1 * vmag if edge_vmax is None: edge_vmax = vmag draw(G, layout, nodelist=nodelist, edgelist=edgelist, cmap=cmap, edge_cmap=edge_cmap, vmin=vmin, vmax=vmax, edge_vmin=edge_vmin, edge_vmax=edge_vmax, **kwargs) # if the biases are provided, then add a legend explaining the color map if linear_biases or quadratic_biases: fig = plt.figure(1) # cax = fig.add_axes([]) cax = fig.add_axes([.9, 0.2, 0.04, 0.6]) # left, bottom, width, height mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=mpl.colors.Normalize(vmin=-1 * vmag, vmax=vmag, clip=False), orientation='vertical')
[ "def", "draw_qubit_graph", "(", "G", ",", "layout", ",", "linear_biases", "=", "{", "}", ",", "quadratic_biases", "=", "{", "}", ",", "nodelist", "=", "None", ",", "edgelist", "=", "None", ",", "cmap", "=", "None", ",", "edge_cmap", "=", "None", ",", ...
Draws graph G according to layout. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph The graph to be drawn layout : dict A dict of coordinates associated with each node in G. Should be of the form {node: coordinate, ...}. Coordinates will be treated as vectors, and should all have the same length. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
[ "Draws", "graph", "G", "according", "to", "layout", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/qubit_layout.py#L44-L148
train
205,060
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
min_vertex_coloring
def min_vertex_coloring(G, sampler=None, **sampler_args): """Returns an approximate minimum vertex coloring. Vertex coloring is the problem of assigning a color to the vertices of a graph in a way that no adjacent vertices have the same color. A minimum vertex coloring is the problem of solving the vertex coloring problem using the smallest number of colors. Since neighboring vertices must satisfy a constraint of having different colors, the problem can be posed as a binary constraint satisfaction problem. Defines a QUBO with ground states corresponding to minimum vertex colorings and uses the sampler to sample from it. Parameters ---------- G : NetworkX graph The graph on which to find a minimum vertex coloring. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- coloring : dict A coloring for each vertex in G such that no adjacent nodes share the same color. A dict of the form {node: color, ...} Example ------- This example colors a single Chimera unit cell. It colors the four horizontal qubits one color (0) and the four vertical qubits another (1). >>> # Set up a sampler; this example uses a sampler from dimod https://github.com/dwavesystems/dimod >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> # Create a graph and color it >>> G = dnx.chimera_graph(1, 1, 4) >>> colors = dnx.min_vertex_coloring(G, sampler=samplerSA) >>> colors {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} References ---------- .. [DWMP] Dahl, E., "Programming the D-Wave: Map Coloring Problem", https://www.dwavesys.com/sites/default/files/Map%20Coloring%20WP2.pdf Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # if the given graph is not connected, apply the function to each connected component # seperately. if not nx.is_connected(G): coloring = {} for subG in (G.subgraph(c).copy() for c in nx.connected_components(G)): sub_coloring = min_vertex_coloring(subG, sampler, **sampler_args) coloring.update(sub_coloring) return coloring n_nodes = len(G) # number of nodes n_edges = len(G.edges) # number of edges # ok, first up, we can eliminate a few graph types trivially # Graphs with no edges, have chromatic number 1 if not n_edges: return {node: 0 for node in G} # Complete graphs have chromatic number N if n_edges == n_nodes * (n_nodes - 1) // 2: return {node: color for color, node in enumerate(G)} # The number of variables in the QUBO is approximately the number of nodes in the graph # times the number of potential colors, so we want as tight an upper bound on the # chromatic number (chi) as possible chi_ub = _chromatic_number_upper_bound(G, n_nodes, n_edges) # now we can start coloring. Without loss of generality, we can determine some of # the node colors before trying to solve. partial_coloring, possible_colors, chi_lb = _partial_precolor(G, chi_ub) # ok, to get the rest of the coloring, we need to start building the QUBO. We do this # by assigning a variable x_v_c for each node v and color c. This variable will be 1 # when node v is colored c, and 0 otherwise. # let's assign an index to each of the variables counter = itertools.count() x_vars = {v: {c: next(counter) for c in possible_colors[v]} for v in possible_colors} # now we have three different constraints we wish to add. # the first constraint enforces the coloring rule, that for each pair of vertices # u, v that share an edge, they should be different colors Q_neighbor = _vertex_different_colors_qubo(G, x_vars) # the second constraint enforces that each vertex has a single color assigned Q_vertex = _vertex_one_color_qubo(x_vars) # the third constraint is that we want a minimum vertex coloring, so we want to # disincentivize the colors we might not need. Q_min_color = _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=.75) # combine all three constraints Q = Q_neighbor for (u, v), bias in iteritems(Q_vertex): if (u, v) in Q: Q[(u, v)] += bias elif (v, u) in Q: Q[(v, u)] += bias else: Q[(u, v)] = bias for (v, v), bias in iteritems(Q_min_color): if (v, v) in Q: Q[(v, v)] += bias else: Q[(v, v)] = bias # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # read off the coloring for v in x_vars: for c in x_vars[v]: if sample[x_vars[v][c]]: partial_coloring[v] = c return partial_coloring
python
def min_vertex_coloring(G, sampler=None, **sampler_args): """Returns an approximate minimum vertex coloring. Vertex coloring is the problem of assigning a color to the vertices of a graph in a way that no adjacent vertices have the same color. A minimum vertex coloring is the problem of solving the vertex coloring problem using the smallest number of colors. Since neighboring vertices must satisfy a constraint of having different colors, the problem can be posed as a binary constraint satisfaction problem. Defines a QUBO with ground states corresponding to minimum vertex colorings and uses the sampler to sample from it. Parameters ---------- G : NetworkX graph The graph on which to find a minimum vertex coloring. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- coloring : dict A coloring for each vertex in G such that no adjacent nodes share the same color. A dict of the form {node: color, ...} Example ------- This example colors a single Chimera unit cell. It colors the four horizontal qubits one color (0) and the four vertical qubits another (1). >>> # Set up a sampler; this example uses a sampler from dimod https://github.com/dwavesystems/dimod >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> # Create a graph and color it >>> G = dnx.chimera_graph(1, 1, 4) >>> colors = dnx.min_vertex_coloring(G, sampler=samplerSA) >>> colors {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} References ---------- .. [DWMP] Dahl, E., "Programming the D-Wave: Map Coloring Problem", https://www.dwavesys.com/sites/default/files/Map%20Coloring%20WP2.pdf Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ # if the given graph is not connected, apply the function to each connected component # seperately. if not nx.is_connected(G): coloring = {} for subG in (G.subgraph(c).copy() for c in nx.connected_components(G)): sub_coloring = min_vertex_coloring(subG, sampler, **sampler_args) coloring.update(sub_coloring) return coloring n_nodes = len(G) # number of nodes n_edges = len(G.edges) # number of edges # ok, first up, we can eliminate a few graph types trivially # Graphs with no edges, have chromatic number 1 if not n_edges: return {node: 0 for node in G} # Complete graphs have chromatic number N if n_edges == n_nodes * (n_nodes - 1) // 2: return {node: color for color, node in enumerate(G)} # The number of variables in the QUBO is approximately the number of nodes in the graph # times the number of potential colors, so we want as tight an upper bound on the # chromatic number (chi) as possible chi_ub = _chromatic_number_upper_bound(G, n_nodes, n_edges) # now we can start coloring. Without loss of generality, we can determine some of # the node colors before trying to solve. partial_coloring, possible_colors, chi_lb = _partial_precolor(G, chi_ub) # ok, to get the rest of the coloring, we need to start building the QUBO. We do this # by assigning a variable x_v_c for each node v and color c. This variable will be 1 # when node v is colored c, and 0 otherwise. # let's assign an index to each of the variables counter = itertools.count() x_vars = {v: {c: next(counter) for c in possible_colors[v]} for v in possible_colors} # now we have three different constraints we wish to add. # the first constraint enforces the coloring rule, that for each pair of vertices # u, v that share an edge, they should be different colors Q_neighbor = _vertex_different_colors_qubo(G, x_vars) # the second constraint enforces that each vertex has a single color assigned Q_vertex = _vertex_one_color_qubo(x_vars) # the third constraint is that we want a minimum vertex coloring, so we want to # disincentivize the colors we might not need. Q_min_color = _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=.75) # combine all three constraints Q = Q_neighbor for (u, v), bias in iteritems(Q_vertex): if (u, v) in Q: Q[(u, v)] += bias elif (v, u) in Q: Q[(v, u)] += bias else: Q[(u, v)] = bias for (v, v), bias in iteritems(Q_min_color): if (v, v) in Q: Q[(v, v)] += bias else: Q[(v, v)] = bias # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # read off the coloring for v in x_vars: for c in x_vars[v]: if sample[x_vars[v][c]]: partial_coloring[v] = c return partial_coloring
[ "def", "min_vertex_coloring", "(", "G", ",", "sampler", "=", "None", ",", "*", "*", "sampler_args", ")", ":", "# if the given graph is not connected, apply the function to each connected component", "# seperately.", "if", "not", "nx", ".", "is_connected", "(", "G", ")",...
Returns an approximate minimum vertex coloring. Vertex coloring is the problem of assigning a color to the vertices of a graph in a way that no adjacent vertices have the same color. A minimum vertex coloring is the problem of solving the vertex coloring problem using the smallest number of colors. Since neighboring vertices must satisfy a constraint of having different colors, the problem can be posed as a binary constraint satisfaction problem. Defines a QUBO with ground states corresponding to minimum vertex colorings and uses the sampler to sample from it. Parameters ---------- G : NetworkX graph The graph on which to find a minimum vertex coloring. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- coloring : dict A coloring for each vertex in G such that no adjacent nodes share the same color. A dict of the form {node: color, ...} Example ------- This example colors a single Chimera unit cell. It colors the four horizontal qubits one color (0) and the four vertical qubits another (1). >>> # Set up a sampler; this example uses a sampler from dimod https://github.com/dwavesystems/dimod >>> import dimod >>> import dwave_networkx as dnx >>> samplerSA = dimod.SimulatedAnnealingSampler() >>> # Create a graph and color it >>> G = dnx.chimera_graph(1, 1, 4) >>> colors = dnx.min_vertex_coloring(G, sampler=samplerSA) >>> colors {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} References ---------- .. [DWMP] Dahl, E., "Programming the D-Wave: Map Coloring Problem", https://www.dwavesys.com/sites/default/files/Map%20Coloring%20WP2.pdf Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample.
[ "Returns", "an", "approximate", "minimum", "vertex", "coloring", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L46-L192
train
205,061
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
_minimum_coloring_qubo
def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=1.): """We want to disincentivize unneeded colors. Generates the QUBO that does that. """ # if we already know the chromatic number, then we don't need to # disincentivize any colors. if chi_lb == chi_ub: return {} # we might need to use some of the colors, so we want to disincentivize # them in increasing amounts, linearly. scaling = magnitude / (chi_ub - chi_lb) # build the QUBO Q = {} for v in x_vars: for f, color in enumerate(range(chi_lb, chi_ub)): idx = x_vars[v][color] Q[(idx, idx)] = (f + 1) * scaling return Q
python
def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=1.): """We want to disincentivize unneeded colors. Generates the QUBO that does that. """ # if we already know the chromatic number, then we don't need to # disincentivize any colors. if chi_lb == chi_ub: return {} # we might need to use some of the colors, so we want to disincentivize # them in increasing amounts, linearly. scaling = magnitude / (chi_ub - chi_lb) # build the QUBO Q = {} for v in x_vars: for f, color in enumerate(range(chi_lb, chi_ub)): idx = x_vars[v][color] Q[(idx, idx)] = (f + 1) * scaling return Q
[ "def", "_minimum_coloring_qubo", "(", "x_vars", ",", "chi_lb", ",", "chi_ub", ",", "magnitude", "=", "1.", ")", ":", "# if we already know the chromatic number, then we don't need to", "# disincentivize any colors.", "if", "chi_lb", "==", "chi_ub", ":", "return", "{", "...
We want to disincentivize unneeded colors. Generates the QUBO that does that.
[ "We", "want", "to", "disincentivize", "unneeded", "colors", ".", "Generates", "the", "QUBO", "that", "does", "that", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L220-L240
train
205,062
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
_vertex_different_colors_qubo
def _vertex_different_colors_qubo(G, x_vars): """For each vertex, it should not have the same color as any of its neighbors. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce each node having a single color. Ground energy is 0, infeasible gap is 1. """ Q = {} for u, v in G.edges: if u not in x_vars or v not in x_vars: continue for color in x_vars[u]: if color in x_vars[v]: Q[(x_vars[u][color], x_vars[v][color])] = 1. return Q
python
def _vertex_different_colors_qubo(G, x_vars): """For each vertex, it should not have the same color as any of its neighbors. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce each node having a single color. Ground energy is 0, infeasible gap is 1. """ Q = {} for u, v in G.edges: if u not in x_vars or v not in x_vars: continue for color in x_vars[u]: if color in x_vars[v]: Q[(x_vars[u][color], x_vars[v][color])] = 1. return Q
[ "def", "_vertex_different_colors_qubo", "(", "G", ",", "x_vars", ")", ":", "Q", "=", "{", "}", "for", "u", ",", "v", "in", "G", ".", "edges", ":", "if", "u", "not", "in", "x_vars", "or", "v", "not", "in", "x_vars", ":", "continue", "for", "color", ...
For each vertex, it should not have the same color as any of its neighbors. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce each node having a single color. Ground energy is 0, infeasible gap is 1.
[ "For", "each", "vertex", "it", "should", "not", "have", "the", "same", "color", "as", "any", "of", "its", "neighbors", ".", "Generates", "the", "QUBO", "to", "enforce", "this", "constraint", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L243-L260
train
205,063
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
_vertex_one_color_qubo
def _vertex_one_color_qubo(x_vars): """For each vertex, it should have exactly one color. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce neighboring vertices having different colors. Ground energy is -1 * |G|, infeasible gap is 1. """ Q = {} for v in x_vars: for color in x_vars[v]: idx = x_vars[v][color] Q[(idx, idx)] = -1 for color0, color1 in itertools.combinations(x_vars[v], 2): idx0 = x_vars[v][color0] idx1 = x_vars[v][color1] Q[(idx0, idx1)] = 2 return Q
python
def _vertex_one_color_qubo(x_vars): """For each vertex, it should have exactly one color. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce neighboring vertices having different colors. Ground energy is -1 * |G|, infeasible gap is 1. """ Q = {} for v in x_vars: for color in x_vars[v]: idx = x_vars[v][color] Q[(idx, idx)] = -1 for color0, color1 in itertools.combinations(x_vars[v], 2): idx0 = x_vars[v][color0] idx1 = x_vars[v][color1] Q[(idx0, idx1)] = 2 return Q
[ "def", "_vertex_one_color_qubo", "(", "x_vars", ")", ":", "Q", "=", "{", "}", "for", "v", "in", "x_vars", ":", "for", "color", "in", "x_vars", "[", "v", "]", ":", "idx", "=", "x_vars", "[", "v", "]", "[", "color", "]", "Q", "[", "(", "idx", ","...
For each vertex, it should have exactly one color. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce neighboring vertices having different colors. Ground energy is -1 * |G|, infeasible gap is 1.
[ "For", "each", "vertex", "it", "should", "have", "exactly", "one", "color", ".", "Generates", "the", "QUBO", "to", "enforce", "this", "constraint", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L263-L285
train
205,064
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
_partial_precolor
def _partial_precolor(G, chi_ub): """In order to reduce the number of variables in the QUBO, we want to color as many nodes as possible without affecting the min vertex coloring. Without loss of generality, we can choose a single maximal clique and color each node in it uniquely. Returns ------- partial_coloring : dict A dict describing a partial coloring of the nodes of G. Of the form {node: color, ...}. possible_colors : dict A dict giving the possible colors for each node in G not already colored. Of the form {node: set([color, ...]), ...}. chi_lb : int A lower bound on the chromatic number chi. Notes ----- partial_coloring.keys() and possible_colors.keys() should be disjoint. """ # find a random maximal clique and give each node in it a unique color v = next(iter(G)) clique = [v] for u in G[v]: if all(w in G[u] for w in clique): clique.append(u) partial_coloring = {v: c for c, v in enumerate(clique)} chi_lb = len(partial_coloring) # lower bound for the chromatic number # now for each uncolored node determine the possible colors possible_colors = {v: set(range(chi_ub)) for v in G if v not in partial_coloring} for v, color in iteritems(partial_coloring): for u in G[v]: if u in possible_colors: possible_colors[u].discard(color) # TODO: there is more here that can be done. For instance some nodes now # might only have one possible color. Or there might only be one node # remaining to color return partial_coloring, possible_colors, chi_lb
python
def _partial_precolor(G, chi_ub): """In order to reduce the number of variables in the QUBO, we want to color as many nodes as possible without affecting the min vertex coloring. Without loss of generality, we can choose a single maximal clique and color each node in it uniquely. Returns ------- partial_coloring : dict A dict describing a partial coloring of the nodes of G. Of the form {node: color, ...}. possible_colors : dict A dict giving the possible colors for each node in G not already colored. Of the form {node: set([color, ...]), ...}. chi_lb : int A lower bound on the chromatic number chi. Notes ----- partial_coloring.keys() and possible_colors.keys() should be disjoint. """ # find a random maximal clique and give each node in it a unique color v = next(iter(G)) clique = [v] for u in G[v]: if all(w in G[u] for w in clique): clique.append(u) partial_coloring = {v: c for c, v in enumerate(clique)} chi_lb = len(partial_coloring) # lower bound for the chromatic number # now for each uncolored node determine the possible colors possible_colors = {v: set(range(chi_ub)) for v in G if v not in partial_coloring} for v, color in iteritems(partial_coloring): for u in G[v]: if u in possible_colors: possible_colors[u].discard(color) # TODO: there is more here that can be done. For instance some nodes now # might only have one possible color. Or there might only be one node # remaining to color return partial_coloring, possible_colors, chi_lb
[ "def", "_partial_precolor", "(", "G", ",", "chi_ub", ")", ":", "# find a random maximal clique and give each node in it a unique color", "v", "=", "next", "(", "iter", "(", "G", ")", ")", "clique", "=", "[", "v", "]", "for", "u", "in", "G", "[", "v", "]", ...
In order to reduce the number of variables in the QUBO, we want to color as many nodes as possible without affecting the min vertex coloring. Without loss of generality, we can choose a single maximal clique and color each node in it uniquely. Returns ------- partial_coloring : dict A dict describing a partial coloring of the nodes of G. Of the form {node: color, ...}. possible_colors : dict A dict giving the possible colors for each node in G not already colored. Of the form {node: set([color, ...]), ...}. chi_lb : int A lower bound on the chromatic number chi. Notes ----- partial_coloring.keys() and possible_colors.keys() should be disjoint.
[ "In", "order", "to", "reduce", "the", "number", "of", "variables", "in", "the", "QUBO", "we", "want", "to", "color", "as", "many", "nodes", "as", "possible", "without", "affecting", "the", "min", "vertex", "coloring", ".", "Without", "loss", "of", "general...
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L288-L336
train
205,065
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
is_cycle
def is_cycle(G): """Determines whether the given graph is a cycle or circle graph. A cycle graph or circular graph is a graph that consists of a single cycle. https://en.wikipedia.org/wiki/Cycle_graph Parameters ---------- G : NetworkX graph Returns ------- is_cycle : bool True if the graph consists of a single cycle. """ trailing, leading = next(iter(G.edges)) start_node = trailing # travel around the graph, checking that each node has degree exactly two # also track how many nodes were visited n_visited = 1 while leading != start_node: neighbors = G[leading] if len(neighbors) != 2: return False node1, node2 = neighbors if node1 == trailing: trailing, leading = leading, node2 else: trailing, leading = leading, node1 n_visited += 1 # if we haven't visited all of the nodes, then it is not a connected cycle return n_visited == len(G)
python
def is_cycle(G): """Determines whether the given graph is a cycle or circle graph. A cycle graph or circular graph is a graph that consists of a single cycle. https://en.wikipedia.org/wiki/Cycle_graph Parameters ---------- G : NetworkX graph Returns ------- is_cycle : bool True if the graph consists of a single cycle. """ trailing, leading = next(iter(G.edges)) start_node = trailing # travel around the graph, checking that each node has degree exactly two # also track how many nodes were visited n_visited = 1 while leading != start_node: neighbors = G[leading] if len(neighbors) != 2: return False node1, node2 = neighbors if node1 == trailing: trailing, leading = leading, node2 else: trailing, leading = leading, node1 n_visited += 1 # if we haven't visited all of the nodes, then it is not a connected cycle return n_visited == len(G)
[ "def", "is_cycle", "(", "G", ")", ":", "trailing", ",", "leading", "=", "next", "(", "iter", "(", "G", ".", "edges", ")", ")", "start_node", "=", "trailing", "# travel around the graph, checking that each node has degree exactly two", "# also track how many nodes were v...
Determines whether the given graph is a cycle or circle graph. A cycle graph or circular graph is a graph that consists of a single cycle. https://en.wikipedia.org/wiki/Cycle_graph Parameters ---------- G : NetworkX graph Returns ------- is_cycle : bool True if the graph consists of a single cycle.
[ "Determines", "whether", "the", "given", "graph", "is", "a", "cycle", "or", "circle", "graph", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L339-L378
train
205,066
dwavesystems/dwave_networkx
dwave_networkx/algorithms/coloring.py
is_vertex_coloring
def is_vertex_coloring(G, coloring): """Determines whether the given coloring is a vertex coloring of graph G. Parameters ---------- G : NetworkX graph The graph on which the vertex coloring is applied. coloring : dict A coloring of the nodes of G. Should be a dict of the form {node: color, ...}. Returns ------- is_vertex_coloring : bool True if the given coloring defines a vertex coloring; that is, no two adjacent vertices share a color. Example ------- This example colors checks two colorings for a graph, G, of a single Chimera unit cell. The first uses one color (0) for the four horizontal qubits and another (1) for the four vertical qubits, in which case there are no adjacencies; the second coloring swaps the color of one node. >>> G = dnx.chimera_graph(1,1,4) >>> colors = {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} >>> dnx.is_vertex_coloring(G, colors) True >>> colors[4]=0 >>> dnx.is_vertex_coloring(G, colors) False """ return all(coloring[u] != coloring[v] for u, v in G.edges)
python
def is_vertex_coloring(G, coloring): """Determines whether the given coloring is a vertex coloring of graph G. Parameters ---------- G : NetworkX graph The graph on which the vertex coloring is applied. coloring : dict A coloring of the nodes of G. Should be a dict of the form {node: color, ...}. Returns ------- is_vertex_coloring : bool True if the given coloring defines a vertex coloring; that is, no two adjacent vertices share a color. Example ------- This example colors checks two colorings for a graph, G, of a single Chimera unit cell. The first uses one color (0) for the four horizontal qubits and another (1) for the four vertical qubits, in which case there are no adjacencies; the second coloring swaps the color of one node. >>> G = dnx.chimera_graph(1,1,4) >>> colors = {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} >>> dnx.is_vertex_coloring(G, colors) True >>> colors[4]=0 >>> dnx.is_vertex_coloring(G, colors) False """ return all(coloring[u] != coloring[v] for u, v in G.edges)
[ "def", "is_vertex_coloring", "(", "G", ",", "coloring", ")", ":", "return", "all", "(", "coloring", "[", "u", "]", "!=", "coloring", "[", "v", "]", "for", "u", ",", "v", "in", "G", ".", "edges", ")" ]
Determines whether the given coloring is a vertex coloring of graph G. Parameters ---------- G : NetworkX graph The graph on which the vertex coloring is applied. coloring : dict A coloring of the nodes of G. Should be a dict of the form {node: color, ...}. Returns ------- is_vertex_coloring : bool True if the given coloring defines a vertex coloring; that is, no two adjacent vertices share a color. Example ------- This example colors checks two colorings for a graph, G, of a single Chimera unit cell. The first uses one color (0) for the four horizontal qubits and another (1) for the four vertical qubits, in which case there are no adjacencies; the second coloring swaps the color of one node. >>> G = dnx.chimera_graph(1,1,4) >>> colors = {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} >>> dnx.is_vertex_coloring(G, colors) True >>> colors[4]=0 >>> dnx.is_vertex_coloring(G, colors) False
[ "Determines", "whether", "the", "given", "coloring", "is", "a", "vertex", "coloring", "of", "graph", "G", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/coloring.py#L381-L415
train
205,067
dwavesystems/dwave_networkx
dwave_networkx/algorithms/matching.py
maximal_matching
def maximal_matching(G, sampler=None, **sampler_args): """Finds an approximate maximal matching. Defines a QUBO with ground states corresponding to a maximal matching and uses the sampler to sample from it. A matching is a subset of edges in which no node occurs more than once. A maximal matching is one in which no edges from G can be added without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to find a maximal matching. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- matching : set A maximal matching of the graph. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Matching on Wikipedia <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ Based on the formulation presented in [AL]_ """ # the maximum degree delta = max(G.degree(node) for node in G) # use the maximum degree to determine the infeasible gaps A = 1. if delta == 2: B = .75 else: B = .75 * A / (delta - 2.) # we want A > (delta - 2) * B # each edge in G gets a variable, so let's create those edge_mapping = _edge_mapping(G) # build the QUBO Q = _maximal_matching_qubo(G, edge_mapping, magnitude=B) Qm = _matching_qubo(G, edge_mapping, magnitude=A) for edge, bias in Qm.items(): if edge not in Q: Q[edge] = bias else: Q[edge] += bias # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # the matching are the edges that are 1 in the sample return set(edge for edge in G.edges if sample[edge_mapping[edge]] > 0)
python
def maximal_matching(G, sampler=None, **sampler_args): """Finds an approximate maximal matching. Defines a QUBO with ground states corresponding to a maximal matching and uses the sampler to sample from it. A matching is a subset of edges in which no node occurs more than once. A maximal matching is one in which no edges from G can be added without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to find a maximal matching. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- matching : set A maximal matching of the graph. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Matching on Wikipedia <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ Based on the formulation presented in [AL]_ """ # the maximum degree delta = max(G.degree(node) for node in G) # use the maximum degree to determine the infeasible gaps A = 1. if delta == 2: B = .75 else: B = .75 * A / (delta - 2.) # we want A > (delta - 2) * B # each edge in G gets a variable, so let's create those edge_mapping = _edge_mapping(G) # build the QUBO Q = _maximal_matching_qubo(G, edge_mapping, magnitude=B) Qm = _matching_qubo(G, edge_mapping, magnitude=A) for edge, bias in Qm.items(): if edge not in Q: Q[edge] = bias else: Q[edge] += bias # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # the matching are the edges that are 1 in the sample return set(edge for edge in G.edges if sample[edge_mapping[edge]] > 0)
[ "def", "maximal_matching", "(", "G", ",", "sampler", "=", "None", ",", "*", "*", "sampler_args", ")", ":", "# the maximum degree", "delta", "=", "max", "(", "G", ".", "degree", "(", "node", ")", "for", "node", "in", "G", ")", "# use the maximum degree to d...
Finds an approximate maximal matching. Defines a QUBO with ground states corresponding to a maximal matching and uses the sampler to sample from it. A matching is a subset of edges in which no node occurs more than once. A maximal matching is one in which no edges from G can be added without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to find a maximal matching. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- matching : set A maximal matching of the graph. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Matching on Wikipedia <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ Based on the formulation presented in [AL]_
[ "Finds", "an", "approximate", "maximal", "matching", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/matching.py#L37-L116
train
205,068
dwavesystems/dwave_networkx
dwave_networkx/algorithms/matching.py
is_maximal_matching
def is_maximal_matching(G, matching): """Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to check the maximal matching. edges : iterable A iterable of edges. Returns ------- is_matching : bool True if the given edges are a maximal matching. Example ------- This example checks two sets of edges, both derived from a single Chimera unit cell, for a matching. The first set (a matching) is a subset of the second, which was found using the `min_maximal_matching()` function. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> dnx.is_matching({(0, 4), (2, 7)}) True >>> dnx.is_maximal_matching(G,{(0, 4), (2, 7)}) False >>> dnx.is_maximal_matching(G,{(0, 4), (1, 5), (2, 7), (3, 6)}) True """ touched_nodes = set().union(*matching) # first check if a matching if len(touched_nodes) != len(matching) * 2: return False # now for each edge, check that at least one of its variables is # already in the matching for (u, v) in G.edges: if u not in touched_nodes and v not in touched_nodes: return False return True
python
def is_maximal_matching(G, matching): """Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to check the maximal matching. edges : iterable A iterable of edges. Returns ------- is_matching : bool True if the given edges are a maximal matching. Example ------- This example checks two sets of edges, both derived from a single Chimera unit cell, for a matching. The first set (a matching) is a subset of the second, which was found using the `min_maximal_matching()` function. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> dnx.is_matching({(0, 4), (2, 7)}) True >>> dnx.is_maximal_matching(G,{(0, 4), (2, 7)}) False >>> dnx.is_maximal_matching(G,{(0, 4), (1, 5), (2, 7), (3, 6)}) True """ touched_nodes = set().union(*matching) # first check if a matching if len(touched_nodes) != len(matching) * 2: return False # now for each edge, check that at least one of its variables is # already in the matching for (u, v) in G.edges: if u not in touched_nodes and v not in touched_nodes: return False return True
[ "def", "is_maximal_matching", "(", "G", ",", "matching", ")", ":", "touched_nodes", "=", "set", "(", ")", ".", "union", "(", "*", "matching", ")", "# first check if a matching", "if", "len", "(", "touched_nodes", ")", "!=", "len", "(", "matching", ")", "*"...
Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to check the maximal matching. edges : iterable A iterable of edges. Returns ------- is_matching : bool True if the given edges are a maximal matching. Example ------- This example checks two sets of edges, both derived from a single Chimera unit cell, for a matching. The first set (a matching) is a subset of the second, which was found using the `min_maximal_matching()` function. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> dnx.is_matching({(0, 4), (2, 7)}) True >>> dnx.is_maximal_matching(G,{(0, 4), (2, 7)}) False >>> dnx.is_maximal_matching(G,{(0, 4), (1, 5), (2, 7), (3, 6)}) True
[ "Determines", "whether", "the", "given", "set", "of", "edges", "is", "a", "maximal", "matching", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/matching.py#L259-L309
train
205,069
dwavesystems/dwave_networkx
dwave_networkx/algorithms/matching.py
_maximal_matching_qubo
def _maximal_matching_qubo(G, edge_mapping, magnitude=1.): """Generates a QUBO that when combined with one as generated by _matching_qubo, induces a maximal matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = -1 * magnitude * |edges| infeasible_gap >= magnitude """ Q = {} # for each node n in G, define a variable y_n to be 1 when n has a colored edge # and 0 otherwise. # for each edge (u, v) in the graph we want to enforce y_u OR y_v. This is because # if both y_u == 0 and y_v == 0, then we could add (u, v) to the matching. for (u, v) in G.edges: # 1 - y_v - y_u + y_v*y_u # for each edge connected to u for edge in G.edges(u): x = edge_mapping[edge] if (x, x) not in Q: Q[(x, x)] = -1 * magnitude else: Q[(x, x)] -= magnitude # for each edge connected to v for edge in G.edges(v): x = edge_mapping[edge] if (x, x) not in Q: Q[(x, x)] = -1 * magnitude else: Q[(x, x)] -= magnitude for e0 in G.edges(v): x0 = edge_mapping[e0] for e1 in G.edges(u): x1 = edge_mapping[e1] if x0 < x1: if (x0, x1) not in Q: Q[(x0, x1)] = magnitude else: Q[(x0, x1)] += magnitude else: if (x1, x0) not in Q: Q[(x1, x0)] = magnitude else: Q[(x1, x0)] += magnitude return Q
python
def _maximal_matching_qubo(G, edge_mapping, magnitude=1.): """Generates a QUBO that when combined with one as generated by _matching_qubo, induces a maximal matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = -1 * magnitude * |edges| infeasible_gap >= magnitude """ Q = {} # for each node n in G, define a variable y_n to be 1 when n has a colored edge # and 0 otherwise. # for each edge (u, v) in the graph we want to enforce y_u OR y_v. This is because # if both y_u == 0 and y_v == 0, then we could add (u, v) to the matching. for (u, v) in G.edges: # 1 - y_v - y_u + y_v*y_u # for each edge connected to u for edge in G.edges(u): x = edge_mapping[edge] if (x, x) not in Q: Q[(x, x)] = -1 * magnitude else: Q[(x, x)] -= magnitude # for each edge connected to v for edge in G.edges(v): x = edge_mapping[edge] if (x, x) not in Q: Q[(x, x)] = -1 * magnitude else: Q[(x, x)] -= magnitude for e0 in G.edges(v): x0 = edge_mapping[e0] for e1 in G.edges(u): x1 = edge_mapping[e1] if x0 < x1: if (x0, x1) not in Q: Q[(x0, x1)] = magnitude else: Q[(x0, x1)] += magnitude else: if (x1, x0) not in Q: Q[(x1, x0)] = magnitude else: Q[(x1, x0)] += magnitude return Q
[ "def", "_maximal_matching_qubo", "(", "G", ",", "edge_mapping", ",", "magnitude", "=", "1.", ")", ":", "Q", "=", "{", "}", "# for each node n in G, define a variable y_n to be 1 when n has a colored edge", "# and 0 otherwise.", "# for each edge (u, v) in the graph we want to enfo...
Generates a QUBO that when combined with one as generated by _matching_qubo, induces a maximal matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = -1 * magnitude * |edges| infeasible_gap >= magnitude
[ "Generates", "a", "QUBO", "that", "when", "combined", "with", "one", "as", "generated", "by", "_matching_qubo", "induces", "a", "maximal", "matching", "on", "the", "given", "graph", "G", ".", "The", "variables", "in", "the", "QUBO", "are", "the", "edges", ...
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/matching.py#L321-L370
train
205,070
dwavesystems/dwave_networkx
dwave_networkx/algorithms/matching.py
_matching_qubo
def _matching_qubo(G, edge_mapping, magnitude=1.): """Generates a QUBO that induces a matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = 0 infeasible_gap = magnitude """ Q = {} # We wish to enforce the behavior that no node has two colored edges for node in G: # for each pair of edges that contain node for edge0, edge1 in itertools.combinations(G.edges(node), 2): v0 = edge_mapping[edge0] v1 = edge_mapping[edge1] # penalize both being True Q[(v0, v1)] = magnitude return Q
python
def _matching_qubo(G, edge_mapping, magnitude=1.): """Generates a QUBO that induces a matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = 0 infeasible_gap = magnitude """ Q = {} # We wish to enforce the behavior that no node has two colored edges for node in G: # for each pair of edges that contain node for edge0, edge1 in itertools.combinations(G.edges(node), 2): v0 = edge_mapping[edge0] v1 = edge_mapping[edge1] # penalize both being True Q[(v0, v1)] = magnitude return Q
[ "def", "_matching_qubo", "(", "G", ",", "edge_mapping", ",", "magnitude", "=", "1.", ")", ":", "Q", "=", "{", "}", "# We wish to enforce the behavior that no node has two colored edges", "for", "node", "in", "G", ":", "# for each pair of edges that contain node", "for",...
Generates a QUBO that induces a matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = 0 infeasible_gap = magnitude
[ "Generates", "a", "QUBO", "that", "induces", "a", "matching", "on", "the", "given", "graph", "G", ".", "The", "variables", "in", "the", "QUBO", "are", "the", "edges", "as", "given", "my", "edge_mapping", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/matching.py#L373-L394
train
205,071
dwavesystems/dwave_networkx
dwave_networkx/algorithms/canonicalization.py
canonical_chimera_labeling
def canonical_chimera_labeling(G, t=None): """Returns a mapping from the labels of G to chimera-indexed labeling. Parameters ---------- G : NetworkX graph A Chimera-structured graph. t : int (optional, default 4) Size of the shore within each Chimera tile. Returns ------- chimera_indices: dict A mapping from the current labels to a 4-tuple of Chimera indices. """ adj = G.adj if t is None: if hasattr(G, 'edges'): num_edges = len(G.edges) else: num_edges = len(G.quadratic) t = _chimera_shore_size(adj, num_edges) chimera_indices = {} row = col = 0 root = min(adj, key=lambda v: len(adj[v])) horiz, verti = rooted_tile(adj, root, t) while len(chimera_indices) < len(adj): new_indices = {} if row == 0: # if we're in the 0th row, we can assign the horizontal randomly for si, v in enumerate(horiz): new_indices[v] = (row, col, 0, si) else: # we need to match the row above for v in horiz: north = [u for u in adj[v] if u in chimera_indices] assert len(north) == 1 i, j, u, si = chimera_indices[north[0]] assert i == row - 1 and j == col and u == 0 new_indices[v] = (row, col, 0, si) if col == 0: # if we're in the 0th col, we can assign the vertical randomly for si, v in enumerate(verti): new_indices[v] = (row, col, 1, si) else: # we need to match the column to the east for v in verti: east = [u for u in adj[v] if u in chimera_indices] assert len(east) == 1 i, j, u, si = chimera_indices[east[0]] assert i == row and j == col - 1 and u == 1 new_indices[v] = (row, col, 1, si) chimera_indices.update(new_indices) # get the next root root_neighbours = [v for v in adj[root] if v not in chimera_indices] if len(root_neighbours) == 1: # we can increment the row root = root_neighbours[0] horiz, verti = rooted_tile(adj, root, t) row += 1 else: # need to go back to row 0, and increment the column assert not root_neighbours # should be empty # we want (0, col, 1, 0), we could cache this, but for now let's just go look for it # the slow way vert_root = [v for v in chimera_indices if chimera_indices[v] == (0, col, 1, 0)][0] vert_root_neighbours = [v for v in adj[vert_root] if v not in chimera_indices] if vert_root_neighbours: verti, horiz = rooted_tile(adj, vert_root_neighbours[0], t) root = next(iter(horiz)) row = 0 col += 1 return chimera_indices
python
def canonical_chimera_labeling(G, t=None): """Returns a mapping from the labels of G to chimera-indexed labeling. Parameters ---------- G : NetworkX graph A Chimera-structured graph. t : int (optional, default 4) Size of the shore within each Chimera tile. Returns ------- chimera_indices: dict A mapping from the current labels to a 4-tuple of Chimera indices. """ adj = G.adj if t is None: if hasattr(G, 'edges'): num_edges = len(G.edges) else: num_edges = len(G.quadratic) t = _chimera_shore_size(adj, num_edges) chimera_indices = {} row = col = 0 root = min(adj, key=lambda v: len(adj[v])) horiz, verti = rooted_tile(adj, root, t) while len(chimera_indices) < len(adj): new_indices = {} if row == 0: # if we're in the 0th row, we can assign the horizontal randomly for si, v in enumerate(horiz): new_indices[v] = (row, col, 0, si) else: # we need to match the row above for v in horiz: north = [u for u in adj[v] if u in chimera_indices] assert len(north) == 1 i, j, u, si = chimera_indices[north[0]] assert i == row - 1 and j == col and u == 0 new_indices[v] = (row, col, 0, si) if col == 0: # if we're in the 0th col, we can assign the vertical randomly for si, v in enumerate(verti): new_indices[v] = (row, col, 1, si) else: # we need to match the column to the east for v in verti: east = [u for u in adj[v] if u in chimera_indices] assert len(east) == 1 i, j, u, si = chimera_indices[east[0]] assert i == row and j == col - 1 and u == 1 new_indices[v] = (row, col, 1, si) chimera_indices.update(new_indices) # get the next root root_neighbours = [v for v in adj[root] if v not in chimera_indices] if len(root_neighbours) == 1: # we can increment the row root = root_neighbours[0] horiz, verti = rooted_tile(adj, root, t) row += 1 else: # need to go back to row 0, and increment the column assert not root_neighbours # should be empty # we want (0, col, 1, 0), we could cache this, but for now let's just go look for it # the slow way vert_root = [v for v in chimera_indices if chimera_indices[v] == (0, col, 1, 0)][0] vert_root_neighbours = [v for v in adj[vert_root] if v not in chimera_indices] if vert_root_neighbours: verti, horiz = rooted_tile(adj, vert_root_neighbours[0], t) root = next(iter(horiz)) row = 0 col += 1 return chimera_indices
[ "def", "canonical_chimera_labeling", "(", "G", ",", "t", "=", "None", ")", ":", "adj", "=", "G", ".", "adj", "if", "t", "is", "None", ":", "if", "hasattr", "(", "G", ",", "'edges'", ")", ":", "num_edges", "=", "len", "(", "G", ".", "edges", ")", ...
Returns a mapping from the labels of G to chimera-indexed labeling. Parameters ---------- G : NetworkX graph A Chimera-structured graph. t : int (optional, default 4) Size of the shore within each Chimera tile. Returns ------- chimera_indices: dict A mapping from the current labels to a 4-tuple of Chimera indices.
[ "Returns", "a", "mapping", "from", "the", "labels", "of", "G", "to", "chimera", "-", "indexed", "labeling", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/canonicalization.py#L25-L113
train
205,072
dwavesystems/dwave_networkx
dwave_networkx/algorithms/independent_set.py
maximum_weighted_independent_set
def maximum_weighted_independent_set(G, weight=None, sampler=None, lagrange=2.0, **sampler_args): """Returns an approximate maximum weighted independent set. Defines a QUBO with ground states corresponding to a maximum weighted independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of maximum total node weight. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut weighted independent set. weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum weighted independent set, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5. """ # Get a QUBO representation of the problem Q = maximum_weighted_independent_set_qubo(G, weight, lagrange) # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # nodes that are spin up or true are exactly the ones in S. return [node for node in sample if sample[node] > 0]
python
def maximum_weighted_independent_set(G, weight=None, sampler=None, lagrange=2.0, **sampler_args): """Returns an approximate maximum weighted independent set. Defines a QUBO with ground states corresponding to a maximum weighted independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of maximum total node weight. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut weighted independent set. weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum weighted independent set, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5. """ # Get a QUBO representation of the problem Q = maximum_weighted_independent_set_qubo(G, weight, lagrange) # use the sampler to find low energy states response = sampler.sample_qubo(Q, **sampler_args) # we want the lowest energy sample sample = next(iter(response)) # nodes that are spin up or true are exactly the ones in S. return [node for node in sample if sample[node] > 0]
[ "def", "maximum_weighted_independent_set", "(", "G", ",", "weight", "=", "None", ",", "sampler", "=", "None", ",", "lagrange", "=", "2.0", ",", "*", "*", "sampler_args", ")", ":", "# Get a QUBO representation of the problem", "Q", "=", "maximum_weighted_independent_...
Returns an approximate maximum weighted independent set. Defines a QUBO with ground states corresponding to a maximum weighted independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of maximum total node weight. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut weighted independent set. weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum weighted independent set, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5.
[ "Returns", "an", "approximate", "maximum", "weighted", "independent", "set", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/independent_set.py#L24-L95
train
205,073
dwavesystems/dwave_networkx
dwave_networkx/algorithms/independent_set.py
maximum_independent_set
def maximum_independent_set(G, sampler=None, lagrange=2.0, **sampler_args): """Returns an approximate maximum independent set. Defines a QUBO with ground states corresponding to a maximum independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of largest possible size. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut independent set. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum independent set, as determined by the given sampler. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum independent set for a graph of a Chimera unit cell created using the `chimera_graph()` function. >>> import dimod >>> sampler = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> indep_nodes = dnx.maximum_independent_set(G, sampler) Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5. """ return maximum_weighted_independent_set(G, None, sampler, lagrange, **sampler_args)
python
def maximum_independent_set(G, sampler=None, lagrange=2.0, **sampler_args): """Returns an approximate maximum independent set. Defines a QUBO with ground states corresponding to a maximum independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of largest possible size. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut independent set. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum independent set, as determined by the given sampler. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum independent set for a graph of a Chimera unit cell created using the `chimera_graph()` function. >>> import dimod >>> sampler = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> indep_nodes = dnx.maximum_independent_set(G, sampler) Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5. """ return maximum_weighted_independent_set(G, None, sampler, lagrange, **sampler_args)
[ "def", "maximum_independent_set", "(", "G", ",", "sampler", "=", "None", ",", "lagrange", "=", "2.0", ",", "*", "*", "sampler_args", ")", ":", "return", "maximum_weighted_independent_set", "(", "G", ",", "None", ",", "sampler", ",", "lagrange", ",", "*", "...
Returns an approximate maximum independent set. Defines a QUBO with ground states corresponding to a maximum independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of largest possible size. Parameters ---------- G : NetworkX graph The graph on which to find a maximum cut independent set. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum independent set, as determined by the given sampler. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum independent set for a graph of a Chimera unit cell created using the `chimera_graph()` function. >>> import dimod >>> sampler = dimod.SimulatedAnnealingSampler() >>> G = dnx.chimera_graph(1, 1, 4) >>> indep_nodes = dnx.maximum_independent_set(G, sampler) Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References ---------- `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5.
[ "Returns", "an", "approximate", "maximum", "independent", "set", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/independent_set.py#L99-L167
train
205,074
dwavesystems/dwave_networkx
dwave_networkx/algorithms/independent_set.py
maximum_weighted_independent_set_qubo
def maximum_weighted_independent_set_qubo(G, weight=None, lagrange=2.0): """Return the QUBO with ground states corresponding to a maximum weighted independent set. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). Returns ------- QUBO : dict The QUBO with ground states corresponding to a maximum weighted independent set. Examples -------- >>> from dwave_networkx.algorithms.independent_set import maximum_weighted_independent_set_qubo ... >>> G = nx.path_graph(3) >>> Q = maximum_weighted_independent_set_qubo(G, weight='weight', lagrange=2.0) >>> Q[(0, 0)] -1.0 >>> Q[(1, 1)] -1.0 >>> Q[(0, 1)] 2.0 """ # empty QUBO for an empty graph if not G: return {} # We assume that the sampler can handle an unstructured QUBO problem, so let's set one up. # Let us define the largest independent set to be S. # For each node n in the graph, we assign a boolean variable v_n, where v_n = 1 when n # is in S and v_n = 0 otherwise. # We call the matrix defining our QUBO problem Q. # On the diagnonal, we assign the linear bias for each node to be the negative of its weight. # This means that each node is biased towards being in S. Weights are scaled to a maximum of 1. # Negative weights are considered 0. # On the off diagnonal, we assign the off-diagonal terms of Q to be 2. Thus, if both # nodes are in S, the overall energy is increased by 2. cost = dict(G.nodes(data=weight, default=1)) scale = max(cost.values()) Q = {(node, node): min(-cost[node] / scale, 0.0) for node in G} Q.update({edge: lagrange for edge in G.edges}) return Q
python
def maximum_weighted_independent_set_qubo(G, weight=None, lagrange=2.0): """Return the QUBO with ground states corresponding to a maximum weighted independent set. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). Returns ------- QUBO : dict The QUBO with ground states corresponding to a maximum weighted independent set. Examples -------- >>> from dwave_networkx.algorithms.independent_set import maximum_weighted_independent_set_qubo ... >>> G = nx.path_graph(3) >>> Q = maximum_weighted_independent_set_qubo(G, weight='weight', lagrange=2.0) >>> Q[(0, 0)] -1.0 >>> Q[(1, 1)] -1.0 >>> Q[(0, 1)] 2.0 """ # empty QUBO for an empty graph if not G: return {} # We assume that the sampler can handle an unstructured QUBO problem, so let's set one up. # Let us define the largest independent set to be S. # For each node n in the graph, we assign a boolean variable v_n, where v_n = 1 when n # is in S and v_n = 0 otherwise. # We call the matrix defining our QUBO problem Q. # On the diagnonal, we assign the linear bias for each node to be the negative of its weight. # This means that each node is biased towards being in S. Weights are scaled to a maximum of 1. # Negative weights are considered 0. # On the off diagnonal, we assign the off-diagonal terms of Q to be 2. Thus, if both # nodes are in S, the overall energy is increased by 2. cost = dict(G.nodes(data=weight, default=1)) scale = max(cost.values()) Q = {(node, node): min(-cost[node] / scale, 0.0) for node in G} Q.update({edge: lagrange for edge in G.edges}) return Q
[ "def", "maximum_weighted_independent_set_qubo", "(", "G", ",", "weight", "=", "None", ",", "lagrange", "=", "2.0", ")", ":", "# empty QUBO for an empty graph", "if", "not", "G", ":", "return", "{", "}", "# We assume that the sampler can handle an unstructured QUBO problem...
Return the QUBO with ground states corresponding to a maximum weighted independent set. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). Returns ------- QUBO : dict The QUBO with ground states corresponding to a maximum weighted independent set. Examples -------- >>> from dwave_networkx.algorithms.independent_set import maximum_weighted_independent_set_qubo ... >>> G = nx.path_graph(3) >>> Q = maximum_weighted_independent_set_qubo(G, weight='weight', lagrange=2.0) >>> Q[(0, 0)] -1.0 >>> Q[(1, 1)] -1.0 >>> Q[(0, 1)] 2.0
[ "Return", "the", "QUBO", "with", "ground", "states", "corresponding", "to", "a", "maximum", "weighted", "independent", "set", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/independent_set.py#L208-L264
train
205,075
dwavesystems/dwave_networkx
dwave_networkx/algorithms/cover.py
min_weighted_vertex_cover
def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args): """Returns an approximate minimum weighted vertex cover. Defines a QUBO with ground states corresponding to a minimum weighted vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. A minimum weighted vertex cover is the vertex cover of minimum total node weight. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- vertex_cover : list List of nodes that the form a the minimum weighted vertex cover, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. https://en.wikipedia.org/wiki/Vertex_cover https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization References ---------- Based on the formulation presented in [AL]_ """ indep_nodes = set(maximum_weighted_independent_set(G, weight, sampler, **sampler_args)) return [v for v in G if v not in indep_nodes]
python
def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args): """Returns an approximate minimum weighted vertex cover. Defines a QUBO with ground states corresponding to a minimum weighted vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. A minimum weighted vertex cover is the vertex cover of minimum total node weight. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- vertex_cover : list List of nodes that the form a the minimum weighted vertex cover, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. https://en.wikipedia.org/wiki/Vertex_cover https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization References ---------- Based on the formulation presented in [AL]_ """ indep_nodes = set(maximum_weighted_independent_set(G, weight, sampler, **sampler_args)) return [v for v in G if v not in indep_nodes]
[ "def", "min_weighted_vertex_cover", "(", "G", ",", "weight", "=", "None", ",", "sampler", "=", "None", ",", "*", "*", "sampler_args", ")", ":", "indep_nodes", "=", "set", "(", "maximum_weighted_independent_set", "(", "G", ",", "weight", ",", "sampler", ",", ...
Returns an approximate minimum weighted vertex cover. Defines a QUBO with ground states corresponding to a minimum weighted vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. A minimum weighted vertex cover is the vertex cover of minimum total node weight. Parameters ---------- G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- vertex_cover : list List of nodes that the form a the minimum weighted vertex cover, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. https://en.wikipedia.org/wiki/Vertex_cover https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization References ---------- Based on the formulation presented in [AL]_
[ "Returns", "an", "approximate", "minimum", "weighted", "vertex", "cover", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/cover.py#L23-L77
train
205,076
dwavesystems/dwave_networkx
dwave_networkx/algorithms/cover.py
is_vertex_cover
def is_vertex_cover(G, vertex_cover): """Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters ---------- G : NetworkX graph The graph on which to check the vertex cover. vertex_cover : Iterable of nodes. Returns ------- is_cover : bool True if the given iterable forms a vertex cover. Examples -------- This example checks two covers for a graph, G, of a single Chimera unit cell. The first uses the set of the four horizontal qubits, which do constitute a cover; the second set removes one node. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> cover = [0, 1, 2, 3] >>> dnx.is_vertex_cover(G,cover) True >>> cover = [0, 1, 2] >>> dnx.is_vertex_cover(G,cover) False """ cover = set(vertex_cover) return all(u in cover or v in cover for u, v in G.edges)
python
def is_vertex_cover(G, vertex_cover): """Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters ---------- G : NetworkX graph The graph on which to check the vertex cover. vertex_cover : Iterable of nodes. Returns ------- is_cover : bool True if the given iterable forms a vertex cover. Examples -------- This example checks two covers for a graph, G, of a single Chimera unit cell. The first uses the set of the four horizontal qubits, which do constitute a cover; the second set removes one node. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> cover = [0, 1, 2, 3] >>> dnx.is_vertex_cover(G,cover) True >>> cover = [0, 1, 2] >>> dnx.is_vertex_cover(G,cover) False """ cover = set(vertex_cover) return all(u in cover or v in cover for u, v in G.edges)
[ "def", "is_vertex_cover", "(", "G", ",", "vertex_cover", ")", ":", "cover", "=", "set", "(", "vertex_cover", ")", "return", "all", "(", "u", "in", "cover", "or", "v", "in", "cover", "for", "u", ",", "v", "in", "G", ".", "edges", ")" ]
Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters ---------- G : NetworkX graph The graph on which to check the vertex cover. vertex_cover : Iterable of nodes. Returns ------- is_cover : bool True if the given iterable forms a vertex cover. Examples -------- This example checks two covers for a graph, G, of a single Chimera unit cell. The first uses the set of the four horizontal qubits, which do constitute a cover; the second set removes one node. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> cover = [0, 1, 2, 3] >>> dnx.is_vertex_cover(G,cover) True >>> cover = [0, 1, 2] >>> dnx.is_vertex_cover(G,cover) False
[ "Determines", "whether", "the", "given", "set", "of", "vertices", "is", "a", "vertex", "cover", "of", "graph", "G", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/cover.py#L150-L186
train
205,077
dwavesystems/dwave_networkx
dwave_networkx/drawing/pegasus_layout.py
pegasus_layout
def pegasus_layout(G, scale=1., center=None, dim=2, crosses=False): """Positions the nodes of graph G in a Pegasus topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.pegasus_graph(1) >>> pos = dnx.pegasus_layout(G) """ if not isinstance(G, nx.Graph) or G.graph.get("family") != "pegasus": raise ValueError("G must be generated by dwave_networkx.pegasus_graph") if G.graph.get('labels') == 'nice': m = 3*(G.graph['rows']-1) c_coords = chimera_node_placer_2d(m, m, 4, scale=scale, center=center, dim=dim) def xy_coords(t, y, x, u, k): return c_coords(3*y+2-t, 3*x+t, u, k) pos = {v: xy_coords(*v) for v in G.nodes()} else: xy_coords = pegasus_node_placer_2d(G, scale, center, dim, crosses=crosses) if G.graph.get('labels') == 'coordinate': pos = {v: xy_coords(*v) for v in G.nodes()} elif G.graph.get('data'): pos = {v: xy_coords(*dat['pegasus_index']) for v, dat in G.nodes(data=True)} else: m = G.graph.get('rows') coord = pegasus_coordinates(m) pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()} return pos
python
def pegasus_layout(G, scale=1., center=None, dim=2, crosses=False): """Positions the nodes of graph G in a Pegasus topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.pegasus_graph(1) >>> pos = dnx.pegasus_layout(G) """ if not isinstance(G, nx.Graph) or G.graph.get("family") != "pegasus": raise ValueError("G must be generated by dwave_networkx.pegasus_graph") if G.graph.get('labels') == 'nice': m = 3*(G.graph['rows']-1) c_coords = chimera_node_placer_2d(m, m, 4, scale=scale, center=center, dim=dim) def xy_coords(t, y, x, u, k): return c_coords(3*y+2-t, 3*x+t, u, k) pos = {v: xy_coords(*v) for v in G.nodes()} else: xy_coords = pegasus_node_placer_2d(G, scale, center, dim, crosses=crosses) if G.graph.get('labels') == 'coordinate': pos = {v: xy_coords(*v) for v in G.nodes()} elif G.graph.get('data'): pos = {v: xy_coords(*dat['pegasus_index']) for v, dat in G.nodes(data=True)} else: m = G.graph.get('rows') coord = pegasus_coordinates(m) pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()} return pos
[ "def", "pegasus_layout", "(", "G", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ",", "crosses", "=", "False", ")", ":", "if", "not", "isinstance", "(", "G", ",", "nx", ".", "Graph", ")", "or", "G", ".", "graph", "....
Positions the nodes of graph G in a Pegasus topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.pegasus_graph(1) >>> pos = dnx.pegasus_layout(G)
[ "Positions", "the", "nodes", "of", "graph", "G", "in", "a", "Pegasus", "topology", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/pegasus_layout.py#L45-L104
train
205,078
dwavesystems/dwave_networkx
dwave_networkx/drawing/pegasus_layout.py
pegasus_node_placer_2d
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot. """ import numpy as np m = G.graph.get('rows') h_offsets = G.graph.get("horizontal_offsets") v_offsets = G.graph.get("vertical_offsets") tile_width = G.graph.get("tile") tile_center = tile_width / 2 - .5 # want the enter plot to fill in [0, 1] when scale=1 scale /= m * tile_width if center is None: center = np.zeros(dim) else: center = np.asarray(center) paddims = dim - 2 if paddims < 0: raise ValueError("layout must have at least two dimensions") if len(center) != dim: raise ValueError("length of center coordinates must match dimension of layout") if crosses: # adjustment for crosses cross_shift = 2. else: cross_shift = 0. def _xy_coords(u, w, k, z): # orientation, major perpendicular offset, minor perpendicular offset, parallel offset if k % 2: p = -.1 else: p = .1 if u: xy = np.array([z*tile_width+h_offsets[k] + tile_center, -tile_width*w-k-p+cross_shift]) else: xy = np.array([tile_width*w+k+p+cross_shift, -z*tile_width-v_offsets[k]-tile_center]) # convention for Pegasus-lattice pictures is to invert the y-axis return np.hstack((xy * scale, np.zeros(paddims))) + center return _xy_coords
python
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot. """ import numpy as np m = G.graph.get('rows') h_offsets = G.graph.get("horizontal_offsets") v_offsets = G.graph.get("vertical_offsets") tile_width = G.graph.get("tile") tile_center = tile_width / 2 - .5 # want the enter plot to fill in [0, 1] when scale=1 scale /= m * tile_width if center is None: center = np.zeros(dim) else: center = np.asarray(center) paddims = dim - 2 if paddims < 0: raise ValueError("layout must have at least two dimensions") if len(center) != dim: raise ValueError("length of center coordinates must match dimension of layout") if crosses: # adjustment for crosses cross_shift = 2. else: cross_shift = 0. def _xy_coords(u, w, k, z): # orientation, major perpendicular offset, minor perpendicular offset, parallel offset if k % 2: p = -.1 else: p = .1 if u: xy = np.array([z*tile_width+h_offsets[k] + tile_center, -tile_width*w-k-p+cross_shift]) else: xy = np.array([tile_width*w+k+p+cross_shift, -z*tile_width-v_offsets[k]-tile_center]) # convention for Pegasus-lattice pictures is to invert the y-axis return np.hstack((xy * scale, np.zeros(paddims))) + center return _xy_coords
[ "def", "pegasus_node_placer_2d", "(", "G", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ",", "crosses", "=", "False", ")", ":", "import", "numpy", "as", "np", "m", "=", "G", ".", "graph", ".", "get", "(", "'rows'", "...
Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot.
[ "Generates", "a", "function", "that", "converts", "Pegasus", "indices", "to", "x", "y", "coordinates", "for", "a", "plot", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/pegasus_layout.py#L107-L184
train
205,079
dwavesystems/dwave_networkx
dwave_networkx/drawing/pegasus_layout.py
draw_pegasus
def draw_pegasus(G, crosses=False, **kwargs): """Draws graph G in a Pegasus topology. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph, a product of dwave_networkx.pegasus_graph. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. Examples -------- >>> # Plot a Pegasus graph with size parameter 2 >>> import networkx as nx >>> import dwave_networkx as dnx >>> import matplotlib.pyplot as plt >>> G = dnx.pegasus_graph(2) >>> dnx.draw_pegasus(G) >>> plt.show() """ draw_qubit_graph(G, pegasus_layout(G, crosses=crosses), **kwargs)
python
def draw_pegasus(G, crosses=False, **kwargs): """Draws graph G in a Pegasus topology. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph, a product of dwave_networkx.pegasus_graph. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. Examples -------- >>> # Plot a Pegasus graph with size parameter 2 >>> import networkx as nx >>> import dwave_networkx as dnx >>> import matplotlib.pyplot as plt >>> G = dnx.pegasus_graph(2) >>> dnx.draw_pegasus(G) >>> plt.show() """ draw_qubit_graph(G, pegasus_layout(G, crosses=crosses), **kwargs)
[ "def", "draw_pegasus", "(", "G", ",", "crosses", "=", "False", ",", "*", "*", "kwargs", ")", ":", "draw_qubit_graph", "(", "G", ",", "pegasus_layout", "(", "G", ",", "crosses", "=", "crosses", ")", ",", "*", "*", "kwargs", ")" ]
Draws graph G in a Pegasus topology. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph, a product of dwave_networkx.pegasus_graph. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. Examples -------- >>> # Plot a Pegasus graph with size parameter 2 >>> import networkx as nx >>> import dwave_networkx as dnx >>> import matplotlib.pyplot as plt >>> G = dnx.pegasus_graph(2) >>> dnx.draw_pegasus(G) >>> plt.show()
[ "Draws", "graph", "G", "in", "a", "Pegasus", "topology", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/pegasus_layout.py#L187-L231
train
205,080
dwavesystems/dwave_networkx
dwave_networkx/drawing/pegasus_layout.py
draw_pegasus_embedding
def draw_pegasus_embedding(G, *args, **kwargs): """Draws an embedding onto the pegasus graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. """ crosses = kwargs.pop("crosses", False) draw_embedding(G, pegasus_layout(G, crosses=crosses), *args, **kwargs)
python
def draw_pegasus_embedding(G, *args, **kwargs): """Draws an embedding onto the pegasus graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. """ crosses = kwargs.pop("crosses", False) draw_embedding(G, pegasus_layout(G, crosses=crosses), *args, **kwargs)
[ "def", "draw_pegasus_embedding", "(", "G", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "crosses", "=", "kwargs", ".", "pop", "(", "\"crosses\"", ",", "False", ")", "draw_embedding", "(", "G", ",", "pegasus_layout", "(", "G", ",", "crosses", "=...
Draws an embedding onto the pegasus graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
[ "Draws", "an", "embedding", "onto", "the", "pegasus", "graph", "G", "according", "to", "layout", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/pegasus_layout.py#L234-L287
train
205,081
dwavesystems/dwave_networkx
dwave_networkx/utils/decorators.py
binary_quadratic_model_sampler
def binary_quadratic_model_sampler(which_args): """Decorator to validate sampler arguments. Parameters ---------- which_args : int or sequence of ints Location of the sampler arguments of the input function in the form `function_name(args, *kw)`. If more than one sampler is allowed, can be a list of locations. Returns ------- _binary_quadratic_model_sampler : function Caller function that validates the sampler format. A sampler is expected to have `sample_qubo` and `sample_ising` methods. Alternatively, if no sampler is provided (or sampler is None), the sampler set by the `set_default_sampler` function is provided to the function. Examples -------- Decorate functions like this:: @binary_quadratic_model_sampler(1) def maximal_matching(G, sampler, **sampler_args): pass This example validates two placeholder samplers, which return a correct response only in the case of finding an independent set on a complete graph (where one node is always an independent set), the first valid, the second missing a method. >>> import networkx as nx >>> import dwave_networkx as dnx >>> from dwave_networkx.utils import decorators >>> # Create two placeholder samplers >>> class WellDefinedSampler: ... # an example sampler, only works for independent set on complete ... # graphs ... def __init__(self, name): ... self.name = name ... def sample_ising(self, h, J): ... sample = {v: -1 for v in h} ... sample[0] = 1 # set one node to true ... return [sample] ... def sample_qubo(self, Q): ... sample = {v: 0 for v in set().union(*Q)} ... sample[0] = 1 # set one node to true ... return [sample] ... def __str__(self): ... return self.name ... >>> class IllDefinedSampler: ... # an example sampler missing a `sample_qubo` method ... def __init__(self, name): ... self.name = name ... def sample_ising(self, h, J): ... sample = {v: -1 for v in h} ... sample[0] = 1 # set one node to true ... return [sample] ... def __str__(self): ... return self.name ... >>> sampler1 = WellDefinedSampler('sampler1') >>> sampler2 = IllDefinedSampler('sampler2') >>> # Define a placeholder independent-set function with the decorator >>> @dnx.utils.binary_quadratic_model_sampler(1) ... def independent_set(G, sampler, **sampler_args): ... Q = {(node, node): -1 for node in G} ... Q.update({edge: 2 for edge in G.edges}) ... response = sampler.sample_qubo(Q, **sampler_args) ... sample = next(iter(response)) ... return [node for node in sample if sample[node] > 0] ... >>> # Validate the samplers >>> G = nx.complete_graph(5) >>> independent_set(G, sampler1) [0] >>> independent_set(G, sampler2) # doctest: +SKIP --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-670b71b268c7> in <module>() ----> 1 independent_set(G, IllDefinedSampler) <decorator-gen-628> in independent_set(G, sampler, **sampler_args) /usr/local/lib/python2.7/dist-packages/dwave_networkx/utils/decorators.pyc in _binary_quadratic_model_sampler(f, *args, **kw) 61 62 if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo): ---> 63 raise TypeError("expected sampler to have a 'sample_qubo' method") 64 if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising): 65 raise TypeError("expected sampler to have a 'sample_ising' method") TypeError: expected sampler to have a 'sample_qubo' method """ @decorator def _binary_quadratic_model_sampler(f, *args, **kw): # convert into a sequence if necessary if isinstance(which_args, int): iter_args = (which_args,) else: iter_args = iter(which_args) # check each sampler for the correct methods new_args = [arg for arg in args] for idx in iter_args: sampler = args[idx] # if no sampler is provided, get the default sampler if it has # been set if sampler is None: # this sampler has already been vetted default_sampler = dnx.get_default_sampler() if default_sampler is None: raise dnx.DWaveNetworkXMissingSampler('no default sampler set') new_args[idx] = default_sampler continue if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo): raise TypeError("expected sampler to have a 'sample_qubo' method") if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising): raise TypeError("expected sampler to have a 'sample_ising' method") # now run the function and return the results return f(*new_args, **kw) return _binary_quadratic_model_sampler
python
def binary_quadratic_model_sampler(which_args): """Decorator to validate sampler arguments. Parameters ---------- which_args : int or sequence of ints Location of the sampler arguments of the input function in the form `function_name(args, *kw)`. If more than one sampler is allowed, can be a list of locations. Returns ------- _binary_quadratic_model_sampler : function Caller function that validates the sampler format. A sampler is expected to have `sample_qubo` and `sample_ising` methods. Alternatively, if no sampler is provided (or sampler is None), the sampler set by the `set_default_sampler` function is provided to the function. Examples -------- Decorate functions like this:: @binary_quadratic_model_sampler(1) def maximal_matching(G, sampler, **sampler_args): pass This example validates two placeholder samplers, which return a correct response only in the case of finding an independent set on a complete graph (where one node is always an independent set), the first valid, the second missing a method. >>> import networkx as nx >>> import dwave_networkx as dnx >>> from dwave_networkx.utils import decorators >>> # Create two placeholder samplers >>> class WellDefinedSampler: ... # an example sampler, only works for independent set on complete ... # graphs ... def __init__(self, name): ... self.name = name ... def sample_ising(self, h, J): ... sample = {v: -1 for v in h} ... sample[0] = 1 # set one node to true ... return [sample] ... def sample_qubo(self, Q): ... sample = {v: 0 for v in set().union(*Q)} ... sample[0] = 1 # set one node to true ... return [sample] ... def __str__(self): ... return self.name ... >>> class IllDefinedSampler: ... # an example sampler missing a `sample_qubo` method ... def __init__(self, name): ... self.name = name ... def sample_ising(self, h, J): ... sample = {v: -1 for v in h} ... sample[0] = 1 # set one node to true ... return [sample] ... def __str__(self): ... return self.name ... >>> sampler1 = WellDefinedSampler('sampler1') >>> sampler2 = IllDefinedSampler('sampler2') >>> # Define a placeholder independent-set function with the decorator >>> @dnx.utils.binary_quadratic_model_sampler(1) ... def independent_set(G, sampler, **sampler_args): ... Q = {(node, node): -1 for node in G} ... Q.update({edge: 2 for edge in G.edges}) ... response = sampler.sample_qubo(Q, **sampler_args) ... sample = next(iter(response)) ... return [node for node in sample if sample[node] > 0] ... >>> # Validate the samplers >>> G = nx.complete_graph(5) >>> independent_set(G, sampler1) [0] >>> independent_set(G, sampler2) # doctest: +SKIP --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-670b71b268c7> in <module>() ----> 1 independent_set(G, IllDefinedSampler) <decorator-gen-628> in independent_set(G, sampler, **sampler_args) /usr/local/lib/python2.7/dist-packages/dwave_networkx/utils/decorators.pyc in _binary_quadratic_model_sampler(f, *args, **kw) 61 62 if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo): ---> 63 raise TypeError("expected sampler to have a 'sample_qubo' method") 64 if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising): 65 raise TypeError("expected sampler to have a 'sample_ising' method") TypeError: expected sampler to have a 'sample_qubo' method """ @decorator def _binary_quadratic_model_sampler(f, *args, **kw): # convert into a sequence if necessary if isinstance(which_args, int): iter_args = (which_args,) else: iter_args = iter(which_args) # check each sampler for the correct methods new_args = [arg for arg in args] for idx in iter_args: sampler = args[idx] # if no sampler is provided, get the default sampler if it has # been set if sampler is None: # this sampler has already been vetted default_sampler = dnx.get_default_sampler() if default_sampler is None: raise dnx.DWaveNetworkXMissingSampler('no default sampler set') new_args[idx] = default_sampler continue if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo): raise TypeError("expected sampler to have a 'sample_qubo' method") if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising): raise TypeError("expected sampler to have a 'sample_ising' method") # now run the function and return the results return f(*new_args, **kw) return _binary_quadratic_model_sampler
[ "def", "binary_quadratic_model_sampler", "(", "which_args", ")", ":", "@", "decorator", "def", "_binary_quadratic_model_sampler", "(", "f", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# convert into a sequence if necessary", "if", "isinstance", "(", "which_arg...
Decorator to validate sampler arguments. Parameters ---------- which_args : int or sequence of ints Location of the sampler arguments of the input function in the form `function_name(args, *kw)`. If more than one sampler is allowed, can be a list of locations. Returns ------- _binary_quadratic_model_sampler : function Caller function that validates the sampler format. A sampler is expected to have `sample_qubo` and `sample_ising` methods. Alternatively, if no sampler is provided (or sampler is None), the sampler set by the `set_default_sampler` function is provided to the function. Examples -------- Decorate functions like this:: @binary_quadratic_model_sampler(1) def maximal_matching(G, sampler, **sampler_args): pass This example validates two placeholder samplers, which return a correct response only in the case of finding an independent set on a complete graph (where one node is always an independent set), the first valid, the second missing a method. >>> import networkx as nx >>> import dwave_networkx as dnx >>> from dwave_networkx.utils import decorators >>> # Create two placeholder samplers >>> class WellDefinedSampler: ... # an example sampler, only works for independent set on complete ... # graphs ... def __init__(self, name): ... self.name = name ... def sample_ising(self, h, J): ... sample = {v: -1 for v in h} ... sample[0] = 1 # set one node to true ... return [sample] ... def sample_qubo(self, Q): ... sample = {v: 0 for v in set().union(*Q)} ... sample[0] = 1 # set one node to true ... return [sample] ... def __str__(self): ... return self.name ... >>> class IllDefinedSampler: ... # an example sampler missing a `sample_qubo` method ... def __init__(self, name): ... self.name = name ... def sample_ising(self, h, J): ... sample = {v: -1 for v in h} ... sample[0] = 1 # set one node to true ... return [sample] ... def __str__(self): ... return self.name ... >>> sampler1 = WellDefinedSampler('sampler1') >>> sampler2 = IllDefinedSampler('sampler2') >>> # Define a placeholder independent-set function with the decorator >>> @dnx.utils.binary_quadratic_model_sampler(1) ... def independent_set(G, sampler, **sampler_args): ... Q = {(node, node): -1 for node in G} ... Q.update({edge: 2 for edge in G.edges}) ... response = sampler.sample_qubo(Q, **sampler_args) ... sample = next(iter(response)) ... return [node for node in sample if sample[node] > 0] ... >>> # Validate the samplers >>> G = nx.complete_graph(5) >>> independent_set(G, sampler1) [0] >>> independent_set(G, sampler2) # doctest: +SKIP --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-670b71b268c7> in <module>() ----> 1 independent_set(G, IllDefinedSampler) <decorator-gen-628> in independent_set(G, sampler, **sampler_args) /usr/local/lib/python2.7/dist-packages/dwave_networkx/utils/decorators.pyc in _binary_quadratic_model_sampler(f, *args, **kw) 61 62 if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo): ---> 63 raise TypeError("expected sampler to have a 'sample_qubo' method") 64 if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising): 65 raise TypeError("expected sampler to have a 'sample_ising' method") TypeError: expected sampler to have a 'sample_qubo' method
[ "Decorator", "to", "validate", "sampler", "arguments", "." ]
9ea1223ddbc7e86db2f90b8b23e250e6642c3d68
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/utils/decorators.py#L28-L151
train
205,082
datascopeanalytics/traces
traces/utils.py
duration_to_number
def duration_to_number(duration, units='seconds'): """If duration is already a numeric type, then just return duration. If duration is a timedelta, return a duration in seconds. TODO: allow for multiple types of units. """ if isinstance(duration, (int, float, long)): return duration elif isinstance(duration, (datetime.timedelta,)): if units == 'seconds': return duration.total_seconds() else: msg = 'unit "%s" is not supported' % units raise NotImplementedError(msg) elif duration == inf or duration == -inf: msg = "Can't convert infinite duration to number" raise ValueError(msg) else: msg = 'duration is an unknown type (%s)' % duration raise TypeError(msg)
python
def duration_to_number(duration, units='seconds'): """If duration is already a numeric type, then just return duration. If duration is a timedelta, return a duration in seconds. TODO: allow for multiple types of units. """ if isinstance(duration, (int, float, long)): return duration elif isinstance(duration, (datetime.timedelta,)): if units == 'seconds': return duration.total_seconds() else: msg = 'unit "%s" is not supported' % units raise NotImplementedError(msg) elif duration == inf or duration == -inf: msg = "Can't convert infinite duration to number" raise ValueError(msg) else: msg = 'duration is an unknown type (%s)' % duration raise TypeError(msg)
[ "def", "duration_to_number", "(", "duration", ",", "units", "=", "'seconds'", ")", ":", "if", "isinstance", "(", "duration", ",", "(", "int", ",", "float", ",", "long", ")", ")", ":", "return", "duration", "elif", "isinstance", "(", "duration", ",", "(",...
If duration is already a numeric type, then just return duration. If duration is a timedelta, return a duration in seconds. TODO: allow for multiple types of units.
[ "If", "duration", "is", "already", "a", "numeric", "type", "then", "just", "return", "duration", ".", "If", "duration", "is", "a", "timedelta", "return", "a", "duration", "in", "seconds", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/utils.py#L6-L27
train
205,083
datascopeanalytics/traces
traces/utils.py
convert_args_to_list
def convert_args_to_list(args): """Convert all iterable pairs of inputs into a list of list""" list_of_pairs = [] if len(args) == 0: return [] if any(isinstance(arg, (list, tuple)) for arg in args): # Domain([[1, 4]]) # Domain([(1, 4)]) # Domain([(1, 4), (5, 8)]) # Domain([[1, 4], [5, 8]]) if len(args) == 1 and \ any(isinstance(arg, (list, tuple)) for arg in args[0]): for item in args[0]: list_of_pairs.append(list(item)) else: # Domain([1, 4]) # Domain((1, 4)) # Domain((1, 4), (5, 8)) # Domain([1, 4], [5, 8]) for item in args: list_of_pairs.append(list(item)) else: # Domain(1, 2) if len(args) == 2: list_of_pairs.append(list(args)) else: msg = "The argument type is invalid. ".format(args) raise TypeError(msg) return list_of_pairs
python
def convert_args_to_list(args): """Convert all iterable pairs of inputs into a list of list""" list_of_pairs = [] if len(args) == 0: return [] if any(isinstance(arg, (list, tuple)) for arg in args): # Domain([[1, 4]]) # Domain([(1, 4)]) # Domain([(1, 4), (5, 8)]) # Domain([[1, 4], [5, 8]]) if len(args) == 1 and \ any(isinstance(arg, (list, tuple)) for arg in args[0]): for item in args[0]: list_of_pairs.append(list(item)) else: # Domain([1, 4]) # Domain((1, 4)) # Domain((1, 4), (5, 8)) # Domain([1, 4], [5, 8]) for item in args: list_of_pairs.append(list(item)) else: # Domain(1, 2) if len(args) == 2: list_of_pairs.append(list(args)) else: msg = "The argument type is invalid. ".format(args) raise TypeError(msg) return list_of_pairs
[ "def", "convert_args_to_list", "(", "args", ")", ":", "list_of_pairs", "=", "[", "]", "if", "len", "(", "args", ")", "==", "0", ":", "return", "[", "]", "if", "any", "(", "isinstance", "(", "arg", ",", "(", "list", ",", "tuple", ")", ")", "for", ...
Convert all iterable pairs of inputs into a list of list
[ "Convert", "all", "iterable", "pairs", "of", "inputs", "into", "a", "list", "of", "list" ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/utils.py#L30-L60
train
205,084
datascopeanalytics/traces
traces/histogram.py
Histogram.variance
def variance(self): """Variance of the distribution.""" _self = self._discard_value(None) if not _self.total(): return 0.0 mean = _self.mean() weighted_central_moment = sum( count * (value - mean)**2 for value, count in iteritems(_self) ) return weighted_central_moment / float(_self.total())
python
def variance(self): """Variance of the distribution.""" _self = self._discard_value(None) if not _self.total(): return 0.0 mean = _self.mean() weighted_central_moment = sum( count * (value - mean)**2 for value, count in iteritems(_self) ) return weighted_central_moment / float(_self.total())
[ "def", "variance", "(", "self", ")", ":", "_self", "=", "self", ".", "_discard_value", "(", "None", ")", "if", "not", "_self", ".", "total", "(", ")", ":", "return", "0.0", "mean", "=", "_self", ".", "mean", "(", ")", "weighted_central_moment", "=", ...
Variance of the distribution.
[ "Variance", "of", "the", "distribution", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/histogram.py#L83-L92
train
205,085
datascopeanalytics/traces
traces/histogram.py
Histogram.normalized
def normalized(self): """Return a normalized version of the histogram where the values sum to one. """ total = self.total() result = Histogram() for value, count in iteritems(self): try: result[value] = count / float(total) except UnorderableElements as e: result = Histogram.from_dict(dict(result), key=hash) result[value] = count / float(total) return result
python
def normalized(self): """Return a normalized version of the histogram where the values sum to one. """ total = self.total() result = Histogram() for value, count in iteritems(self): try: result[value] = count / float(total) except UnorderableElements as e: result = Histogram.from_dict(dict(result), key=hash) result[value] = count / float(total) return result
[ "def", "normalized", "(", "self", ")", ":", "total", "=", "self", ".", "total", "(", ")", "result", "=", "Histogram", "(", ")", "for", "value", ",", "count", "in", "iteritems", "(", "self", ")", ":", "try", ":", "result", "[", "value", "]", "=", ...
Return a normalized version of the histogram where the values sum to one.
[ "Return", "a", "normalized", "version", "of", "the", "histogram", "where", "the", "values", "sum", "to", "one", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/histogram.py#L98-L111
train
205,086
datascopeanalytics/traces
traces/histogram.py
Histogram._quantile_function
def _quantile_function(self, alpha=0.5, smallest_count=None): """Return a function that returns the quantile values for this histogram. """ total = float(self.total()) smallest_observed_count = min(itervalues(self)) if smallest_count is None: smallest_count = smallest_observed_count else: smallest_count = min(smallest_count, smallest_observed_count) beta = alpha * smallest_count debug_plot = [] cumulative_sum = 0.0 inverse = sortedcontainers.SortedDict() for value, count in iteritems(self): debug_plot.append((cumulative_sum / total, value)) inverse[(cumulative_sum + beta) / total] = value cumulative_sum += count inverse[(cumulative_sum - beta) / total] = value debug_plot.append((cumulative_sum / total, value)) # get maximum and minumum q values q_min = inverse.iloc[0] q_max = inverse.iloc[-1] # this stuff if helpful for debugging -- keep it in here # for i, j in debug_plot: # print i, j # print '' # for i, j in inverse.iteritems(): # print i, j # print '' def function(q): if q < 0.0 or q > 1.0: msg = 'invalid quantile %s, need `0 <= q <= 1`' % q raise ValueError(msg) elif q < q_min: q = q_min elif q > q_max: q = q_max # if beta is if beta > 0: if q in inverse: result = inverse[q] else: previous_index = inverse.bisect_left(q) - 1 x1 = inverse.iloc[previous_index] x2 = inverse.iloc[previous_index + 1] y1 = inverse[x1] y2 = inverse[x2] result = (y2 - y1) * (q - x1) / float(x2 - x1) + y1 else: if q in inverse: previous_index = inverse.bisect_left(q) - 1 x1 = inverse.iloc[previous_index] x2 = inverse.iloc[previous_index + 1] y1 = inverse[x1] y2 = inverse[x2] result = 0.5 * (y1 + y2) else: previous_index = inverse.bisect_left(q) - 1 x1 = inverse.iloc[previous_index] result = inverse[x1] return float(result) return function
python
def _quantile_function(self, alpha=0.5, smallest_count=None): """Return a function that returns the quantile values for this histogram. """ total = float(self.total()) smallest_observed_count = min(itervalues(self)) if smallest_count is None: smallest_count = smallest_observed_count else: smallest_count = min(smallest_count, smallest_observed_count) beta = alpha * smallest_count debug_plot = [] cumulative_sum = 0.0 inverse = sortedcontainers.SortedDict() for value, count in iteritems(self): debug_plot.append((cumulative_sum / total, value)) inverse[(cumulative_sum + beta) / total] = value cumulative_sum += count inverse[(cumulative_sum - beta) / total] = value debug_plot.append((cumulative_sum / total, value)) # get maximum and minumum q values q_min = inverse.iloc[0] q_max = inverse.iloc[-1] # this stuff if helpful for debugging -- keep it in here # for i, j in debug_plot: # print i, j # print '' # for i, j in inverse.iteritems(): # print i, j # print '' def function(q): if q < 0.0 or q > 1.0: msg = 'invalid quantile %s, need `0 <= q <= 1`' % q raise ValueError(msg) elif q < q_min: q = q_min elif q > q_max: q = q_max # if beta is if beta > 0: if q in inverse: result = inverse[q] else: previous_index = inverse.bisect_left(q) - 1 x1 = inverse.iloc[previous_index] x2 = inverse.iloc[previous_index + 1] y1 = inverse[x1] y2 = inverse[x2] result = (y2 - y1) * (q - x1) / float(x2 - x1) + y1 else: if q in inverse: previous_index = inverse.bisect_left(q) - 1 x1 = inverse.iloc[previous_index] x2 = inverse.iloc[previous_index + 1] y1 = inverse[x1] y2 = inverse[x2] result = 0.5 * (y1 + y2) else: previous_index = inverse.bisect_left(q) - 1 x1 = inverse.iloc[previous_index] result = inverse[x1] return float(result) return function
[ "def", "_quantile_function", "(", "self", ",", "alpha", "=", "0.5", ",", "smallest_count", "=", "None", ")", ":", "total", "=", "float", "(", "self", ".", "total", "(", ")", ")", "smallest_observed_count", "=", "min", "(", "itervalues", "(", "self", ")",...
Return a function that returns the quantile values for this histogram.
[ "Return", "a", "function", "that", "returns", "the", "quantile", "values", "for", "this", "histogram", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/histogram.py#L129-L203
train
205,087
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.get
def get(self, time, interpolate='previous'): """Get the value of the time series, even in-between measured values. """ try: getter = self.getter_functions[interpolate] except KeyError: msg = ( "unknown value '{}' for interpolate, " "valid values are in [{}]" ).format(interpolate, ', '.join(self.getter_functions)) raise ValueError(msg) else: return getter(time)
python
def get(self, time, interpolate='previous'): """Get the value of the time series, even in-between measured values. """ try: getter = self.getter_functions[interpolate] except KeyError: msg = ( "unknown value '{}' for interpolate, " "valid values are in [{}]" ).format(interpolate, ', '.join(self.getter_functions)) raise ValueError(msg) else: return getter(time)
[ "def", "get", "(", "self", ",", "time", ",", "interpolate", "=", "'previous'", ")", ":", "try", ":", "getter", "=", "self", ".", "getter_functions", "[", "interpolate", "]", "except", "KeyError", ":", "msg", "=", "(", "\"unknown value '{}' for interpolate, \""...
Get the value of the time series, even in-between measured values.
[ "Get", "the", "value", "of", "the", "time", "series", "even", "in", "-", "between", "measured", "values", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L154-L167
train
205,088
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.set
def set(self, time, value, compact=False): """Set the value for the time series. If compact is True, only set the value if it's different from what it would be anyway. """ if (len(self) == 0) or (not compact) or \ (compact and self.get(time) != value): self._d[time] = value
python
def set(self, time, value, compact=False): """Set the value for the time series. If compact is True, only set the value if it's different from what it would be anyway. """ if (len(self) == 0) or (not compact) or \ (compact and self.get(time) != value): self._d[time] = value
[ "def", "set", "(", "self", ",", "time", ",", "value", ",", "compact", "=", "False", ")", ":", "if", "(", "len", "(", "self", ")", "==", "0", ")", "or", "(", "not", "compact", ")", "or", "(", "compact", "and", "self", ".", "get", "(", "time", ...
Set the value for the time series. If compact is True, only set the value if it's different from what it would be anyway.
[ "Set", "the", "value", "for", "the", "time", "series", ".", "If", "compact", "is", "True", "only", "set", "the", "value", "if", "it", "s", "different", "from", "what", "it", "would", "be", "anyway", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L197-L204
train
205,089
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.set_interval
def set_interval(self, start, end, value, compact=False): """Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway. """ # for each interval to render for i, (s, e, v) in enumerate(self.iterperiods(start, end)): # look at all intervals included in the current interval # (always at least 1) if i == 0: # if the first, set initial value to new value of range self.set(s, value, compact) else: # otherwise, remove intermediate key del self[s] # finish by setting the end of the interval to the previous value self.set(end, v, compact)
python
def set_interval(self, start, end, value, compact=False): """Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway. """ # for each interval to render for i, (s, e, v) in enumerate(self.iterperiods(start, end)): # look at all intervals included in the current interval # (always at least 1) if i == 0: # if the first, set initial value to new value of range self.set(s, value, compact) else: # otherwise, remove intermediate key del self[s] # finish by setting the end of the interval to the previous value self.set(end, v, compact)
[ "def", "set_interval", "(", "self", ",", "start", ",", "end", ",", "value", ",", "compact", "=", "False", ")", ":", "# for each interval to render", "for", "i", ",", "(", "s", ",", "e", ",", "v", ")", "in", "enumerate", "(", "self", ".", "iterperiods",...
Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway.
[ "Set", "the", "value", "for", "the", "time", "series", "on", "an", "interval", ".", "If", "compact", "is", "True", "only", "set", "the", "value", "if", "it", "s", "different", "from", "what", "it", "would", "be", "anyway", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L206-L224
train
205,090
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.exists
def exists(self): """returns False when the timeseries has a None value, True otherwise""" result = TimeSeries(default=False if self.default is None else True) for t, v in self: result[t] = False if v is None else True return result
python
def exists(self): """returns False when the timeseries has a None value, True otherwise""" result = TimeSeries(default=False if self.default is None else True) for t, v in self: result[t] = False if v is None else True return result
[ "def", "exists", "(", "self", ")", ":", "result", "=", "TimeSeries", "(", "default", "=", "False", "if", "self", ".", "default", "is", "None", "else", "True", ")", "for", "t", ",", "v", "in", "self", ":", "result", "[", "t", "]", "=", "False", "i...
returns False when the timeseries has a None value, True otherwise
[ "returns", "False", "when", "the", "timeseries", "has", "a", "None", "value", "True", "otherwise" ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L244-L250
train
205,091
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.iterintervals
def iterintervals(self, n=2): """Iterate over groups of `n` consecutive measurement points in the time series. """ # tee the original iterator into n identical iterators streams = tee(iter(self), n) # advance the "cursor" on each iterator by an increasing # offset, e.g. if n=3: # # [a, b, c, d, e, f, ..., w, x, y, z] # first cursor --> * # second cursor --> * # third cursor --> * for stream_index, stream in enumerate(streams): for i in range(stream_index): next(stream) # now, zip the offset streams back together to yield tuples, # in the n=3 example it would yield: # (a, b, c), (b, c, d), ..., (w, x, y), (x, y, z) for intervals in zip(*streams): yield intervals
python
def iterintervals(self, n=2): """Iterate over groups of `n` consecutive measurement points in the time series. """ # tee the original iterator into n identical iterators streams = tee(iter(self), n) # advance the "cursor" on each iterator by an increasing # offset, e.g. if n=3: # # [a, b, c, d, e, f, ..., w, x, y, z] # first cursor --> * # second cursor --> * # third cursor --> * for stream_index, stream in enumerate(streams): for i in range(stream_index): next(stream) # now, zip the offset streams back together to yield tuples, # in the n=3 example it would yield: # (a, b, c), (b, c, d), ..., (w, x, y), (x, y, z) for intervals in zip(*streams): yield intervals
[ "def", "iterintervals", "(", "self", ",", "n", "=", "2", ")", ":", "# tee the original iterator into n identical iterators", "streams", "=", "tee", "(", "iter", "(", "self", ")", ",", "n", ")", "# advance the \"cursor\" on each iterator by an increasing", "# offset, e.g...
Iterate over groups of `n` consecutive measurement points in the time series.
[ "Iterate", "over", "groups", "of", "n", "consecutive", "measurement", "points", "in", "the", "time", "series", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L285-L308
train
205,092
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.sample
def sample(self, sampling_period, start=None, end=None, interpolate='previous'): """Sampling at regular time periods. """ start, end, mask = self._check_boundaries(start, end) sampling_period = \ self._check_regularization(start, end, sampling_period) result = [] current_time = start while current_time <= end: value = self.get(current_time, interpolate=interpolate) result.append((current_time, value)) current_time += sampling_period return result
python
def sample(self, sampling_period, start=None, end=None, interpolate='previous'): """Sampling at regular time periods. """ start, end, mask = self._check_boundaries(start, end) sampling_period = \ self._check_regularization(start, end, sampling_period) result = [] current_time = start while current_time <= end: value = self.get(current_time, interpolate=interpolate) result.append((current_time, value)) current_time += sampling_period return result
[ "def", "sample", "(", "self", ",", "sampling_period", ",", "start", "=", "None", ",", "end", "=", "None", ",", "interpolate", "=", "'previous'", ")", ":", "start", ",", "end", ",", "mask", "=", "self", ".", "_check_boundaries", "(", "start", ",", "end"...
Sampling at regular time periods.
[ "Sampling", "at", "regular", "time", "periods", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L417-L433
train
205,093
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.moving_average
def moving_average(self, sampling_period, window_size=None, start=None, end=None, placement='center', pandas=False): """Averaging over regular intervals """ start, end, mask = self._check_boundaries(start, end) # default to sampling_period if not given if window_size is None: window_size = sampling_period sampling_period = \ self._check_regularization(start, end, sampling_period) # convert to datetime if the times are datetimes full_window = window_size * 1. # convert to float if int or do nothing half_window = full_window / 2. # divide by 2 if (isinstance(start, datetime.datetime) and not isinstance(full_window, datetime.timedelta)): half_window = datetime.timedelta(seconds=half_window) full_window = datetime.timedelta(seconds=full_window) result = [] current_time = start while current_time <= end: if placement == 'center': window_start = current_time - half_window window_end = current_time + half_window elif placement == 'left': window_start = current_time window_end = current_time + full_window elif placement == 'right': window_start = current_time - full_window window_end = current_time else: msg = 'unknown placement "{}"'.format(placement) raise ValueError(msg) # calculate mean over window and add (t, v) tuple to list try: mean = self.mean(window_start, window_end) except TypeError as e: if 'NoneType' in str(e): mean = None else: raise e result.append((current_time, mean)) current_time += sampling_period # convert to pandas Series if pandas=True if pandas: try: import pandas as pd except ImportError: msg = "can't have pandas=True if pandas is not installed" raise ImportError(msg) result = pd.Series( [v for t, v in result], index=[t for t, v in result], ) return result
python
def moving_average(self, sampling_period, window_size=None, start=None, end=None, placement='center', pandas=False): """Averaging over regular intervals """ start, end, mask = self._check_boundaries(start, end) # default to sampling_period if not given if window_size is None: window_size = sampling_period sampling_period = \ self._check_regularization(start, end, sampling_period) # convert to datetime if the times are datetimes full_window = window_size * 1. # convert to float if int or do nothing half_window = full_window / 2. # divide by 2 if (isinstance(start, datetime.datetime) and not isinstance(full_window, datetime.timedelta)): half_window = datetime.timedelta(seconds=half_window) full_window = datetime.timedelta(seconds=full_window) result = [] current_time = start while current_time <= end: if placement == 'center': window_start = current_time - half_window window_end = current_time + half_window elif placement == 'left': window_start = current_time window_end = current_time + full_window elif placement == 'right': window_start = current_time - full_window window_end = current_time else: msg = 'unknown placement "{}"'.format(placement) raise ValueError(msg) # calculate mean over window and add (t, v) tuple to list try: mean = self.mean(window_start, window_end) except TypeError as e: if 'NoneType' in str(e): mean = None else: raise e result.append((current_time, mean)) current_time += sampling_period # convert to pandas Series if pandas=True if pandas: try: import pandas as pd except ImportError: msg = "can't have pandas=True if pandas is not installed" raise ImportError(msg) result = pd.Series( [v for t, v in result], index=[t for t, v in result], ) return result
[ "def", "moving_average", "(", "self", ",", "sampling_period", ",", "window_size", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "placement", "=", "'center'", ",", "pandas", "=", "False", ")", ":", "start", ",", "end", ",", "mask...
Averaging over regular intervals
[ "Averaging", "over", "regular", "intervals" ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L435-L502
train
205,094
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.mean
def mean(self, start=None, end=None, mask=None): """This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy. """ return self.distribution(start=start, end=end, mask=mask).mean()
python
def mean(self, start=None, end=None, mask=None): """This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy. """ return self.distribution(start=start, end=end, mask=mask).mean()
[ "def", "mean", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "mask", "=", "None", ")", ":", "return", "self", ".", "distribution", "(", "start", "=", "start", ",", "end", "=", "end", ",", "mask", "=", "mask", ")", ".", "...
This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy.
[ "This", "calculated", "the", "average", "value", "of", "the", "time", "series", "over", "the", "given", "time", "range", "from", "start", "to", "end", "when", "mask", "is", "truthy", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L546-L551
train
205,095
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.distribution
def distribution(self, start=None, end=None, normalized=True, mask=None): """Calculate the distribution of values over the given time range from `start` to `end`. Args: start (orderable, optional): The lower time bound of when to calculate the distribution. By default, the first time point will be used. end (orderable, optional): The upper time bound of when to calculate the distribution. By default, the last time point will be used. normalized (bool): If True, distribution will sum to one. If False and the time values of the TimeSeries are datetimes, the units will be seconds. mask (:obj:`TimeSeries`, optional): A domain on which to calculate the distribution. Returns: :obj:`Histogram` with the results. """ start, end, mask = self._check_boundaries(start, end, mask=mask) counter = histogram.Histogram() for start, end, _ in mask.iterperiods(value=True): for t0, t1, value in self.iterperiods(start, end): duration = utils.duration_to_number( t1 - t0, units='seconds', ) try: counter[value] += duration except histogram.UnorderableElements as e: counter = histogram.Histogram.from_dict( dict(counter), key=hash) counter[value] += duration # divide by total duration if result needs to be normalized if normalized: return counter.normalized() else: return counter
python
def distribution(self, start=None, end=None, normalized=True, mask=None): """Calculate the distribution of values over the given time range from `start` to `end`. Args: start (orderable, optional): The lower time bound of when to calculate the distribution. By default, the first time point will be used. end (orderable, optional): The upper time bound of when to calculate the distribution. By default, the last time point will be used. normalized (bool): If True, distribution will sum to one. If False and the time values of the TimeSeries are datetimes, the units will be seconds. mask (:obj:`TimeSeries`, optional): A domain on which to calculate the distribution. Returns: :obj:`Histogram` with the results. """ start, end, mask = self._check_boundaries(start, end, mask=mask) counter = histogram.Histogram() for start, end, _ in mask.iterperiods(value=True): for t0, t1, value in self.iterperiods(start, end): duration = utils.duration_to_number( t1 - t0, units='seconds', ) try: counter[value] += duration except histogram.UnorderableElements as e: counter = histogram.Histogram.from_dict( dict(counter), key=hash) counter[value] += duration # divide by total duration if result needs to be normalized if normalized: return counter.normalized() else: return counter
[ "def", "distribution", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "normalized", "=", "True", ",", "mask", "=", "None", ")", ":", "start", ",", "end", ",", "mask", "=", "self", ".", "_check_boundaries", "(", "start", ",", ...
Calculate the distribution of values over the given time range from `start` to `end`. Args: start (orderable, optional): The lower time bound of when to calculate the distribution. By default, the first time point will be used. end (orderable, optional): The upper time bound of when to calculate the distribution. By default, the last time point will be used. normalized (bool): If True, distribution will sum to one. If False and the time values of the TimeSeries are datetimes, the units will be seconds. mask (:obj:`TimeSeries`, optional): A domain on which to calculate the distribution. Returns: :obj:`Histogram` with the results.
[ "Calculate", "the", "distribution", "of", "values", "over", "the", "given", "time", "range", "from", "start", "to", "end", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L553-L601
train
205,096
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.n_points
def n_points(self, start=-inf, end=+inf, mask=None, include_start=True, include_end=False, normalized=False): """Calculate the number of points over the given time range from `start` to `end`. Args: start (orderable, optional): The lower time bound of when to calculate the distribution. By default, start is -infinity. end (orderable, optional): The upper time bound of when to calculate the distribution. By default, the end is +infinity. mask (:obj:`TimeSeries`, optional): A domain on which to calculate the distribution. Returns: `int` with the result """ # just go ahead and return 0 if we already know it regarless # of boundaries if not self.n_measurements(): return 0 start, end, mask = self._check_boundaries(start, end, mask=mask) count = 0 for start, end, _ in mask.iterperiods(value=True): if include_end: end_count = self._d.bisect_right(end) else: end_count = self._d.bisect_left(end) if include_start: start_count = self._d.bisect_left(start) else: start_count = self._d.bisect_right(start) count += (end_count - start_count) if normalized: count /= float(self.n_measurements()) return count
python
def n_points(self, start=-inf, end=+inf, mask=None, include_start=True, include_end=False, normalized=False): """Calculate the number of points over the given time range from `start` to `end`. Args: start (orderable, optional): The lower time bound of when to calculate the distribution. By default, start is -infinity. end (orderable, optional): The upper time bound of when to calculate the distribution. By default, the end is +infinity. mask (:obj:`TimeSeries`, optional): A domain on which to calculate the distribution. Returns: `int` with the result """ # just go ahead and return 0 if we already know it regarless # of boundaries if not self.n_measurements(): return 0 start, end, mask = self._check_boundaries(start, end, mask=mask) count = 0 for start, end, _ in mask.iterperiods(value=True): if include_end: end_count = self._d.bisect_right(end) else: end_count = self._d.bisect_left(end) if include_start: start_count = self._d.bisect_left(start) else: start_count = self._d.bisect_right(start) count += (end_count - start_count) if normalized: count /= float(self.n_measurements()) return count
[ "def", "n_points", "(", "self", ",", "start", "=", "-", "inf", ",", "end", "=", "+", "inf", ",", "mask", "=", "None", ",", "include_start", "=", "True", ",", "include_end", "=", "False", ",", "normalized", "=", "False", ")", ":", "# just go ahead and r...
Calculate the number of points over the given time range from `start` to `end`. Args: start (orderable, optional): The lower time bound of when to calculate the distribution. By default, start is -infinity. end (orderable, optional): The upper time bound of when to calculate the distribution. By default, the end is +infinity. mask (:obj:`TimeSeries`, optional): A domain on which to calculate the distribution. Returns: `int` with the result
[ "Calculate", "the", "number", "of", "points", "over", "the", "given", "time", "range", "from", "start", "to", "end", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L603-L651
train
205,097
datascopeanalytics/traces
traces/timeseries.py
TimeSeries._check_time_series
def _check_time_series(self, other): """Function used to check the type of the argument and raise an informative error message if it's not a TimeSeries. """ if not isinstance(other, TimeSeries): msg = "unsupported operand types(s) for +: %s and %s" % \ (type(self), type(other)) raise TypeError(msg)
python
def _check_time_series(self, other): """Function used to check the type of the argument and raise an informative error message if it's not a TimeSeries. """ if not isinstance(other, TimeSeries): msg = "unsupported operand types(s) for +: %s and %s" % \ (type(self), type(other)) raise TypeError(msg)
[ "def", "_check_time_series", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "TimeSeries", ")", ":", "msg", "=", "\"unsupported operand types(s) for +: %s and %s\"", "%", "(", "type", "(", "self", ")", ",", "type", "(", "ot...
Function used to check the type of the argument and raise an informative error message if it's not a TimeSeries.
[ "Function", "used", "to", "check", "the", "type", "of", "the", "argument", "and", "raise", "an", "informative", "error", "message", "if", "it", "s", "not", "a", "TimeSeries", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L653-L661
train
205,098
datascopeanalytics/traces
traces/timeseries.py
TimeSeries.operation
def operation(self, other, function, **kwargs): """Calculate "elementwise" operation either between this TimeSeries and another one, i.e. operation(t) = function(self(t), other(t)) or between this timeseries and a constant: operation(t) = function(self(t), other) If it's another time series, the measurement times in the resulting TimeSeries will be the union of the sets of measurement times of the input time series. If it's a constant, the measurement times will not change. """ result = TimeSeries(**kwargs) if isinstance(other, TimeSeries): for time, value in self: result[time] = function(value, other[time]) for time, value in other: result[time] = function(self[time], value) else: for time, value in self: result[time] = function(value, other) return result
python
def operation(self, other, function, **kwargs): """Calculate "elementwise" operation either between this TimeSeries and another one, i.e. operation(t) = function(self(t), other(t)) or between this timeseries and a constant: operation(t) = function(self(t), other) If it's another time series, the measurement times in the resulting TimeSeries will be the union of the sets of measurement times of the input time series. If it's a constant, the measurement times will not change. """ result = TimeSeries(**kwargs) if isinstance(other, TimeSeries): for time, value in self: result[time] = function(value, other[time]) for time, value in other: result[time] = function(self[time], value) else: for time, value in self: result[time] = function(value, other) return result
[ "def", "operation", "(", "self", ",", "other", ",", "function", ",", "*", "*", "kwargs", ")", ":", "result", "=", "TimeSeries", "(", "*", "*", "kwargs", ")", "if", "isinstance", "(", "other", ",", "TimeSeries", ")", ":", "for", "time", ",", "value", ...
Calculate "elementwise" operation either between this TimeSeries and another one, i.e. operation(t) = function(self(t), other(t)) or between this timeseries and a constant: operation(t) = function(self(t), other) If it's another time series, the measurement times in the resulting TimeSeries will be the union of the sets of measurement times of the input time series. If it's a constant, the measurement times will not change.
[ "Calculate", "elementwise", "operation", "either", "between", "this", "TimeSeries", "and", "another", "one", "i", ".", "e", "." ]
420611151a05fea88a07bc5200fefffdc37cc95b
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L803-L828
train
205,099