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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
tmbo/questionary | questionary/prompts/confirm.py | confirm | def confirm(message: Text,
default: bool = True,
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Prompt the user to confirm or reject.
This question type can be used to prompt the user for a confirmation
of a yes-or-no question. If the user just hits enter, the default
value will be returned.
Args:
message: Question text
default: Default value will be returned if the user just hits
enter.
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`).
"""
merged_style = merge_styles([DEFAULT_STYLE, style])
status = {'answer': None}
def get_prompt_tokens():
tokens = []
tokens.append(("class:qmark", qmark))
tokens.append(("class:question", ' {} '.format(message)))
if status['answer'] is not None:
answer = ' {}'.format(YES if status['answer'] else NO)
tokens.append(("class:answer", answer))
else:
instruction = ' {}'.format(YES_OR_NO if default else NO_OR_YES)
tokens.append(("class:instruction", instruction))
return to_formatted_text(tokens)
bindings = KeyBindings()
@bindings.add(Keys.ControlQ, eager=True)
@bindings.add(Keys.ControlC, eager=True)
def _(event):
event.app.exit(exception=KeyboardInterrupt, style='class:aborting')
@bindings.add('n')
@bindings.add('N')
def key_n(event):
status['answer'] = False
event.app.exit(result=False)
@bindings.add('y')
@bindings.add('Y')
def key_y(event):
status['answer'] = True
event.app.exit(result=True)
@bindings.add(Keys.ControlM, eager=True)
def set_answer(event):
status['answer'] = default
event.app.exit(result=default)
@bindings.add(Keys.Any)
def other(event):
"""Disallow inserting other text."""
pass
return Question(PromptSession(get_prompt_tokens,
key_bindings=bindings,
style=merged_style,
**kwargs).app) | python | def confirm(message: Text,
default: bool = True,
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Prompt the user to confirm or reject.
This question type can be used to prompt the user for a confirmation
of a yes-or-no question. If the user just hits enter, the default
value will be returned.
Args:
message: Question text
default: Default value will be returned if the user just hits
enter.
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`).
"""
merged_style = merge_styles([DEFAULT_STYLE, style])
status = {'answer': None}
def get_prompt_tokens():
tokens = []
tokens.append(("class:qmark", qmark))
tokens.append(("class:question", ' {} '.format(message)))
if status['answer'] is not None:
answer = ' {}'.format(YES if status['answer'] else NO)
tokens.append(("class:answer", answer))
else:
instruction = ' {}'.format(YES_OR_NO if default else NO_OR_YES)
tokens.append(("class:instruction", instruction))
return to_formatted_text(tokens)
bindings = KeyBindings()
@bindings.add(Keys.ControlQ, eager=True)
@bindings.add(Keys.ControlC, eager=True)
def _(event):
event.app.exit(exception=KeyboardInterrupt, style='class:aborting')
@bindings.add('n')
@bindings.add('N')
def key_n(event):
status['answer'] = False
event.app.exit(result=False)
@bindings.add('y')
@bindings.add('Y')
def key_y(event):
status['answer'] = True
event.app.exit(result=True)
@bindings.add(Keys.ControlM, eager=True)
def set_answer(event):
status['answer'] = default
event.app.exit(result=default)
@bindings.add(Keys.Any)
def other(event):
"""Disallow inserting other text."""
pass
return Question(PromptSession(get_prompt_tokens,
key_bindings=bindings,
style=merged_style,
**kwargs).app) | [
"def",
"confirm",
"(",
"message",
":",
"Text",
",",
"default",
":",
"bool",
"=",
"True",
",",
"qmark",
":",
"Text",
"=",
"DEFAULT_QUESTION_PREFIX",
",",
"style",
":",
"Optional",
"[",
"Style",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")... | Prompt the user to confirm or reject.
This question type can be used to prompt the user for a confirmation
of a yes-or-no question. If the user just hits enter, the default
value will be returned.
Args:
message: Question text
default: Default value will be returned if the user just hits
enter.
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`). | [
"Prompt",
"the",
"user",
"to",
"confirm",
"or",
"reject",
"."
] | 3dbaa569a0d252404d547360bee495294bbd620d | https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/confirm.py#L16-L94 | train | 212,500 |
tmbo/questionary | questionary/prompts/rawselect.py | rawselect | def rawselect(message: Text,
choices: List[Union[Text, Choice, Dict[Text, Any]]],
default: Optional[Text] = None,
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Ask the user to select one item from a list of choices using shortcuts.
The user can only select one option.
Args:
message: Question text
choices: Items shown in the selection, this can contain `Choice` or
or `Separator` objects or simple items as strings. Passing
`Choice` objects, allows you to configure the item more
(e.g. preselecting it or disabeling it).
default: Default return value (single value).
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`).
"""
return select.select(message, choices, default, qmark, style,
use_shortcuts=True,
**kwargs) | python | def rawselect(message: Text,
choices: List[Union[Text, Choice, Dict[Text, Any]]],
default: Optional[Text] = None,
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Ask the user to select one item from a list of choices using shortcuts.
The user can only select one option.
Args:
message: Question text
choices: Items shown in the selection, this can contain `Choice` or
or `Separator` objects or simple items as strings. Passing
`Choice` objects, allows you to configure the item more
(e.g. preselecting it or disabeling it).
default: Default return value (single value).
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`).
"""
return select.select(message, choices, default, qmark, style,
use_shortcuts=True,
**kwargs) | [
"def",
"rawselect",
"(",
"message",
":",
"Text",
",",
"choices",
":",
"List",
"[",
"Union",
"[",
"Text",
",",
"Choice",
",",
"Dict",
"[",
"Text",
",",
"Any",
"]",
"]",
"]",
",",
"default",
":",
"Optional",
"[",
"Text",
"]",
"=",
"None",
",",
"qma... | Ask the user to select one item from a list of choices using shortcuts.
The user can only select one option.
Args:
message: Question text
choices: Items shown in the selection, this can contain `Choice` or
or `Separator` objects or simple items as strings. Passing
`Choice` objects, allows you to configure the item more
(e.g. preselecting it or disabeling it).
default: Default return value (single value).
qmark: Question prefix displayed in front of the question.
By default this is a `?`
style: A custom color and style for the question parts. You can
configure colors as well as font types for different elements.
Returns:
Question: Question instance, ready to be prompted (using `.ask()`). | [
"Ask",
"the",
"user",
"to",
"select",
"one",
"item",
"from",
"a",
"list",
"of",
"choices",
"using",
"shortcuts",
"."
] | 3dbaa569a0d252404d547360bee495294bbd620d | https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/rawselect.py#L12-L43 | train | 212,501 |
r4fek/django-cassandra-engine | django_cassandra_engine/base/introspection.py | CassandraDatabaseIntrospection._discover_models | def _discover_models(self):
"""
Return a dict containing a list of cassandra.cqlengine.Model classes
within installed App.
"""
apps = get_installed_apps()
connection = self.connection.connection.alias
keyspace = self.connection.connection.keyspace
for app in apps:
self._cql_models[app.__name__] = get_cql_models(
app, connection=connection, keyspace=keyspace) | python | def _discover_models(self):
"""
Return a dict containing a list of cassandra.cqlengine.Model classes
within installed App.
"""
apps = get_installed_apps()
connection = self.connection.connection.alias
keyspace = self.connection.connection.keyspace
for app in apps:
self._cql_models[app.__name__] = get_cql_models(
app, connection=connection, keyspace=keyspace) | [
"def",
"_discover_models",
"(",
"self",
")",
":",
"apps",
"=",
"get_installed_apps",
"(",
")",
"connection",
"=",
"self",
".",
"connection",
".",
"connection",
".",
"alias",
"keyspace",
"=",
"self",
".",
"connection",
".",
"connection",
".",
"keyspace",
"for... | Return a dict containing a list of cassandra.cqlengine.Model classes
within installed App. | [
"Return",
"a",
"dict",
"containing",
"a",
"list",
"of",
"cassandra",
".",
"cqlengine",
".",
"Model",
"classes",
"within",
"installed",
"App",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/introspection.py#L20-L32 | train | 212,502 |
r4fek/django-cassandra-engine | django_cassandra_engine/base/introspection.py | CassandraDatabaseIntrospection.django_table_names | def django_table_names(self, only_existing=False, **kwargs):
"""
Returns a list of all table names that have associated cqlengine models
and are present in settings.INSTALLED_APPS.
"""
all_models = list(chain.from_iterable(self.cql_models.values()))
tables = [model.column_family_name(include_keyspace=False)
for model in all_models]
return tables | python | def django_table_names(self, only_existing=False, **kwargs):
"""
Returns a list of all table names that have associated cqlengine models
and are present in settings.INSTALLED_APPS.
"""
all_models = list(chain.from_iterable(self.cql_models.values()))
tables = [model.column_family_name(include_keyspace=False)
for model in all_models]
return tables | [
"def",
"django_table_names",
"(",
"self",
",",
"only_existing",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"all_models",
"=",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
"self",
".",
"cql_models",
".",
"values",
"(",
")",
")",
")",
"tables",
... | Returns a list of all table names that have associated cqlengine models
and are present in settings.INSTALLED_APPS. | [
"Returns",
"a",
"list",
"of",
"all",
"table",
"names",
"that",
"have",
"associated",
"cqlengine",
"models",
"and",
"are",
"present",
"in",
"settings",
".",
"INSTALLED_APPS",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/introspection.py#L41-L51 | train | 212,503 |
r4fek/django-cassandra-engine | django_cassandra_engine/base/introspection.py | CassandraDatabaseIntrospection.table_names | def table_names(self, cursor=None, **kwargs):
"""
Returns all table names in current keyspace
"""
# Avoid migration code being executed
if cursor:
return []
connection = self.connection.connection
keyspace_name = connection.keyspace
if not connection.cluster.schema_metadata_enabled and \
keyspace_name not in connection.cluster.metadata.keyspaces:
connection.cluster.refresh_schema_metadata()
keyspace = connection.cluster.metadata.keyspaces[keyspace_name]
return keyspace.tables | python | def table_names(self, cursor=None, **kwargs):
"""
Returns all table names in current keyspace
"""
# Avoid migration code being executed
if cursor:
return []
connection = self.connection.connection
keyspace_name = connection.keyspace
if not connection.cluster.schema_metadata_enabled and \
keyspace_name not in connection.cluster.metadata.keyspaces:
connection.cluster.refresh_schema_metadata()
keyspace = connection.cluster.metadata.keyspaces[keyspace_name]
return keyspace.tables | [
"def",
"table_names",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Avoid migration code being executed",
"if",
"cursor",
":",
"return",
"[",
"]",
"connection",
"=",
"self",
".",
"connection",
".",
"connection",
"keyspace_name"... | Returns all table names in current keyspace | [
"Returns",
"all",
"table",
"names",
"in",
"current",
"keyspace"
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/introspection.py#L53-L68 | train | 212,504 |
r4fek/django-cassandra-engine | django_cassandra_engine/base/creation.py | CassandraDatabaseCreation.set_models_keyspace | def set_models_keyspace(self, keyspace):
"""Set keyspace for all connection models"""
for models in self.connection.introspection.cql_models.values():
for model in models:
model.__keyspace__ = keyspace | python | def set_models_keyspace(self, keyspace):
"""Set keyspace for all connection models"""
for models in self.connection.introspection.cql_models.values():
for model in models:
model.__keyspace__ = keyspace | [
"def",
"set_models_keyspace",
"(",
"self",
",",
"keyspace",
")",
":",
"for",
"models",
"in",
"self",
".",
"connection",
".",
"introspection",
".",
"cql_models",
".",
"values",
"(",
")",
":",
"for",
"model",
"in",
"models",
":",
"model",
".",
"__keyspace__"... | Set keyspace for all connection models | [
"Set",
"keyspace",
"for",
"all",
"connection",
"models"
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/creation.py#L90-L95 | train | 212,505 |
r4fek/django-cassandra-engine | django_cassandra_engine/management/commands/sync_cassandra.py | Command._import_management | def _import_management():
"""
Import the 'management' module within each installed app, to register
dispatcher events.
"""
from importlib import import_module
for app_name in settings.INSTALLED_APPS:
try:
import_module('.management', app_name)
except SystemError:
# We get SystemError if INSTALLED_APPS contains the
# name of a class rather than a module
pass
except ImportError as exc:
# This is slightly hackish. We want to ignore ImportErrors
# if the "management" module itself is missing -- but we don't
# want to ignore the exception if the management module exists
# but raises an ImportError for some reason. The only way we
# can do this is to check the text of the exception. Note that
# we're a bit broad in how we check the text, because different
# Python implementations may not use the same text.
# CPython uses the text "No module named management"
# PyPy uses "No module named myproject.myapp.management"
msg = exc.args[0]
if not msg.startswith('No module named') \
or 'management' not in msg:
raise | python | def _import_management():
"""
Import the 'management' module within each installed app, to register
dispatcher events.
"""
from importlib import import_module
for app_name in settings.INSTALLED_APPS:
try:
import_module('.management', app_name)
except SystemError:
# We get SystemError if INSTALLED_APPS contains the
# name of a class rather than a module
pass
except ImportError as exc:
# This is slightly hackish. We want to ignore ImportErrors
# if the "management" module itself is missing -- but we don't
# want to ignore the exception if the management module exists
# but raises an ImportError for some reason. The only way we
# can do this is to check the text of the exception. Note that
# we're a bit broad in how we check the text, because different
# Python implementations may not use the same text.
# CPython uses the text "No module named management"
# PyPy uses "No module named myproject.myapp.management"
msg = exc.args[0]
if not msg.startswith('No module named') \
or 'management' not in msg:
raise | [
"def",
"_import_management",
"(",
")",
":",
"from",
"importlib",
"import",
"import_module",
"for",
"app_name",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"try",
":",
"import_module",
"(",
"'.management'",
",",
"app_name",
")",
"except",
"SystemError",
":",
"#... | Import the 'management' module within each installed app, to register
dispatcher events. | [
"Import",
"the",
"management",
"module",
"within",
"each",
"installed",
"app",
"to",
"register",
"dispatcher",
"events",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/management/commands/sync_cassandra.py#L23-L51 | train | 212,506 |
r4fek/django-cassandra-engine | django_cassandra_engine/utils.py | get_installed_apps | def get_installed_apps():
"""
Return list of all installed apps
"""
if django.VERSION >= (1, 7):
from django.apps import apps
return [a.models_module for a in apps.get_app_configs()
if a.models_module is not None]
else:
from django.db import models
return models.get_apps() | python | def get_installed_apps():
"""
Return list of all installed apps
"""
if django.VERSION >= (1, 7):
from django.apps import apps
return [a.models_module for a in apps.get_app_configs()
if a.models_module is not None]
else:
from django.db import models
return models.get_apps() | [
"def",
"get_installed_apps",
"(",
")",
":",
"if",
"django",
".",
"VERSION",
">=",
"(",
"1",
",",
"7",
")",
":",
"from",
"django",
".",
"apps",
"import",
"apps",
"return",
"[",
"a",
".",
"models_module",
"for",
"a",
"in",
"apps",
".",
"get_app_configs",... | Return list of all installed apps | [
"Return",
"list",
"of",
"all",
"installed",
"apps"
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/utils.py#L57-L67 | train | 212,507 |
r4fek/django-cassandra-engine | django_cassandra_engine/management/commands/makemigrations.py | Command.handle | def handle(self, *args, **options):
"""
Pretend django_cassandra_engine to be dummy database backend
with no support for migrations.
"""
self._change_cassandra_engine_name('django.db.backends.dummy')
try:
super(Command, self).handle(*args, **options)
finally:
self._change_cassandra_engine_name('django_cassandra_engine') | python | def handle(self, *args, **options):
"""
Pretend django_cassandra_engine to be dummy database backend
with no support for migrations.
"""
self._change_cassandra_engine_name('django.db.backends.dummy')
try:
super(Command, self).handle(*args, **options)
finally:
self._change_cassandra_engine_name('django_cassandra_engine') | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"_change_cassandra_engine_name",
"(",
"'django.db.backends.dummy'",
")",
"try",
":",
"super",
"(",
"Command",
",",
"self",
")",
".",
"handle",
"(",
"*",
"arg... | Pretend django_cassandra_engine to be dummy database backend
with no support for migrations. | [
"Pretend",
"django_cassandra_engine",
"to",
"be",
"dummy",
"database",
"backend",
"with",
"no",
"support",
"for",
"migrations",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/management/commands/makemigrations.py#L15-L24 | train | 212,508 |
r4fek/django-cassandra-engine | django_cassandra_engine/base/operations.py | CassandraDatabaseOperations.sql_flush | def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Truncate all existing tables in current keyspace.
:returns: an empty list
"""
for table in tables:
qs = "TRUNCATE {}".format(table)
self.connection.connection.execute(qs)
return [] | python | def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Truncate all existing tables in current keyspace.
:returns: an empty list
"""
for table in tables:
qs = "TRUNCATE {}".format(table)
self.connection.connection.execute(qs)
return [] | [
"def",
"sql_flush",
"(",
"self",
",",
"style",
",",
"tables",
",",
"sequences",
",",
"allow_cascade",
"=",
"False",
")",
":",
"for",
"table",
"in",
"tables",
":",
"qs",
"=",
"\"TRUNCATE {}\"",
".",
"format",
"(",
"table",
")",
"self",
".",
"connection",
... | Truncate all existing tables in current keyspace.
:returns: an empty list | [
"Truncate",
"all",
"existing",
"tables",
"in",
"current",
"keyspace",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/operations.py#L36-L47 | train | 212,509 |
r4fek/django-cassandra-engine | django_cassandra_engine/models/__init__.py | DjangoCassandraOptions.add_field | def add_field(self, field, **kwargs):
"""Add each field as a private field."""
getattr(self, self._private_fields_name).append(field)
self._expire_cache(reverse=True)
self._expire_cache(reverse=False) | python | def add_field(self, field, **kwargs):
"""Add each field as a private field."""
getattr(self, self._private_fields_name).append(field)
self._expire_cache(reverse=True)
self._expire_cache(reverse=False) | [
"def",
"add_field",
"(",
"self",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"getattr",
"(",
"self",
",",
"self",
".",
"_private_fields_name",
")",
".",
"append",
"(",
"field",
")",
"self",
".",
"_expire_cache",
"(",
"reverse",
"=",
"True",
")",
... | Add each field as a private field. | [
"Add",
"each",
"field",
"as",
"a",
"private",
"field",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L80-L84 | train | 212,510 |
r4fek/django-cassandra-engine | django_cassandra_engine/models/__init__.py | DjangoCassandraOptions._give_columns_django_field_attributes | def _give_columns_django_field_attributes(self):
"""
Add Django Field attributes to each cqlengine.Column instance.
So that the Django Options class may interact with it as if it were
a Django Field.
"""
methods_to_add = (
django_field_methods.value_from_object,
django_field_methods.value_to_string,
django_field_methods.get_attname,
django_field_methods.get_cache_name,
django_field_methods.pre_save,
django_field_methods.get_prep_value,
django_field_methods.get_choices,
django_field_methods.get_choices_default,
django_field_methods.save_form_data,
django_field_methods.formfield,
django_field_methods.get_db_prep_value,
django_field_methods.get_db_prep_save,
django_field_methods.db_type_suffix,
django_field_methods.select_format,
django_field_methods.get_internal_type,
django_field_methods.get_attname_column,
django_field_methods.check,
django_field_methods._check_field_name,
django_field_methods._check_db_index,
django_field_methods.deconstruct,
django_field_methods.run_validators,
django_field_methods.clean,
django_field_methods.get_db_converters,
django_field_methods.get_prep_lookup,
django_field_methods.get_db_prep_lookup,
django_field_methods.get_filter_kwargs_for_object,
django_field_methods.set_attributes_from_name,
django_field_methods.db_parameters,
django_field_methods.get_pk_value_on_save,
django_field_methods.get_col,
)
for name, cql_column in six.iteritems(self._defined_columns):
self._set_column_django_attributes(cql_column=cql_column, name=name)
for method in methods_to_add:
try:
method_name = method.func_name
except AttributeError:
# python 3
method_name = method.__name__
new_method = six.create_bound_method(method, cql_column)
setattr(cql_column, method_name, new_method) | python | def _give_columns_django_field_attributes(self):
"""
Add Django Field attributes to each cqlengine.Column instance.
So that the Django Options class may interact with it as if it were
a Django Field.
"""
methods_to_add = (
django_field_methods.value_from_object,
django_field_methods.value_to_string,
django_field_methods.get_attname,
django_field_methods.get_cache_name,
django_field_methods.pre_save,
django_field_methods.get_prep_value,
django_field_methods.get_choices,
django_field_methods.get_choices_default,
django_field_methods.save_form_data,
django_field_methods.formfield,
django_field_methods.get_db_prep_value,
django_field_methods.get_db_prep_save,
django_field_methods.db_type_suffix,
django_field_methods.select_format,
django_field_methods.get_internal_type,
django_field_methods.get_attname_column,
django_field_methods.check,
django_field_methods._check_field_name,
django_field_methods._check_db_index,
django_field_methods.deconstruct,
django_field_methods.run_validators,
django_field_methods.clean,
django_field_methods.get_db_converters,
django_field_methods.get_prep_lookup,
django_field_methods.get_db_prep_lookup,
django_field_methods.get_filter_kwargs_for_object,
django_field_methods.set_attributes_from_name,
django_field_methods.db_parameters,
django_field_methods.get_pk_value_on_save,
django_field_methods.get_col,
)
for name, cql_column in six.iteritems(self._defined_columns):
self._set_column_django_attributes(cql_column=cql_column, name=name)
for method in methods_to_add:
try:
method_name = method.func_name
except AttributeError:
# python 3
method_name = method.__name__
new_method = six.create_bound_method(method, cql_column)
setattr(cql_column, method_name, new_method) | [
"def",
"_give_columns_django_field_attributes",
"(",
"self",
")",
":",
"methods_to_add",
"=",
"(",
"django_field_methods",
".",
"value_from_object",
",",
"django_field_methods",
".",
"value_to_string",
",",
"django_field_methods",
".",
"get_attname",
",",
"django_field_meth... | Add Django Field attributes to each cqlengine.Column instance.
So that the Django Options class may interact with it as if it were
a Django Field. | [
"Add",
"Django",
"Field",
"attributes",
"to",
"each",
"cqlengine",
".",
"Column",
"instance",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L130-L179 | train | 212,511 |
r4fek/django-cassandra-engine | django_cassandra_engine/models/__init__.py | DjangoCassandraModel._get_column | def _get_column(cls, name):
"""
Based on cqlengine.models.BaseModel._get_column.
But to work with 'pk'
"""
if name == 'pk':
return cls._meta.get_field(cls._meta.pk.name)
return cls._columns[name] | python | def _get_column(cls, name):
"""
Based on cqlengine.models.BaseModel._get_column.
But to work with 'pk'
"""
if name == 'pk':
return cls._meta.get_field(cls._meta.pk.name)
return cls._columns[name] | [
"def",
"_get_column",
"(",
"cls",
",",
"name",
")",
":",
"if",
"name",
"==",
"'pk'",
":",
"return",
"cls",
".",
"_meta",
".",
"get_field",
"(",
"cls",
".",
"_meta",
".",
"pk",
".",
"name",
")",
"return",
"cls",
".",
"_columns",
"[",
"name",
"]"
] | Based on cqlengine.models.BaseModel._get_column.
But to work with 'pk' | [
"Based",
"on",
"cqlengine",
".",
"models",
".",
"BaseModel",
".",
"_get_column",
"."
] | b43f8fddd4bba143f03f73f8bbfc09e6b32c699b | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L833-L841 | train | 212,512 |
grantmcconnaughey/django-avatar | avatar/views.py | _get_next | def _get_next(request):
"""
The part that's the least straightforward about views in this module is
how they determine their redirects after they have finished computation.
In short, they will try and determine the next place to go in the
following order:
1. If there is a variable named ``next`` in the *POST* parameters, the
view will redirect to that variable's value.
2. If there is a variable named ``next`` in the *GET* parameters,
the view will redirect to that variable's value.
3. If Django can determine the previous page from the HTTP headers,
the view will redirect to that previous page.
"""
next = request.POST.get('next', request.GET.get('next',
request.META.get('HTTP_REFERER', None)))
if not next:
next = request.path
return next | python | def _get_next(request):
"""
The part that's the least straightforward about views in this module is
how they determine their redirects after they have finished computation.
In short, they will try and determine the next place to go in the
following order:
1. If there is a variable named ``next`` in the *POST* parameters, the
view will redirect to that variable's value.
2. If there is a variable named ``next`` in the *GET* parameters,
the view will redirect to that variable's value.
3. If Django can determine the previous page from the HTTP headers,
the view will redirect to that previous page.
"""
next = request.POST.get('next', request.GET.get('next',
request.META.get('HTTP_REFERER', None)))
if not next:
next = request.path
return next | [
"def",
"_get_next",
"(",
"request",
")",
":",
"next",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'next'",
",",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_REFERER'",
",",
"None",
")",
"... | The part that's the least straightforward about views in this module is
how they determine their redirects after they have finished computation.
In short, they will try and determine the next place to go in the
following order:
1. If there is a variable named ``next`` in the *POST* parameters, the
view will redirect to that variable's value.
2. If there is a variable named ``next`` in the *GET* parameters,
the view will redirect to that variable's value.
3. If Django can determine the previous page from the HTTP headers,
the view will redirect to that previous page. | [
"The",
"part",
"that",
"s",
"the",
"least",
"straightforward",
"about",
"views",
"in",
"this",
"module",
"is",
"how",
"they",
"determine",
"their",
"redirects",
"after",
"they",
"have",
"finished",
"computation",
"."
] | 182e7aa641c70dae1eed3ae2ff1e7d057ec6103f | https://github.com/grantmcconnaughey/django-avatar/blob/182e7aa641c70dae1eed3ae2ff1e7d057ec6103f/avatar/views.py#L16-L35 | train | 212,513 |
grantmcconnaughey/django-avatar | avatar/utils.py | get_cache_key | def get_cache_key(user_or_username, size, prefix):
"""
Returns a cache key consisten of a username and image size.
"""
if isinstance(user_or_username, get_user_model()):
user_or_username = get_username(user_or_username)
key = six.u('%s_%s_%s') % (prefix, user_or_username, size)
return six.u('%s_%s') % (slugify(key)[:100],
hashlib.md5(force_bytes(key)).hexdigest()) | python | def get_cache_key(user_or_username, size, prefix):
"""
Returns a cache key consisten of a username and image size.
"""
if isinstance(user_or_username, get_user_model()):
user_or_username = get_username(user_or_username)
key = six.u('%s_%s_%s') % (prefix, user_or_username, size)
return six.u('%s_%s') % (slugify(key)[:100],
hashlib.md5(force_bytes(key)).hexdigest()) | [
"def",
"get_cache_key",
"(",
"user_or_username",
",",
"size",
",",
"prefix",
")",
":",
"if",
"isinstance",
"(",
"user_or_username",
",",
"get_user_model",
"(",
")",
")",
":",
"user_or_username",
"=",
"get_username",
"(",
"user_or_username",
")",
"key",
"=",
"s... | Returns a cache key consisten of a username and image size. | [
"Returns",
"a",
"cache",
"key",
"consisten",
"of",
"a",
"username",
"and",
"image",
"size",
"."
] | 182e7aa641c70dae1eed3ae2ff1e7d057ec6103f | https://github.com/grantmcconnaughey/django-avatar/blob/182e7aa641c70dae1eed3ae2ff1e7d057ec6103f/avatar/utils.py#L33-L41 | train | 212,514 |
grantmcconnaughey/django-avatar | avatar/utils.py | cache_result | def cache_result(default_size=settings.AVATAR_DEFAULT_SIZE):
"""
Decorator to cache the result of functions that take a ``user`` and a
``size`` value.
"""
if not settings.AVATAR_CACHE_ENABLED:
def decorator(func):
return func
return decorator
def decorator(func):
def cached_func(user, size=None, **kwargs):
prefix = func.__name__
cached_funcs.add(prefix)
key = get_cache_key(user, size or default_size, prefix=prefix)
result = cache.get(key)
if result is None:
result = func(user, size or default_size, **kwargs)
cache_set(key, result)
return result
return cached_func
return decorator | python | def cache_result(default_size=settings.AVATAR_DEFAULT_SIZE):
"""
Decorator to cache the result of functions that take a ``user`` and a
``size`` value.
"""
if not settings.AVATAR_CACHE_ENABLED:
def decorator(func):
return func
return decorator
def decorator(func):
def cached_func(user, size=None, **kwargs):
prefix = func.__name__
cached_funcs.add(prefix)
key = get_cache_key(user, size or default_size, prefix=prefix)
result = cache.get(key)
if result is None:
result = func(user, size or default_size, **kwargs)
cache_set(key, result)
return result
return cached_func
return decorator | [
"def",
"cache_result",
"(",
"default_size",
"=",
"settings",
".",
"AVATAR_DEFAULT_SIZE",
")",
":",
"if",
"not",
"settings",
".",
"AVATAR_CACHE_ENABLED",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"return",
"func",
"return",
"decorator",
"def",
"decorator",
... | Decorator to cache the result of functions that take a ``user`` and a
``size`` value. | [
"Decorator",
"to",
"cache",
"the",
"result",
"of",
"functions",
"that",
"take",
"a",
"user",
"and",
"a",
"size",
"value",
"."
] | 182e7aa641c70dae1eed3ae2ff1e7d057ec6103f | https://github.com/grantmcconnaughey/django-avatar/blob/182e7aa641c70dae1eed3ae2ff1e7d057ec6103f/avatar/utils.py#L49-L70 | train | 212,515 |
grantmcconnaughey/django-avatar | avatar/utils.py | invalidate_cache | def invalidate_cache(user, size=None):
"""
Function to be called when saving or changing an user's avatars.
"""
sizes = set(settings.AVATAR_AUTO_GENERATE_SIZES)
if size is not None:
sizes.add(size)
for prefix in cached_funcs:
for size in sizes:
cache.delete(get_cache_key(user, size, prefix)) | python | def invalidate_cache(user, size=None):
"""
Function to be called when saving or changing an user's avatars.
"""
sizes = set(settings.AVATAR_AUTO_GENERATE_SIZES)
if size is not None:
sizes.add(size)
for prefix in cached_funcs:
for size in sizes:
cache.delete(get_cache_key(user, size, prefix)) | [
"def",
"invalidate_cache",
"(",
"user",
",",
"size",
"=",
"None",
")",
":",
"sizes",
"=",
"set",
"(",
"settings",
".",
"AVATAR_AUTO_GENERATE_SIZES",
")",
"if",
"size",
"is",
"not",
"None",
":",
"sizes",
".",
"add",
"(",
"size",
")",
"for",
"prefix",
"i... | Function to be called when saving or changing an user's avatars. | [
"Function",
"to",
"be",
"called",
"when",
"saving",
"or",
"changing",
"an",
"user",
"s",
"avatars",
"."
] | 182e7aa641c70dae1eed3ae2ff1e7d057ec6103f | https://github.com/grantmcconnaughey/django-avatar/blob/182e7aa641c70dae1eed3ae2ff1e7d057ec6103f/avatar/utils.py#L73-L82 | train | 212,516 |
plaid/plaid-python | plaid/api/sandbox.py | PublicToken.create | def create(self,
institution_id,
initial_products,
_options=None,
webhook=None,
transactions__start_date=None,
transactions__end_date=None,
):
'''
Generate a public token for sandbox testing.
:param str institution_id:
:param [str] initial_products:
:param str webhook:
'''
options = _options or {}
if webhook is not None:
options['webhook'] = webhook
transaction_options = {}
transaction_options.update(options.get('transactions', {}))
if transactions__start_date is not None:
transaction_options['start_date'] = transactions__start_date
if transactions__end_date is not None:
transaction_options['end_date'] = transactions__end_date
if transaction_options:
options['transactions'] = transaction_options
return self.client.post_public_key('/sandbox/public_token/create', {
'institution_id': institution_id,
'initial_products': initial_products,
'options': options,
}) | python | def create(self,
institution_id,
initial_products,
_options=None,
webhook=None,
transactions__start_date=None,
transactions__end_date=None,
):
'''
Generate a public token for sandbox testing.
:param str institution_id:
:param [str] initial_products:
:param str webhook:
'''
options = _options or {}
if webhook is not None:
options['webhook'] = webhook
transaction_options = {}
transaction_options.update(options.get('transactions', {}))
if transactions__start_date is not None:
transaction_options['start_date'] = transactions__start_date
if transactions__end_date is not None:
transaction_options['end_date'] = transactions__end_date
if transaction_options:
options['transactions'] = transaction_options
return self.client.post_public_key('/sandbox/public_token/create', {
'institution_id': institution_id,
'initial_products': initial_products,
'options': options,
}) | [
"def",
"create",
"(",
"self",
",",
"institution_id",
",",
"initial_products",
",",
"_options",
"=",
"None",
",",
"webhook",
"=",
"None",
",",
"transactions__start_date",
"=",
"None",
",",
"transactions__end_date",
"=",
"None",
",",
")",
":",
"options",
"=",
... | Generate a public token for sandbox testing.
:param str institution_id:
:param [str] initial_products:
:param str webhook: | [
"Generate",
"a",
"public",
"token",
"for",
"sandbox",
"testing",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/sandbox.py#L33-L68 | train | 212,517 |
plaid/plaid-python | plaid/errors.py | PlaidError.from_response | def from_response(response):
'''
Create an error of the right class from an API response.
:param response dict Response JSON
'''
cls = PLAID_ERROR_TYPE_MAP.get(response['error_type'], PlaidError)
return cls(response['error_message'],
response['error_type'],
response['error_code'],
response['display_message'],
response['request_id'],
response.get('causes')) | python | def from_response(response):
'''
Create an error of the right class from an API response.
:param response dict Response JSON
'''
cls = PLAID_ERROR_TYPE_MAP.get(response['error_type'], PlaidError)
return cls(response['error_message'],
response['error_type'],
response['error_code'],
response['display_message'],
response['request_id'],
response.get('causes')) | [
"def",
"from_response",
"(",
"response",
")",
":",
"cls",
"=",
"PLAID_ERROR_TYPE_MAP",
".",
"get",
"(",
"response",
"[",
"'error_type'",
"]",
",",
"PlaidError",
")",
"return",
"cls",
"(",
"response",
"[",
"'error_message'",
"]",
",",
"response",
"[",
"'error... | Create an error of the right class from an API response.
:param response dict Response JSON | [
"Create",
"an",
"error",
"of",
"the",
"right",
"class",
"from",
"an",
"API",
"response",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/errors.py#L76-L88 | train | 212,518 |
plaid/plaid-python | plaid/api/assets.py | AssetReport.create | def create(self,
access_tokens,
days_requested,
options=None):
'''
Create an asset report.
:param [str] access_tokens: A list of access tokens, one token for
each Item to be included in the Asset
Report.
:param int days_requested: Days of transaction history requested
to be included in the Asset Report.
:param dict options: An optional dictionary. For more
information on the options object, see
the documentation site listed above.
'''
options = options or {}
return self.client.post('/asset_report/create', {
'access_tokens': access_tokens,
'days_requested': days_requested,
'options': options,
}) | python | def create(self,
access_tokens,
days_requested,
options=None):
'''
Create an asset report.
:param [str] access_tokens: A list of access tokens, one token for
each Item to be included in the Asset
Report.
:param int days_requested: Days of transaction history requested
to be included in the Asset Report.
:param dict options: An optional dictionary. For more
information on the options object, see
the documentation site listed above.
'''
options = options or {}
return self.client.post('/asset_report/create', {
'access_tokens': access_tokens,
'days_requested': days_requested,
'options': options,
}) | [
"def",
"create",
"(",
"self",
",",
"access_tokens",
",",
"days_requested",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"return",
"self",
".",
"client",
".",
"post",
"(",
"'/asset_report/create'",
",",
"{",
"'access_tok... | Create an asset report.
:param [str] access_tokens: A list of access tokens, one token for
each Item to be included in the Asset
Report.
:param int days_requested: Days of transaction history requested
to be included in the Asset Report.
:param dict options: An optional dictionary. For more
information on the options object, see
the documentation site listed above. | [
"Create",
"an",
"asset",
"report",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/assets.py#L12-L34 | train | 212,519 |
plaid/plaid-python | plaid/api/assets.py | AssetReport.refresh | def refresh(self,
asset_report_token,
days_requested,
options=None):
'''
Create a new, refreshed asset report based on an existing asset report.
:param str asset_report_token: The existing Asset Report's asset
report token.
:param int days_requested: Days of transaction history
requested to be included in the
Asset Report.
:param dict options: An optional dictionary. This is the
same object used in `create`.
'''
options = options or {}
return self.client.post('/asset_report/refresh', {
'asset_report_token': asset_report_token,
'days_requested': days_requested,
'options': options,
}) | python | def refresh(self,
asset_report_token,
days_requested,
options=None):
'''
Create a new, refreshed asset report based on an existing asset report.
:param str asset_report_token: The existing Asset Report's asset
report token.
:param int days_requested: Days of transaction history
requested to be included in the
Asset Report.
:param dict options: An optional dictionary. This is the
same object used in `create`.
'''
options = options or {}
return self.client.post('/asset_report/refresh', {
'asset_report_token': asset_report_token,
'days_requested': days_requested,
'options': options,
}) | [
"def",
"refresh",
"(",
"self",
",",
"asset_report_token",
",",
"days_requested",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"return",
"self",
".",
"client",
".",
"post",
"(",
"'/asset_report/refresh'",
",",
"{",
"'ass... | Create a new, refreshed asset report based on an existing asset report.
:param str asset_report_token: The existing Asset Report's asset
report token.
:param int days_requested: Days of transaction history
requested to be included in the
Asset Report.
:param dict options: An optional dictionary. This is the
same object used in `create`. | [
"Create",
"a",
"new",
"refreshed",
"asset",
"report",
"based",
"on",
"an",
"existing",
"asset",
"report",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/assets.py#L53-L74 | train | 212,520 |
plaid/plaid-python | plaid/api/assets.py | AssetReport.get | def get(self,
asset_report_token,
include_insights=False):
'''
Retrieves an asset report.
:param str asset_report_token: The asset report token for the
asset report you created.
:param bool include_insights: An optional boolean specifying
whether we should retrieve the
report as an Asset Report with
Insights. For more, see
https://plaid.com/docs/#retrieve-json-report-request.
'''
return self.client.post('/asset_report/get', {
'asset_report_token': asset_report_token,
'include_insights': include_insights,
}) | python | def get(self,
asset_report_token,
include_insights=False):
'''
Retrieves an asset report.
:param str asset_report_token: The asset report token for the
asset report you created.
:param bool include_insights: An optional boolean specifying
whether we should retrieve the
report as an Asset Report with
Insights. For more, see
https://plaid.com/docs/#retrieve-json-report-request.
'''
return self.client.post('/asset_report/get', {
'asset_report_token': asset_report_token,
'include_insights': include_insights,
}) | [
"def",
"get",
"(",
"self",
",",
"asset_report_token",
",",
"include_insights",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"post",
"(",
"'/asset_report/get'",
",",
"{",
"'asset_report_token'",
":",
"asset_report_token",
",",
"'include_insights'",... | Retrieves an asset report.
:param str asset_report_token: The asset report token for the
asset report you created.
:param bool include_insights: An optional boolean specifying
whether we should retrieve the
report as an Asset Report with
Insights. For more, see
https://plaid.com/docs/#retrieve-json-report-request. | [
"Retrieves",
"an",
"asset",
"report",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/assets.py#L76-L94 | train | 212,521 |
plaid/plaid-python | plaid/client.py | Client.post | def post(self, path, data, is_json=True):
'''Make a post request with client_id and secret key.'''
post_data = {
'client_id': self.client_id,
'secret': self.secret,
}
post_data.update(data)
return self._post(path, post_data, is_json) | python | def post(self, path, data, is_json=True):
'''Make a post request with client_id and secret key.'''
post_data = {
'client_id': self.client_id,
'secret': self.secret,
}
post_data.update(data)
return self._post(path, post_data, is_json) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
",",
"is_json",
"=",
"True",
")",
":",
"post_data",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'secret'",
":",
"self",
".",
"secret",
",",
"}",
"post_data",
".",
"update",
"(",
... | Make a post request with client_id and secret key. | [
"Make",
"a",
"post",
"request",
"with",
"client_id",
"and",
"secret",
"key",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L80-L87 | train | 212,522 |
plaid/plaid-python | plaid/client.py | Client.post_public | def post_public(self, path, data, is_json=True):
'''Make a post request requiring no auth.'''
return self._post(path, data, is_json) | python | def post_public(self, path, data, is_json=True):
'''Make a post request requiring no auth.'''
return self._post(path, data, is_json) | [
"def",
"post_public",
"(",
"self",
",",
"path",
",",
"data",
",",
"is_json",
"=",
"True",
")",
":",
"return",
"self",
".",
"_post",
"(",
"path",
",",
"data",
",",
"is_json",
")"
] | Make a post request requiring no auth. | [
"Make",
"a",
"post",
"request",
"requiring",
"no",
"auth",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L89-L91 | train | 212,523 |
plaid/plaid-python | plaid/client.py | Client.post_public_key | def post_public_key(self, path, data, is_json=True):
'''Make a post request using a public key.'''
post_data = {
'public_key': self.public_key
}
post_data.update(data)
return self._post(path, post_data, is_json) | python | def post_public_key(self, path, data, is_json=True):
'''Make a post request using a public key.'''
post_data = {
'public_key': self.public_key
}
post_data.update(data)
return self._post(path, post_data, is_json) | [
"def",
"post_public_key",
"(",
"self",
",",
"path",
",",
"data",
",",
"is_json",
"=",
"True",
")",
":",
"post_data",
"=",
"{",
"'public_key'",
":",
"self",
".",
"public_key",
"}",
"post_data",
".",
"update",
"(",
"data",
")",
"return",
"self",
".",
"_p... | Make a post request using a public key. | [
"Make",
"a",
"post",
"request",
"using",
"a",
"public",
"key",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L93-L99 | train | 212,524 |
plaid/plaid-python | plaid/api/institutions.py | Institutions.get_by_id | def get_by_id(self, institution_id, _options=None):
'''
Fetch a single institution by id.
:param str institution_id:
'''
options = _options or {}
return self.client.post_public_key('/institutions/get_by_id', {
'institution_id': institution_id,
'options': options,
}) | python | def get_by_id(self, institution_id, _options=None):
'''
Fetch a single institution by id.
:param str institution_id:
'''
options = _options or {}
return self.client.post_public_key('/institutions/get_by_id', {
'institution_id': institution_id,
'options': options,
}) | [
"def",
"get_by_id",
"(",
"self",
",",
"institution_id",
",",
"_options",
"=",
"None",
")",
":",
"options",
"=",
"_options",
"or",
"{",
"}",
"return",
"self",
".",
"client",
".",
"post_public_key",
"(",
"'/institutions/get_by_id'",
",",
"{",
"'institution_id'",... | Fetch a single institution by id.
:param str institution_id: | [
"Fetch",
"a",
"single",
"institution",
"by",
"id",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/institutions.py#L26-L37 | train | 212,525 |
plaid/plaid-python | plaid/api/institutions.py | Institutions.search | def search(self, query, _options={}, products=None):
'''
Search all institutions by name.
:param str query: Query against the full list of
institutions.
:param [str] products: Filter FIs by available products. Optional.
'''
options = _options or {}
return self.client.post_public_key('/institutions/search', {
'query': query,
'products': products,
'options': options,
}) | python | def search(self, query, _options={}, products=None):
'''
Search all institutions by name.
:param str query: Query against the full list of
institutions.
:param [str] products: Filter FIs by available products. Optional.
'''
options = _options or {}
return self.client.post_public_key('/institutions/search', {
'query': query,
'products': products,
'options': options,
}) | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"_options",
"=",
"{",
"}",
",",
"products",
"=",
"None",
")",
":",
"options",
"=",
"_options",
"or",
"{",
"}",
"return",
"self",
".",
"client",
".",
"post_public_key",
"(",
"'/institutions/search'",
",",
... | Search all institutions by name.
:param str query: Query against the full list of
institutions.
:param [str] products: Filter FIs by available products. Optional. | [
"Search",
"all",
"institutions",
"by",
"name",
"."
] | c549c3108790266a3b344c47e0c83fff59146eeb | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/institutions.py#L39-L53 | train | 212,526 |
ynqa/pandavro | pandavro/__init__.py | read_avro | def read_avro(file_path_or_buffer, schema=None, **kwargs):
"""
Avro file reader.
Args:
file_path_or_buffer: Input file path or file-like object.
schema: Avro schema.
**kwargs: Keyword argument to pandas.DataFrame.from_records.
Returns:
Class of pd.DataFrame.
"""
if isinstance(file_path_or_buffer, six.string_types):
with open(file_path_or_buffer, 'rb') as f:
return __file_to_dataframe(f, schema, **kwargs)
else:
return __file_to_dataframe(file_path_or_buffer, schema, **kwargs) | python | def read_avro(file_path_or_buffer, schema=None, **kwargs):
"""
Avro file reader.
Args:
file_path_or_buffer: Input file path or file-like object.
schema: Avro schema.
**kwargs: Keyword argument to pandas.DataFrame.from_records.
Returns:
Class of pd.DataFrame.
"""
if isinstance(file_path_or_buffer, six.string_types):
with open(file_path_or_buffer, 'rb') as f:
return __file_to_dataframe(f, schema, **kwargs)
else:
return __file_to_dataframe(file_path_or_buffer, schema, **kwargs) | [
"def",
"read_avro",
"(",
"file_path_or_buffer",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"file_path_or_buffer",
",",
"six",
".",
"string_types",
")",
":",
"with",
"open",
"(",
"file_path_or_buffer",
",",
"'rb'",... | Avro file reader.
Args:
file_path_or_buffer: Input file path or file-like object.
schema: Avro schema.
**kwargs: Keyword argument to pandas.DataFrame.from_records.
Returns:
Class of pd.DataFrame. | [
"Avro",
"file",
"reader",
"."
] | 9c9528a7bcf616e48b3699249d7457fd7e9b4366 | https://github.com/ynqa/pandavro/blob/9c9528a7bcf616e48b3699249d7457fd7e9b4366/pandavro/__init__.py#L90-L106 | train | 212,527 |
ynqa/pandavro | pandavro/__init__.py | to_avro | def to_avro(file_path_or_buffer, df, schema=None, codec='null', append=False):
"""
Avro file writer.
Args:
file_path_or_buffer:
Output file path or file-like object.
df: pd.DataFrame.
schema: Dict of Avro schema.
If it's set None, inferring schema.
append: Boolean to control if will append to existing file
codec: A string indicating the compression codec to use.
Default is no compression ("null"), other acceptable values are
"snappy" and "deflate". You must have python-snappy installed to use
the snappy codec.
"""
if schema is None:
schema = __schema_infer(df)
open_mode = 'wb' if not append else 'a+b'
if isinstance(file_path_or_buffer, six.string_types):
with open(file_path_or_buffer, open_mode) as f:
fastavro.writer(f, schema=schema,
records=df.to_dict('records'), codec=codec)
else:
fastavro.writer(file_path_or_buffer, schema=schema,
records=df.to_dict('records'), codec=codec) | python | def to_avro(file_path_or_buffer, df, schema=None, codec='null', append=False):
"""
Avro file writer.
Args:
file_path_or_buffer:
Output file path or file-like object.
df: pd.DataFrame.
schema: Dict of Avro schema.
If it's set None, inferring schema.
append: Boolean to control if will append to existing file
codec: A string indicating the compression codec to use.
Default is no compression ("null"), other acceptable values are
"snappy" and "deflate". You must have python-snappy installed to use
the snappy codec.
"""
if schema is None:
schema = __schema_infer(df)
open_mode = 'wb' if not append else 'a+b'
if isinstance(file_path_or_buffer, six.string_types):
with open(file_path_or_buffer, open_mode) as f:
fastavro.writer(f, schema=schema,
records=df.to_dict('records'), codec=codec)
else:
fastavro.writer(file_path_or_buffer, schema=schema,
records=df.to_dict('records'), codec=codec) | [
"def",
"to_avro",
"(",
"file_path_or_buffer",
",",
"df",
",",
"schema",
"=",
"None",
",",
"codec",
"=",
"'null'",
",",
"append",
"=",
"False",
")",
":",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"__schema_infer",
"(",
"df",
")",
"open_mode",
"=... | Avro file writer.
Args:
file_path_or_buffer:
Output file path or file-like object.
df: pd.DataFrame.
schema: Dict of Avro schema.
If it's set None, inferring schema.
append: Boolean to control if will append to existing file
codec: A string indicating the compression codec to use.
Default is no compression ("null"), other acceptable values are
"snappy" and "deflate". You must have python-snappy installed to use
the snappy codec. | [
"Avro",
"file",
"writer",
"."
] | 9c9528a7bcf616e48b3699249d7457fd7e9b4366 | https://github.com/ynqa/pandavro/blob/9c9528a7bcf616e48b3699249d7457fd7e9b4366/pandavro/__init__.py#L126-L154 | train | 212,528 |
CamDavidsonPilon/tdigest | tdigest/tdigest.py | TDigest.update | def update(self, x, w=1):
"""
Update the t-digest with value x and weight w.
"""
self.n += w
if len(self) == 0:
self._add_centroid(Centroid(x, w))
return
S = self._find_closest_centroids(x)
while len(S) != 0 and w > 0:
j = choice(list(range(len(S))))
c_j = S[j]
q = self._compute_centroid_quantile(c_j)
# This filters the out centroids that do not satisfy the second part
# of the definition of S. See original paper by Dunning.
if c_j.count + w > self._threshold(q):
S.pop(j)
continue
delta_w = min(self._threshold(q) - c_j.count, w)
self._update_centroid(c_j, x, delta_w)
w -= delta_w
S.pop(j)
if w > 0:
self._add_centroid(Centroid(x, w))
if len(self) > self.K / self.delta:
self.compress()
return | python | def update(self, x, w=1):
"""
Update the t-digest with value x and weight w.
"""
self.n += w
if len(self) == 0:
self._add_centroid(Centroid(x, w))
return
S = self._find_closest_centroids(x)
while len(S) != 0 and w > 0:
j = choice(list(range(len(S))))
c_j = S[j]
q = self._compute_centroid_quantile(c_j)
# This filters the out centroids that do not satisfy the second part
# of the definition of S. See original paper by Dunning.
if c_j.count + w > self._threshold(q):
S.pop(j)
continue
delta_w = min(self._threshold(q) - c_j.count, w)
self._update_centroid(c_j, x, delta_w)
w -= delta_w
S.pop(j)
if w > 0:
self._add_centroid(Centroid(x, w))
if len(self) > self.K / self.delta:
self.compress()
return | [
"def",
"update",
"(",
"self",
",",
"x",
",",
"w",
"=",
"1",
")",
":",
"self",
".",
"n",
"+=",
"w",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"self",
".",
"_add_centroid",
"(",
"Centroid",
"(",
"x",
",",
"w",
")",
")",
"return",
"S",
"=... | Update the t-digest with value x and weight w. | [
"Update",
"the",
"t",
"-",
"digest",
"with",
"value",
"x",
"and",
"weight",
"w",
"."
] | e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246 | https://github.com/CamDavidsonPilon/tdigest/blob/e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246/tdigest/tdigest.py#L104-L140 | train | 212,529 |
CamDavidsonPilon/tdigest | tdigest/tdigest.py | TDigest.batch_update | def batch_update(self, values, w=1):
"""
Update the t-digest with an iterable of values. This assumes all points have the
same weight.
"""
for x in values:
self.update(x, w)
self.compress()
return | python | def batch_update(self, values, w=1):
"""
Update the t-digest with an iterable of values. This assumes all points have the
same weight.
"""
for x in values:
self.update(x, w)
self.compress()
return | [
"def",
"batch_update",
"(",
"self",
",",
"values",
",",
"w",
"=",
"1",
")",
":",
"for",
"x",
"in",
"values",
":",
"self",
".",
"update",
"(",
"x",
",",
"w",
")",
"self",
".",
"compress",
"(",
")",
"return"
] | Update the t-digest with an iterable of values. This assumes all points have the
same weight. | [
"Update",
"the",
"t",
"-",
"digest",
"with",
"an",
"iterable",
"of",
"values",
".",
"This",
"assumes",
"all",
"points",
"have",
"the",
"same",
"weight",
"."
] | e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246 | https://github.com/CamDavidsonPilon/tdigest/blob/e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246/tdigest/tdigest.py#L142-L150 | train | 212,530 |
CamDavidsonPilon/tdigest | tdigest/tdigest.py | TDigest.trimmed_mean | def trimmed_mean(self, p1, p2):
"""
Computes the mean of the distribution between the two percentiles p1 and p2.
This is a modified algorithm than the one presented in the original t-Digest paper.
"""
if not (p1 < p2):
raise ValueError("p1 must be between 0 and 100 and less than p2.")
min_count = p1 / 100. * self.n
max_count = p2 / 100. * self.n
trimmed_sum = trimmed_count = curr_count = 0
for i, c in enumerate(self.C.values()):
next_count = curr_count + c.count
if next_count <= min_count:
curr_count = next_count
continue
count = c.count
if curr_count < min_count:
count = next_count - min_count
if next_count > max_count:
count -= next_count - max_count
trimmed_sum += count * c.mean
trimmed_count += count
if next_count >= max_count:
break
curr_count = next_count
if trimmed_count == 0:
return 0
return trimmed_sum / trimmed_count | python | def trimmed_mean(self, p1, p2):
"""
Computes the mean of the distribution between the two percentiles p1 and p2.
This is a modified algorithm than the one presented in the original t-Digest paper.
"""
if not (p1 < p2):
raise ValueError("p1 must be between 0 and 100 and less than p2.")
min_count = p1 / 100. * self.n
max_count = p2 / 100. * self.n
trimmed_sum = trimmed_count = curr_count = 0
for i, c in enumerate(self.C.values()):
next_count = curr_count + c.count
if next_count <= min_count:
curr_count = next_count
continue
count = c.count
if curr_count < min_count:
count = next_count - min_count
if next_count > max_count:
count -= next_count - max_count
trimmed_sum += count * c.mean
trimmed_count += count
if next_count >= max_count:
break
curr_count = next_count
if trimmed_count == 0:
return 0
return trimmed_sum / trimmed_count | [
"def",
"trimmed_mean",
"(",
"self",
",",
"p1",
",",
"p2",
")",
":",
"if",
"not",
"(",
"p1",
"<",
"p2",
")",
":",
"raise",
"ValueError",
"(",
"\"p1 must be between 0 and 100 and less than p2.\"",
")",
"min_count",
"=",
"p1",
"/",
"100.",
"*",
"self",
".",
... | Computes the mean of the distribution between the two percentiles p1 and p2.
This is a modified algorithm than the one presented in the original t-Digest paper. | [
"Computes",
"the",
"mean",
"of",
"the",
"distribution",
"between",
"the",
"two",
"percentiles",
"p1",
"and",
"p2",
".",
"This",
"is",
"a",
"modified",
"algorithm",
"than",
"the",
"one",
"presented",
"in",
"the",
"original",
"t",
"-",
"Digest",
"paper",
"."... | e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246 | https://github.com/CamDavidsonPilon/tdigest/blob/e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246/tdigest/tdigest.py#L216-L250 | train | 212,531 |
CamDavidsonPilon/tdigest | tdigest/tdigest.py | TDigest.centroids_to_list | def centroids_to_list(self):
"""
Returns a Python list of the TDigest object's Centroid values.
"""
centroids = []
for key in self.C.keys():
tree_values = self.C.get_value(key)
centroids.append({'m':tree_values.mean, 'c':tree_values.count})
return centroids | python | def centroids_to_list(self):
"""
Returns a Python list of the TDigest object's Centroid values.
"""
centroids = []
for key in self.C.keys():
tree_values = self.C.get_value(key)
centroids.append({'m':tree_values.mean, 'c':tree_values.count})
return centroids | [
"def",
"centroids_to_list",
"(",
"self",
")",
":",
"centroids",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"C",
".",
"keys",
"(",
")",
":",
"tree_values",
"=",
"self",
".",
"C",
".",
"get_value",
"(",
"key",
")",
"centroids",
".",
"append",
"(... | Returns a Python list of the TDigest object's Centroid values. | [
"Returns",
"a",
"Python",
"list",
"of",
"the",
"TDigest",
"object",
"s",
"Centroid",
"values",
"."
] | e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246 | https://github.com/CamDavidsonPilon/tdigest/blob/e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246/tdigest/tdigest.py#L252-L261 | train | 212,532 |
CamDavidsonPilon/tdigest | tdigest/tdigest.py | TDigest.update_from_dict | def update_from_dict(self, dict_values):
"""
Updates TDigest object with dictionary values.
The digest delta and K values are optional if you would like to update them,
but the n value is not required because it is computed from the centroid weights.
For example, you can initalize a new TDigest:
digest = TDigest()
Then load dictionary values into the digest:
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
Or update an existing digest where the centroids will be appropriately merged:
digest = TDigest()
digest.update(1)
digest.update(2)
digest.update(3)
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
Resulting in the digest having merged similar centroids by increasing their weight:
{'K': 25, 'delta': 0.01, 'centroids': [{'c': 2.0, 'm': 1.0}, {'c': 2.0, 'm': 2.0}, {'c': 2.0, 'm': 3.0}], 'n': 6.0}
Alternative you can provide only a list of centroid values with update_centroids_from_list()
"""
self.delta = dict_values.get('delta', self.delta)
self.K = dict_values.get('K', self.K)
self.update_centroids_from_list(dict_values['centroids'])
return self | python | def update_from_dict(self, dict_values):
"""
Updates TDigest object with dictionary values.
The digest delta and K values are optional if you would like to update them,
but the n value is not required because it is computed from the centroid weights.
For example, you can initalize a new TDigest:
digest = TDigest()
Then load dictionary values into the digest:
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
Or update an existing digest where the centroids will be appropriately merged:
digest = TDigest()
digest.update(1)
digest.update(2)
digest.update(3)
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
Resulting in the digest having merged similar centroids by increasing their weight:
{'K': 25, 'delta': 0.01, 'centroids': [{'c': 2.0, 'm': 1.0}, {'c': 2.0, 'm': 2.0}, {'c': 2.0, 'm': 3.0}], 'n': 6.0}
Alternative you can provide only a list of centroid values with update_centroids_from_list()
"""
self.delta = dict_values.get('delta', self.delta)
self.K = dict_values.get('K', self.K)
self.update_centroids_from_list(dict_values['centroids'])
return self | [
"def",
"update_from_dict",
"(",
"self",
",",
"dict_values",
")",
":",
"self",
".",
"delta",
"=",
"dict_values",
".",
"get",
"(",
"'delta'",
",",
"self",
".",
"delta",
")",
"self",
".",
"K",
"=",
"dict_values",
".",
"get",
"(",
"'K'",
",",
"self",
"."... | Updates TDigest object with dictionary values.
The digest delta and K values are optional if you would like to update them,
but the n value is not required because it is computed from the centroid weights.
For example, you can initalize a new TDigest:
digest = TDigest()
Then load dictionary values into the digest:
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
Or update an existing digest where the centroids will be appropriately merged:
digest = TDigest()
digest.update(1)
digest.update(2)
digest.update(3)
digest.update_from_dict({'K': 25, 'delta': 0.01, 'centroids': [{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]})
Resulting in the digest having merged similar centroids by increasing their weight:
{'K': 25, 'delta': 0.01, 'centroids': [{'c': 2.0, 'm': 1.0}, {'c': 2.0, 'm': 2.0}, {'c': 2.0, 'm': 3.0}], 'n': 6.0}
Alternative you can provide only a list of centroid values with update_centroids_from_list() | [
"Updates",
"TDigest",
"object",
"with",
"dictionary",
"values",
"."
] | e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246 | https://github.com/CamDavidsonPilon/tdigest/blob/e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246/tdigest/tdigest.py#L271-L299 | train | 212,533 |
CamDavidsonPilon/tdigest | tdigest/tdigest.py | TDigest.update_centroids_from_list | def update_centroids_from_list(self, list_values):
"""
Add or update Centroids from a Python list.
Any existing centroids in the digest object are appropriately updated.
Example:
digest.update_centroids([{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}])
"""
[self.update(value['m'], value['c']) for value in list_values]
return self | python | def update_centroids_from_list(self, list_values):
"""
Add or update Centroids from a Python list.
Any existing centroids in the digest object are appropriately updated.
Example:
digest.update_centroids([{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}])
"""
[self.update(value['m'], value['c']) for value in list_values]
return self | [
"def",
"update_centroids_from_list",
"(",
"self",
",",
"list_values",
")",
":",
"[",
"self",
".",
"update",
"(",
"value",
"[",
"'m'",
"]",
",",
"value",
"[",
"'c'",
"]",
")",
"for",
"value",
"in",
"list_values",
"]",
"return",
"self"
] | Add or update Centroids from a Python list.
Any existing centroids in the digest object are appropriately updated.
Example:
digest.update_centroids([{'c': 1.0, 'm': 1.0}, {'c': 1.0, 'm': 2.0}, {'c': 1.0, 'm': 3.0}]) | [
"Add",
"or",
"update",
"Centroids",
"from",
"a",
"Python",
"list",
".",
"Any",
"existing",
"centroids",
"in",
"the",
"digest",
"object",
"are",
"appropriately",
"updated",
"."
] | e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246 | https://github.com/CamDavidsonPilon/tdigest/blob/e56db9fd5e6aeb75f3be5f29a62286f4f5fb1246/tdigest/tdigest.py#L301-L311 | train | 212,534 |
GuyAllard/markov_clustering | markov_clustering/modularity.py | is_undirected | def is_undirected(matrix):
"""
Determine if the matrix reprensents a directed graph
:param matrix: The matrix to tested
:returns: boolean
"""
if isspmatrix(matrix):
return sparse_allclose(matrix, matrix.transpose())
return np.allclose(matrix, matrix.T) | python | def is_undirected(matrix):
"""
Determine if the matrix reprensents a directed graph
:param matrix: The matrix to tested
:returns: boolean
"""
if isspmatrix(matrix):
return sparse_allclose(matrix, matrix.transpose())
return np.allclose(matrix, matrix.T) | [
"def",
"is_undirected",
"(",
"matrix",
")",
":",
"if",
"isspmatrix",
"(",
"matrix",
")",
":",
"return",
"sparse_allclose",
"(",
"matrix",
",",
"matrix",
".",
"transpose",
"(",
")",
")",
"return",
"np",
".",
"allclose",
"(",
"matrix",
",",
"matrix",
".",
... | Determine if the matrix reprensents a directed graph
:param matrix: The matrix to tested
:returns: boolean | [
"Determine",
"if",
"the",
"matrix",
"reprensents",
"a",
"directed",
"graph"
] | 28787cf64ef06bf024ff915246008c767ea830cf | https://github.com/GuyAllard/markov_clustering/blob/28787cf64ef06bf024ff915246008c767ea830cf/markov_clustering/modularity.py#L12-L22 | train | 212,535 |
GuyAllard/markov_clustering | markov_clustering/modularity.py | convert_to_adjacency_matrix | def convert_to_adjacency_matrix(matrix):
"""
Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix
"""
for i in range(matrix.shape[0]):
if isspmatrix(matrix):
col = find(matrix[:,i])[2]
else:
col = matrix[:,i].T.tolist()[0]
coeff = max( Fraction(c).limit_denominator().denominator for c in col )
matrix[:,i] *= coeff
return matrix | python | def convert_to_adjacency_matrix(matrix):
"""
Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix
"""
for i in range(matrix.shape[0]):
if isspmatrix(matrix):
col = find(matrix[:,i])[2]
else:
col = matrix[:,i].T.tolist()[0]
coeff = max( Fraction(c).limit_denominator().denominator for c in col )
matrix[:,i] *= coeff
return matrix | [
"def",
"convert_to_adjacency_matrix",
"(",
"matrix",
")",
":",
"for",
"i",
"in",
"range",
"(",
"matrix",
".",
"shape",
"[",
"0",
"]",
")",
":",
"if",
"isspmatrix",
"(",
"matrix",
")",
":",
"col",
"=",
"find",
"(",
"matrix",
"[",
":",
",",
"i",
"]",... | Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix | [
"Converts",
"transition",
"matrix",
"into",
"adjacency",
"matrix"
] | 28787cf64ef06bf024ff915246008c767ea830cf | https://github.com/GuyAllard/markov_clustering/blob/28787cf64ef06bf024ff915246008c767ea830cf/markov_clustering/modularity.py#L25-L42 | train | 212,536 |
GuyAllard/markov_clustering | markov_clustering/modularity.py | modularity | def modularity(matrix, clusters):
"""
Compute the modularity
:param matrix: The adjacency matrix
:param clusters: The clusters returned by get_clusters
:returns: modularity value
"""
matrix = convert_to_adjacency_matrix(matrix)
m = matrix.sum()
if isspmatrix(matrix):
matrix_2 = matrix.tocsr(copy=True)
else :
matrix_2 = matrix
if is_undirected(matrix):
expected = lambda i,j : (( matrix_2[i,:].sum() + matrix[:,i].sum() )*
( matrix[:,j].sum() + matrix_2[j,:].sum() ))
else:
expected = lambda i,j : ( matrix_2[i,:].sum()*matrix[:,j].sum() )
delta = delta_matrix(matrix, clusters)
indices = np.array(delta.nonzero())
Q = sum( matrix[i, j] - expected(i, j)/m for i, j in indices.T )/m
return Q | python | def modularity(matrix, clusters):
"""
Compute the modularity
:param matrix: The adjacency matrix
:param clusters: The clusters returned by get_clusters
:returns: modularity value
"""
matrix = convert_to_adjacency_matrix(matrix)
m = matrix.sum()
if isspmatrix(matrix):
matrix_2 = matrix.tocsr(copy=True)
else :
matrix_2 = matrix
if is_undirected(matrix):
expected = lambda i,j : (( matrix_2[i,:].sum() + matrix[:,i].sum() )*
( matrix[:,j].sum() + matrix_2[j,:].sum() ))
else:
expected = lambda i,j : ( matrix_2[i,:].sum()*matrix[:,j].sum() )
delta = delta_matrix(matrix, clusters)
indices = np.array(delta.nonzero())
Q = sum( matrix[i, j] - expected(i, j)/m for i, j in indices.T )/m
return Q | [
"def",
"modularity",
"(",
"matrix",
",",
"clusters",
")",
":",
"matrix",
"=",
"convert_to_adjacency_matrix",
"(",
"matrix",
")",
"m",
"=",
"matrix",
".",
"sum",
"(",
")",
"if",
"isspmatrix",
"(",
"matrix",
")",
":",
"matrix_2",
"=",
"matrix",
".",
"tocsr... | Compute the modularity
:param matrix: The adjacency matrix
:param clusters: The clusters returned by get_clusters
:returns: modularity value | [
"Compute",
"the",
"modularity"
] | 28787cf64ef06bf024ff915246008c767ea830cf | https://github.com/GuyAllard/markov_clustering/blob/28787cf64ef06bf024ff915246008c767ea830cf/markov_clustering/modularity.py#L66-L93 | train | 212,537 |
GuyAllard/markov_clustering | markov_clustering/mcl.py | sparse_allclose | def sparse_allclose(a, b, rtol=1e-5, atol=1e-8):
"""
Version of np.allclose for use with sparse matrices
"""
c = np.abs(a - b) - rtol * np.abs(b)
# noinspection PyUnresolvedReferences
return c.max() <= atol | python | def sparse_allclose(a, b, rtol=1e-5, atol=1e-8):
"""
Version of np.allclose for use with sparse matrices
"""
c = np.abs(a - b) - rtol * np.abs(b)
# noinspection PyUnresolvedReferences
return c.max() <= atol | [
"def",
"sparse_allclose",
"(",
"a",
",",
"b",
",",
"rtol",
"=",
"1e-5",
",",
"atol",
"=",
"1e-8",
")",
":",
"c",
"=",
"np",
".",
"abs",
"(",
"a",
"-",
"b",
")",
"-",
"rtol",
"*",
"np",
".",
"abs",
"(",
"b",
")",
"# noinspection PyUnresolvedRefere... | Version of np.allclose for use with sparse matrices | [
"Version",
"of",
"np",
".",
"allclose",
"for",
"use",
"with",
"sparse",
"matrices"
] | 28787cf64ef06bf024ff915246008c767ea830cf | https://github.com/GuyAllard/markov_clustering/blob/28787cf64ef06bf024ff915246008c767ea830cf/markov_clustering/mcl.py#L7-L13 | train | 212,538 |
soxofaan/dahuffman | dahuffman/huffmancodec.py | _guess_concat | def _guess_concat(data):
"""
Guess concat function from given data
"""
return {
type(u''): u''.join,
type(b''): concat_bytes,
}.get(type(data), list) | python | def _guess_concat(data):
"""
Guess concat function from given data
"""
return {
type(u''): u''.join,
type(b''): concat_bytes,
}.get(type(data), list) | [
"def",
"_guess_concat",
"(",
"data",
")",
":",
"return",
"{",
"type",
"(",
"u''",
")",
":",
"u''",
".",
"join",
",",
"type",
"(",
"b''",
")",
":",
"concat_bytes",
",",
"}",
".",
"get",
"(",
"type",
"(",
"data",
")",
",",
"list",
")"
] | Guess concat function from given data | [
"Guess",
"concat",
"function",
"from",
"given",
"data"
] | e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2 | https://github.com/soxofaan/dahuffman/blob/e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2/dahuffman/huffmancodec.py#L42-L49 | train | 212,539 |
soxofaan/dahuffman | dahuffman/huffmancodec.py | PrefixCodec.print_code_table | def print_code_table(self, out=sys.stdout):
"""
Print code table overview
"""
out.write(u'bits code (value) symbol\n')
for symbol, (bitsize, value) in sorted(self._table.items()):
out.write(u'{b:4d} {c:10} ({v:5d}) {s!r}\n'.format(
b=bitsize, v=value, s=symbol, c=bin(value)[2:].rjust(bitsize, '0')
)) | python | def print_code_table(self, out=sys.stdout):
"""
Print code table overview
"""
out.write(u'bits code (value) symbol\n')
for symbol, (bitsize, value) in sorted(self._table.items()):
out.write(u'{b:4d} {c:10} ({v:5d}) {s!r}\n'.format(
b=bitsize, v=value, s=symbol, c=bin(value)[2:].rjust(bitsize, '0')
)) | [
"def",
"print_code_table",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"out",
".",
"write",
"(",
"u'bits code (value) symbol\\n'",
")",
"for",
"symbol",
",",
"(",
"bitsize",
",",
"value",
")",
"in",
"sorted",
"(",
"self",
".",
"... | Print code table overview | [
"Print",
"code",
"table",
"overview"
] | e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2 | https://github.com/soxofaan/dahuffman/blob/e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2/dahuffman/huffmancodec.py#L82-L90 | train | 212,540 |
soxofaan/dahuffman | dahuffman/huffmancodec.py | PrefixCodec.encode_streaming | def encode_streaming(self, data):
"""
Encode given data in streaming fashion.
:param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)
:return: generator of bytes (single character strings in Python2, ints in Python 3)
"""
# Buffer value and size
buffer = 0
size = 0
for s in data:
b, v = self._table[s]
# Shift new bits in the buffer
buffer = (buffer << b) + v
size += b
while size >= 8:
byte = buffer >> (size - 8)
yield to_byte(byte)
buffer = buffer - (byte << (size - 8))
size -= 8
# Handling of the final sub-byte chunk.
# The end of the encoded bit stream does not align necessarily with byte boundaries,
# so we need an "end of file" indicator symbol (_EOF) to guard against decoding
# the non-data trailing bits of the last byte.
# As an optimization however, while encoding _EOF, it is only necessary to encode up to
# the end of the current byte and cut off there.
# No new byte has to be started for the remainder, saving us one (or more) output bytes.
if size > 0:
b, v = self._table[_EOF]
buffer = (buffer << b) + v
size += b
if size >= 8:
byte = buffer >> (size - 8)
else:
byte = buffer << (8 - size)
yield to_byte(byte) | python | def encode_streaming(self, data):
"""
Encode given data in streaming fashion.
:param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)
:return: generator of bytes (single character strings in Python2, ints in Python 3)
"""
# Buffer value and size
buffer = 0
size = 0
for s in data:
b, v = self._table[s]
# Shift new bits in the buffer
buffer = (buffer << b) + v
size += b
while size >= 8:
byte = buffer >> (size - 8)
yield to_byte(byte)
buffer = buffer - (byte << (size - 8))
size -= 8
# Handling of the final sub-byte chunk.
# The end of the encoded bit stream does not align necessarily with byte boundaries,
# so we need an "end of file" indicator symbol (_EOF) to guard against decoding
# the non-data trailing bits of the last byte.
# As an optimization however, while encoding _EOF, it is only necessary to encode up to
# the end of the current byte and cut off there.
# No new byte has to be started for the remainder, saving us one (or more) output bytes.
if size > 0:
b, v = self._table[_EOF]
buffer = (buffer << b) + v
size += b
if size >= 8:
byte = buffer >> (size - 8)
else:
byte = buffer << (8 - size)
yield to_byte(byte) | [
"def",
"encode_streaming",
"(",
"self",
",",
"data",
")",
":",
"# Buffer value and size",
"buffer",
"=",
"0",
"size",
"=",
"0",
"for",
"s",
"in",
"data",
":",
"b",
",",
"v",
"=",
"self",
".",
"_table",
"[",
"s",
"]",
"# Shift new bits in the buffer",
"bu... | Encode given data in streaming fashion.
:param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)
:return: generator of bytes (single character strings in Python2, ints in Python 3) | [
"Encode",
"given",
"data",
"in",
"streaming",
"fashion",
"."
] | e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2 | https://github.com/soxofaan/dahuffman/blob/e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2/dahuffman/huffmancodec.py#L101-L137 | train | 212,541 |
soxofaan/dahuffman | dahuffman/huffmancodec.py | PrefixCodec.decode | def decode(self, data, as_list=False):
"""
Decode given data.
:param data: sequence of bytes (string, list or generator of bytes)
:param as_list: whether to return as a list instead of
:return:
"""
return self._concat(self.decode_streaming(data)) | python | def decode(self, data, as_list=False):
"""
Decode given data.
:param data: sequence of bytes (string, list or generator of bytes)
:param as_list: whether to return as a list instead of
:return:
"""
return self._concat(self.decode_streaming(data)) | [
"def",
"decode",
"(",
"self",
",",
"data",
",",
"as_list",
"=",
"False",
")",
":",
"return",
"self",
".",
"_concat",
"(",
"self",
".",
"decode_streaming",
"(",
"data",
")",
")"
] | Decode given data.
:param data: sequence of bytes (string, list or generator of bytes)
:param as_list: whether to return as a list instead of
:return: | [
"Decode",
"given",
"data",
"."
] | e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2 | https://github.com/soxofaan/dahuffman/blob/e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2/dahuffman/huffmancodec.py#L139-L147 | train | 212,542 |
soxofaan/dahuffman | dahuffman/huffmancodec.py | PrefixCodec.decode_streaming | def decode_streaming(self, data):
"""
Decode given data in streaming fashion
:param data: sequence of bytes (string, list or generator of bytes)
:return: generator of symbols
"""
# Reverse lookup table: map (bitsize, value) to symbols
lookup = dict(((b, v), s) for (s, (b, v)) in self._table.items())
buffer = 0
size = 0
for byte in data:
for m in [128, 64, 32, 16, 8, 4, 2, 1]:
buffer = (buffer << 1) + bool(from_byte(byte) & m)
size += 1
if (size, buffer) in lookup:
symbol = lookup[size, buffer]
if symbol == _EOF:
return
yield symbol
buffer = 0
size = 0 | python | def decode_streaming(self, data):
"""
Decode given data in streaming fashion
:param data: sequence of bytes (string, list or generator of bytes)
:return: generator of symbols
"""
# Reverse lookup table: map (bitsize, value) to symbols
lookup = dict(((b, v), s) for (s, (b, v)) in self._table.items())
buffer = 0
size = 0
for byte in data:
for m in [128, 64, 32, 16, 8, 4, 2, 1]:
buffer = (buffer << 1) + bool(from_byte(byte) & m)
size += 1
if (size, buffer) in lookup:
symbol = lookup[size, buffer]
if symbol == _EOF:
return
yield symbol
buffer = 0
size = 0 | [
"def",
"decode_streaming",
"(",
"self",
",",
"data",
")",
":",
"# Reverse lookup table: map (bitsize, value) to symbols",
"lookup",
"=",
"dict",
"(",
"(",
"(",
"b",
",",
"v",
")",
",",
"s",
")",
"for",
"(",
"s",
",",
"(",
"b",
",",
"v",
")",
")",
"in",... | Decode given data in streaming fashion
:param data: sequence of bytes (string, list or generator of bytes)
:return: generator of symbols | [
"Decode",
"given",
"data",
"in",
"streaming",
"fashion"
] | e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2 | https://github.com/soxofaan/dahuffman/blob/e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2/dahuffman/huffmancodec.py#L149-L171 | train | 212,543 |
soxofaan/dahuffman | dahuffman/huffmancodec.py | HuffmanCodec.from_data | def from_data(cls, data):
"""
Build Huffman code table from symbol sequence
:param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)
:return: HuffmanCoder
"""
frequencies = collections.Counter(data)
return cls.from_frequencies(frequencies, concat=_guess_concat(data)) | python | def from_data(cls, data):
"""
Build Huffman code table from symbol sequence
:param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)
:return: HuffmanCoder
"""
frequencies = collections.Counter(data)
return cls.from_frequencies(frequencies, concat=_guess_concat(data)) | [
"def",
"from_data",
"(",
"cls",
",",
"data",
")",
":",
"frequencies",
"=",
"collections",
".",
"Counter",
"(",
"data",
")",
"return",
"cls",
".",
"from_frequencies",
"(",
"frequencies",
",",
"concat",
"=",
"_guess_concat",
"(",
"data",
")",
")"
] | Build Huffman code table from symbol sequence
:param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)
:return: HuffmanCoder | [
"Build",
"Huffman",
"code",
"table",
"from",
"symbol",
"sequence"
] | e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2 | https://github.com/soxofaan/dahuffman/blob/e6e1cf6ab3f6cb29f21e642fbcdd63084e5d63c2/dahuffman/huffmancodec.py#L215-L223 | train | 212,544 |
cloudflare/sqlalchemy-clickhouse | connector.py | Cursor._reset_state | def _reset_state(self):
"""Reset state about the previous query in preparation for running another query"""
self._uuid = None
self._columns = None
self._rownumber = 0
# Internal helper state
self._state = self._STATE_NONE
self._data = None
self._columns = None | python | def _reset_state(self):
"""Reset state about the previous query in preparation for running another query"""
self._uuid = None
self._columns = None
self._rownumber = 0
# Internal helper state
self._state = self._STATE_NONE
self._data = None
self._columns = None | [
"def",
"_reset_state",
"(",
"self",
")",
":",
"self",
".",
"_uuid",
"=",
"None",
"self",
".",
"_columns",
"=",
"None",
"self",
".",
"_rownumber",
"=",
"0",
"# Internal helper state",
"self",
".",
"_state",
"=",
"self",
".",
"_STATE_NONE",
"self",
".",
"_... | Reset state about the previous query in preparation for running another query | [
"Reset",
"state",
"about",
"the",
"previous",
"query",
"in",
"preparation",
"for",
"running",
"another",
"query"
] | fc46142445d4510566f6412964df2fb9d2f4bd2e | https://github.com/cloudflare/sqlalchemy-clickhouse/blob/fc46142445d4510566f6412964df2fb9d2f4bd2e/connector.py#L161-L169 | train | 212,545 |
cloudflare/sqlalchemy-clickhouse | connector.py | Cursor.fetchone | def fetchone(self):
"""Fetch the next row of a query result set, returning a single sequence, or ``None`` when
no more data is available. """
if self._state == self._STATE_NONE:
raise Exception("No query yet")
if not self._data:
return None
else:
self._rownumber += 1
return self._data.pop(0) | python | def fetchone(self):
"""Fetch the next row of a query result set, returning a single sequence, or ``None`` when
no more data is available. """
if self._state == self._STATE_NONE:
raise Exception("No query yet")
if not self._data:
return None
else:
self._rownumber += 1
return self._data.pop(0) | [
"def",
"fetchone",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"self",
".",
"_STATE_NONE",
":",
"raise",
"Exception",
"(",
"\"No query yet\"",
")",
"if",
"not",
"self",
".",
"_data",
":",
"return",
"None",
"else",
":",
"self",
".",
"_rown... | Fetch the next row of a query result set, returning a single sequence, or ``None`` when
no more data is available. | [
"Fetch",
"the",
"next",
"row",
"of",
"a",
"query",
"result",
"set",
"returning",
"a",
"single",
"sequence",
"or",
"None",
"when",
"no",
"more",
"data",
"is",
"available",
"."
] | fc46142445d4510566f6412964df2fb9d2f4bd2e | https://github.com/cloudflare/sqlalchemy-clickhouse/blob/fc46142445d4510566f6412964df2fb9d2f4bd2e/connector.py#L249-L258 | train | 212,546 |
cloudflare/sqlalchemy-clickhouse | connector.py | Cursor._process_response | def _process_response(self, response):
""" Update the internal state with the data from the response """
assert self._state == self._STATE_RUNNING, "Should be running if processing response"
cols = None
data = []
for r in response:
if not cols:
cols = [(f, r._fields[f].db_type) for f in r._fields]
data.append([getattr(r, f) for f in r._fields])
self._data = data
self._columns = cols
self._state = self._STATE_FINISHED | python | def _process_response(self, response):
""" Update the internal state with the data from the response """
assert self._state == self._STATE_RUNNING, "Should be running if processing response"
cols = None
data = []
for r in response:
if not cols:
cols = [(f, r._fields[f].db_type) for f in r._fields]
data.append([getattr(r, f) for f in r._fields])
self._data = data
self._columns = cols
self._state = self._STATE_FINISHED | [
"def",
"_process_response",
"(",
"self",
",",
"response",
")",
":",
"assert",
"self",
".",
"_state",
"==",
"self",
".",
"_STATE_RUNNING",
",",
"\"Should be running if processing response\"",
"cols",
"=",
"None",
"data",
"=",
"[",
"]",
"for",
"r",
"in",
"respon... | Update the internal state with the data from the response | [
"Update",
"the",
"internal",
"state",
"with",
"the",
"data",
"from",
"the",
"response"
] | fc46142445d4510566f6412964df2fb9d2f4bd2e | https://github.com/cloudflare/sqlalchemy-clickhouse/blob/fc46142445d4510566f6412964df2fb9d2f4bd2e/connector.py#L350-L361 | train | 212,547 |
ekzhu/SetSimilaritySearch | SetSimilaritySearch/utils.py | _frequency_order_transform | def _frequency_order_transform(sets):
"""Transform tokens to integers according to global frequency order.
This step replaces all original tokens in the sets with integers, and
helps to speed up subsequent prefix filtering and similarity computation.
See Section 4.3.2 in the paper "A Primitive Operator for Similarity Joins
in Data Cleaning" by Chaudhuri et al..
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
Returns:
sets (list): a list of sets, each entry is a sorted Numpy array with
integer tokens replacing the tokens in the original set.
order (dict): a dictionary that maps token to its integer representation
in the frequency order.
"""
logging.debug("Applying frequency order transform on tokens...")
counts = reversed(Counter(token for s in sets for token in s).most_common())
order = dict((token, i) for i, (token, _) in enumerate(counts))
sets = [np.sort([order[token] for token in s]) for s in sets]
logging.debug("Done applying frequency order.")
return sets, order | python | def _frequency_order_transform(sets):
"""Transform tokens to integers according to global frequency order.
This step replaces all original tokens in the sets with integers, and
helps to speed up subsequent prefix filtering and similarity computation.
See Section 4.3.2 in the paper "A Primitive Operator for Similarity Joins
in Data Cleaning" by Chaudhuri et al..
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
Returns:
sets (list): a list of sets, each entry is a sorted Numpy array with
integer tokens replacing the tokens in the original set.
order (dict): a dictionary that maps token to its integer representation
in the frequency order.
"""
logging.debug("Applying frequency order transform on tokens...")
counts = reversed(Counter(token for s in sets for token in s).most_common())
order = dict((token, i) for i, (token, _) in enumerate(counts))
sets = [np.sort([order[token] for token in s]) for s in sets]
logging.debug("Done applying frequency order.")
return sets, order | [
"def",
"_frequency_order_transform",
"(",
"sets",
")",
":",
"logging",
".",
"debug",
"(",
"\"Applying frequency order transform on tokens...\"",
")",
"counts",
"=",
"reversed",
"(",
"Counter",
"(",
"token",
"for",
"s",
"in",
"sets",
"for",
"token",
"in",
"s",
")... | Transform tokens to integers according to global frequency order.
This step replaces all original tokens in the sets with integers, and
helps to speed up subsequent prefix filtering and similarity computation.
See Section 4.3.2 in the paper "A Primitive Operator for Similarity Joins
in Data Cleaning" by Chaudhuri et al..
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
Returns:
sets (list): a list of sets, each entry is a sorted Numpy array with
integer tokens replacing the tokens in the original set.
order (dict): a dictionary that maps token to its integer representation
in the frequency order. | [
"Transform",
"tokens",
"to",
"integers",
"according",
"to",
"global",
"frequency",
"order",
".",
"This",
"step",
"replaces",
"all",
"original",
"tokens",
"in",
"the",
"sets",
"with",
"integers",
"and",
"helps",
"to",
"speed",
"up",
"subsequent",
"prefix",
"fil... | 30188ca0257b644501f4a359172fddb2f89bf568 | https://github.com/ekzhu/SetSimilaritySearch/blob/30188ca0257b644501f4a359172fddb2f89bf568/SetSimilaritySearch/utils.py#L91-L113 | train | 212,548 |
ekzhu/SetSimilaritySearch | SetSimilaritySearch/all_pairs.py | all_pairs | def all_pairs(sets, similarity_func_name="jaccard",
similarity_threshold=0.5):
"""Find all pairs of sets with similarity greater than a threshold.
This is an implementation of the All-Pair-Binary algorithm in the paper
"Scaling Up All Pairs Similarity Search" by Bayardo et al., with
position filter enhancement.
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
similarity_func_name (str): the name of the similarity function used;
this function currently supports `"jaccard"` and `"cosine"`.
similarity_threshold (float): the threshold used, must be a float
between 0 and 1.0.
Returns:
pairs (Iterator[tuple]): an iterator of tuples `(x, y, similarity)`
where `x` and `y` are the indices of sets in the input list `sets`.
"""
if not isinstance(sets, list) or len(sets) == 0:
raise ValueError("Input parameter sets must be a non-empty list.")
if similarity_func_name not in _similarity_funcs:
raise ValueError("Similarity function {} is not supported.".format(
similarity_func_name))
if similarity_threshold < 0 or similarity_threshold > 1.0:
raise ValueError("Similarity threshold must be in the range [0, 1].")
if similarity_func_name not in _symmetric_similarity_funcs:
raise ValueError("The similarity function must be symmetric "
"({})".format(", ".join(_symmetric_similarity_funcs)))
similarity_func = _similarity_funcs[similarity_func_name]
overlap_threshold_func = _overlap_threshold_funcs[similarity_func_name]
position_filter_func = _position_filter_funcs[similarity_func_name]
sets, _ = _frequency_order_transform(sets)
index = defaultdict(list)
logging.debug("Find all pairs with similarities >= {}...".format(
similarity_threshold))
count = 0
for x1 in np.argsort([len(s) for s in sets]):
s1 = sets[x1]
t = overlap_threshold_func(len(s1), similarity_threshold)
prefix_size = len(s1) - t + 1
prefix = s1[:prefix_size]
# Find candidates using tokens in the prefix.
candidates = set([x2 for p1, token in enumerate(prefix)
for x2, p2 in index[token]
if position_filter_func(s1, sets[x2], p1, p2,
similarity_threshold)])
for x2 in candidates:
s2 = sets[x2]
sim = similarity_func(s1, s2)
if sim < similarity_threshold:
continue
# Output reverse-ordered set index pair (larger first).
yield tuple(sorted([x1, x2], reverse=True) + [sim,])
count += 1
# Insert this prefix into index.
for j, token in enumerate(prefix):
index[token].append((x1, j))
logging.debug("{} pairs found.".format(count)) | python | def all_pairs(sets, similarity_func_name="jaccard",
similarity_threshold=0.5):
"""Find all pairs of sets with similarity greater than a threshold.
This is an implementation of the All-Pair-Binary algorithm in the paper
"Scaling Up All Pairs Similarity Search" by Bayardo et al., with
position filter enhancement.
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
similarity_func_name (str): the name of the similarity function used;
this function currently supports `"jaccard"` and `"cosine"`.
similarity_threshold (float): the threshold used, must be a float
between 0 and 1.0.
Returns:
pairs (Iterator[tuple]): an iterator of tuples `(x, y, similarity)`
where `x` and `y` are the indices of sets in the input list `sets`.
"""
if not isinstance(sets, list) or len(sets) == 0:
raise ValueError("Input parameter sets must be a non-empty list.")
if similarity_func_name not in _similarity_funcs:
raise ValueError("Similarity function {} is not supported.".format(
similarity_func_name))
if similarity_threshold < 0 or similarity_threshold > 1.0:
raise ValueError("Similarity threshold must be in the range [0, 1].")
if similarity_func_name not in _symmetric_similarity_funcs:
raise ValueError("The similarity function must be symmetric "
"({})".format(", ".join(_symmetric_similarity_funcs)))
similarity_func = _similarity_funcs[similarity_func_name]
overlap_threshold_func = _overlap_threshold_funcs[similarity_func_name]
position_filter_func = _position_filter_funcs[similarity_func_name]
sets, _ = _frequency_order_transform(sets)
index = defaultdict(list)
logging.debug("Find all pairs with similarities >= {}...".format(
similarity_threshold))
count = 0
for x1 in np.argsort([len(s) for s in sets]):
s1 = sets[x1]
t = overlap_threshold_func(len(s1), similarity_threshold)
prefix_size = len(s1) - t + 1
prefix = s1[:prefix_size]
# Find candidates using tokens in the prefix.
candidates = set([x2 for p1, token in enumerate(prefix)
for x2, p2 in index[token]
if position_filter_func(s1, sets[x2], p1, p2,
similarity_threshold)])
for x2 in candidates:
s2 = sets[x2]
sim = similarity_func(s1, s2)
if sim < similarity_threshold:
continue
# Output reverse-ordered set index pair (larger first).
yield tuple(sorted([x1, x2], reverse=True) + [sim,])
count += 1
# Insert this prefix into index.
for j, token in enumerate(prefix):
index[token].append((x1, j))
logging.debug("{} pairs found.".format(count)) | [
"def",
"all_pairs",
"(",
"sets",
",",
"similarity_func_name",
"=",
"\"jaccard\"",
",",
"similarity_threshold",
"=",
"0.5",
")",
":",
"if",
"not",
"isinstance",
"(",
"sets",
",",
"list",
")",
"or",
"len",
"(",
"sets",
")",
"==",
"0",
":",
"raise",
"ValueE... | Find all pairs of sets with similarity greater than a threshold.
This is an implementation of the All-Pair-Binary algorithm in the paper
"Scaling Up All Pairs Similarity Search" by Bayardo et al., with
position filter enhancement.
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
similarity_func_name (str): the name of the similarity function used;
this function currently supports `"jaccard"` and `"cosine"`.
similarity_threshold (float): the threshold used, must be a float
between 0 and 1.0.
Returns:
pairs (Iterator[tuple]): an iterator of tuples `(x, y, similarity)`
where `x` and `y` are the indices of sets in the input list `sets`. | [
"Find",
"all",
"pairs",
"of",
"sets",
"with",
"similarity",
"greater",
"than",
"a",
"threshold",
".",
"This",
"is",
"an",
"implementation",
"of",
"the",
"All",
"-",
"Pair",
"-",
"Binary",
"algorithm",
"in",
"the",
"paper",
"Scaling",
"Up",
"All",
"Pairs",
... | 30188ca0257b644501f4a359172fddb2f89bf568 | https://github.com/ekzhu/SetSimilaritySearch/blob/30188ca0257b644501f4a359172fddb2f89bf568/SetSimilaritySearch/all_pairs.py#L9-L67 | train | 212,549 |
ekzhu/SetSimilaritySearch | SetSimilaritySearch/search.py | SearchIndex.query | def query(self, s):
"""Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets.
"""
s1 = np.sort([self.order[token] for token in s if token in self.order])
logging.debug("{} original tokens and {} tokens after applying "
"frequency order.".format(len(s), len(s1)))
prefix = self._get_prefix(s1)
candidates = set([i for p1, token in enumerate(prefix)
for i, p2 in self.index[token]
if self.position_filter_func(s1, self.sets[i], p1, p2,
self.similarity_threshold)])
logging.debug("{} candidates found.".format(len(candidates)))
results = deque([])
for i in candidates:
s2 = self.sets[i]
sim = self.similarity_func(s1, s2)
if sim < self.similarity_threshold:
continue
results.append((i, sim))
logging.debug("{} verified sets found.".format(len(results)))
return list(results) | python | def query(self, s):
"""Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets.
"""
s1 = np.sort([self.order[token] for token in s if token in self.order])
logging.debug("{} original tokens and {} tokens after applying "
"frequency order.".format(len(s), len(s1)))
prefix = self._get_prefix(s1)
candidates = set([i for p1, token in enumerate(prefix)
for i, p2 in self.index[token]
if self.position_filter_func(s1, self.sets[i], p1, p2,
self.similarity_threshold)])
logging.debug("{} candidates found.".format(len(candidates)))
results = deque([])
for i in candidates:
s2 = self.sets[i]
sim = self.similarity_func(s1, s2)
if sim < self.similarity_threshold:
continue
results.append((i, sim))
logging.debug("{} verified sets found.".format(len(results)))
return list(results) | [
"def",
"query",
"(",
"self",
",",
"s",
")",
":",
"s1",
"=",
"np",
".",
"sort",
"(",
"[",
"self",
".",
"order",
"[",
"token",
"]",
"for",
"token",
"in",
"s",
"if",
"token",
"in",
"self",
".",
"order",
"]",
")",
"logging",
".",
"debug",
"(",
"\... | Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets. | [
"Query",
"the",
"search",
"index",
"for",
"sets",
"similar",
"to",
"the",
"query",
"set",
"."
] | 30188ca0257b644501f4a359172fddb2f89bf568 | https://github.com/ekzhu/SetSimilaritySearch/blob/30188ca0257b644501f4a359172fddb2f89bf568/SetSimilaritySearch/search.py#L65-L91 | train | 212,550 |
dwavesystems/dimod | dimod/reference/samplers/random_sampler.py | RandomSampler.sample | def sample(self, bqm, num_reads=10):
"""Give random samples for a binary quadratic model.
Variable assignments are chosen by coin flip.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
num_reads (int, optional, default=10):
Number of reads.
Returns:
:obj:`.SampleSet`
"""
values = tuple(bqm.vartype.value)
def _itersample():
for __ in range(num_reads):
sample = {v: choice(values) for v in bqm.linear}
energy = bqm.energy(sample)
yield sample, energy
samples, energies = zip(*_itersample())
return SampleSet.from_samples(samples, bqm.vartype, energies) | python | def sample(self, bqm, num_reads=10):
"""Give random samples for a binary quadratic model.
Variable assignments are chosen by coin flip.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
num_reads (int, optional, default=10):
Number of reads.
Returns:
:obj:`.SampleSet`
"""
values = tuple(bqm.vartype.value)
def _itersample():
for __ in range(num_reads):
sample = {v: choice(values) for v in bqm.linear}
energy = bqm.energy(sample)
yield sample, energy
samples, energies = zip(*_itersample())
return SampleSet.from_samples(samples, bqm.vartype, energies) | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"num_reads",
"=",
"10",
")",
":",
"values",
"=",
"tuple",
"(",
"bqm",
".",
"vartype",
".",
"value",
")",
"def",
"_itersample",
"(",
")",
":",
"for",
"__",
"in",
"range",
"(",
"num_reads",
")",
":",
"... | Give random samples for a binary quadratic model.
Variable assignments are chosen by coin flip.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
num_reads (int, optional, default=10):
Number of reads.
Returns:
:obj:`.SampleSet` | [
"Give",
"random",
"samples",
"for",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/samplers/random_sampler.py#L41-L68 | train | 212,551 |
dwavesystems/dimod | dimod/generators/constraints.py | combinations | def combinations(n, k, strength=1, vartype=BINARY):
r"""Generate a bqm that is minimized when k of n variables are selected.
More fully, we wish to generate a binary quadratic model which is minimized
for each of the k-combinations of its variables.
The energy for the binary quadratic model is given by
:math:`(\sum_{i} x_i - k)^2`.
Args:
n (int/list/set):
If n is an integer, variables are labelled [0, n-1]. If n is list or
set then the variables are labelled accordingly.
k (int):
The generated binary quadratic model will have 0 energy when any k
of the variables are 1.
strength (number, optional, default=1):
The energy of the first excited state of the binary quadratic model.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:obj:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2)
>>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
0.0
>>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
1.0
>>> bqm = dimod.generators.combinations(5, 1)
>>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 0, 4: 0})
0.0
>>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 1, 4: 0})
1.0
>>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2, strength=3.0)
>>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
0.0
>>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
3.0
"""
if isinstance(n, abc.Sized) and isinstance(n, abc.Iterable):
# what we actually want is abc.Collection but that doesn't exist in
# python2
variables = n
else:
try:
variables = range(n)
except TypeError:
raise TypeError('n should be a collection or an integer')
if k > len(variables) or k < 0:
raise ValueError("cannot select k={} from {} variables".format(k, len(variables)))
# (\sum_i x_i - k)^2
# = \sum_i x_i \sum_j x_j - 2k\sum_i x_i + k^2
# = \sum_i,j x_ix_j + (1 - 2k)\sim_i x_i + k^2
lbias = float(strength*(1 - 2*k))
qbias = float(2*strength)
bqm = BinaryQuadraticModel.empty(vartype)
bqm.add_variables_from(((v, lbias) for v in variables), vartype=BINARY)
bqm.add_interactions_from(((u, v, qbias)
for u, v in itertools.combinations(variables, 2)),
vartype=BINARY)
bqm.add_offset(strength*(k**2))
return bqm | python | def combinations(n, k, strength=1, vartype=BINARY):
r"""Generate a bqm that is minimized when k of n variables are selected.
More fully, we wish to generate a binary quadratic model which is minimized
for each of the k-combinations of its variables.
The energy for the binary quadratic model is given by
:math:`(\sum_{i} x_i - k)^2`.
Args:
n (int/list/set):
If n is an integer, variables are labelled [0, n-1]. If n is list or
set then the variables are labelled accordingly.
k (int):
The generated binary quadratic model will have 0 energy when any k
of the variables are 1.
strength (number, optional, default=1):
The energy of the first excited state of the binary quadratic model.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:obj:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2)
>>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
0.0
>>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
1.0
>>> bqm = dimod.generators.combinations(5, 1)
>>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 0, 4: 0})
0.0
>>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 1, 4: 0})
1.0
>>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2, strength=3.0)
>>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
0.0
>>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
3.0
"""
if isinstance(n, abc.Sized) and isinstance(n, abc.Iterable):
# what we actually want is abc.Collection but that doesn't exist in
# python2
variables = n
else:
try:
variables = range(n)
except TypeError:
raise TypeError('n should be a collection or an integer')
if k > len(variables) or k < 0:
raise ValueError("cannot select k={} from {} variables".format(k, len(variables)))
# (\sum_i x_i - k)^2
# = \sum_i x_i \sum_j x_j - 2k\sum_i x_i + k^2
# = \sum_i,j x_ix_j + (1 - 2k)\sim_i x_i + k^2
lbias = float(strength*(1 - 2*k))
qbias = float(2*strength)
bqm = BinaryQuadraticModel.empty(vartype)
bqm.add_variables_from(((v, lbias) for v in variables), vartype=BINARY)
bqm.add_interactions_from(((u, v, qbias)
for u, v in itertools.combinations(variables, 2)),
vartype=BINARY)
bqm.add_offset(strength*(k**2))
return bqm | [
"def",
"combinations",
"(",
"n",
",",
"k",
",",
"strength",
"=",
"1",
",",
"vartype",
"=",
"BINARY",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"abc",
".",
"Sized",
")",
"and",
"isinstance",
"(",
"n",
",",
"abc",
".",
"Iterable",
")",
":",
"# w... | r"""Generate a bqm that is minimized when k of n variables are selected.
More fully, we wish to generate a binary quadratic model which is minimized
for each of the k-combinations of its variables.
The energy for the binary quadratic model is given by
:math:`(\sum_{i} x_i - k)^2`.
Args:
n (int/list/set):
If n is an integer, variables are labelled [0, n-1]. If n is list or
set then the variables are labelled accordingly.
k (int):
The generated binary quadratic model will have 0 energy when any k
of the variables are 1.
strength (number, optional, default=1):
The energy of the first excited state of the binary quadratic model.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:obj:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2)
>>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
0.0
>>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
1.0
>>> bqm = dimod.generators.combinations(5, 1)
>>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 0, 4: 0})
0.0
>>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 1, 4: 0})
1.0
>>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2, strength=3.0)
>>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
0.0
>>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
3.0 | [
"r",
"Generate",
"a",
"bqm",
"that",
"is",
"minimized",
"when",
"k",
"of",
"n",
"variables",
"are",
"selected",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/generators/constraints.py#L30-L107 | train | 212,552 |
dwavesystems/dimod | dimod/generators/random.py | uniform | def uniform(graph, vartype, low=0.0, high=1.0, cls=BinaryQuadraticModel,
seed=None):
"""Generate a bqm with random biases and offset.
Biases and offset are drawn from a uniform distribution range (low, high).
Args:
graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
The graph to build the bqm loops on. Either an integer n, interpreted as a
complete graph of size n, or a nodes/edges pair, or a NetworkX graph.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
low (float, optional, default=0.0):
The low end of the range for the random biases.
high (float, optional, default=1.0):
The high end of the range for the random biases.
cls (:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`
"""
if seed is None:
seed = numpy.random.randint(2**32, dtype=np.uint32)
r = numpy.random.RandomState(seed)
variables, edges = graph
index = {v: idx for idx, v in enumerate(variables)}
if edges:
irow, icol = zip(*((index[u], index[v]) for u, v in edges))
else:
irow = icol = tuple()
ldata = r.uniform(low, high, size=len(variables))
qdata = r.uniform(low, high, size=len(irow))
offset = r.uniform(low, high)
return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype,
variable_order=variables) | python | def uniform(graph, vartype, low=0.0, high=1.0, cls=BinaryQuadraticModel,
seed=None):
"""Generate a bqm with random biases and offset.
Biases and offset are drawn from a uniform distribution range (low, high).
Args:
graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
The graph to build the bqm loops on. Either an integer n, interpreted as a
complete graph of size n, or a nodes/edges pair, or a NetworkX graph.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
low (float, optional, default=0.0):
The low end of the range for the random biases.
high (float, optional, default=1.0):
The high end of the range for the random biases.
cls (:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`
"""
if seed is None:
seed = numpy.random.randint(2**32, dtype=np.uint32)
r = numpy.random.RandomState(seed)
variables, edges = graph
index = {v: idx for idx, v in enumerate(variables)}
if edges:
irow, icol = zip(*((index[u], index[v]) for u, v in edges))
else:
irow = icol = tuple()
ldata = r.uniform(low, high, size=len(variables))
qdata = r.uniform(low, high, size=len(irow))
offset = r.uniform(low, high)
return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype,
variable_order=variables) | [
"def",
"uniform",
"(",
"graph",
",",
"vartype",
",",
"low",
"=",
"0.0",
",",
"high",
"=",
"1.0",
",",
"cls",
"=",
"BinaryQuadraticModel",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"numpy",
".",
"random",
".",... | Generate a bqm with random biases and offset.
Biases and offset are drawn from a uniform distribution range (low, high).
Args:
graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
The graph to build the bqm loops on. Either an integer n, interpreted as a
complete graph of size n, or a nodes/edges pair, or a NetworkX graph.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
low (float, optional, default=0.0):
The low end of the range for the random biases.
high (float, optional, default=1.0):
The high end of the range for the random biases.
cls (:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel` | [
"Generate",
"a",
"bqm",
"with",
"random",
"biases",
"and",
"offset",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/generators/random.py#L28-L79 | train | 212,553 |
dwavesystems/dimod | dimod/generators/random.py | ran_r | def ran_r(r, graph, cls=BinaryQuadraticModel, seed=None):
"""Generate an Ising model for a RANr problem.
In RANr problems all linear biases are zero and quadratic values are uniformly
selected integers between -r to r, excluding zero. This class of problems is relevant
for binary quadratic models (BQM) with spin variables (Ising models).
This generator of RANr problems follows the definition in [Kin2015]_\ .
Args:
r (int):
Order of the RANr problem.
graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
The graph to build the BQM for. Either an
integer n, interpreted as a complete graph of size n, or
a nodes/edges pair, or a NetworkX graph.
cls (:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`.
Examples:
>>> import networkx as nx
>>> K_7 = nx.complete_graph(7)
>>> bqm = dimod.generators.random.ran_r(1, K_7)
.. [Kin2015] James King, Sheir Yarkoni, Mayssam M. Nevisi, Jeremy P. Hilton,
Catherine C. McGeoch. Benchmarking a quantum annealing processor with the
time-to-target metric. https://arxiv.org/abs/1508.05087
"""
if not isinstance(r, int):
raise TypeError("r should be a positive integer")
if r < 1:
raise ValueError("r should be a positive integer")
if seed is None:
seed = numpy.random.randint(2**32, dtype=np.uint32)
rnd = numpy.random.RandomState(seed)
variables, edges = graph
index = {v: idx for idx, v in enumerate(variables)}
if edges:
irow, icol = zip(*((index[u], index[v]) for u, v in edges))
else:
irow = icol = tuple()
ldata = np.zeros(len(variables))
rvals = np.empty(2*r)
rvals[0:r] = range(-r, 0)
rvals[r:] = range(1, r+1)
qdata = rnd.choice(rvals, size=len(irow))
offset = 0
return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype='SPIN',
variable_order=variables) | python | def ran_r(r, graph, cls=BinaryQuadraticModel, seed=None):
"""Generate an Ising model for a RANr problem.
In RANr problems all linear biases are zero and quadratic values are uniformly
selected integers between -r to r, excluding zero. This class of problems is relevant
for binary quadratic models (BQM) with spin variables (Ising models).
This generator of RANr problems follows the definition in [Kin2015]_\ .
Args:
r (int):
Order of the RANr problem.
graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
The graph to build the BQM for. Either an
integer n, interpreted as a complete graph of size n, or
a nodes/edges pair, or a NetworkX graph.
cls (:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`.
Examples:
>>> import networkx as nx
>>> K_7 = nx.complete_graph(7)
>>> bqm = dimod.generators.random.ran_r(1, K_7)
.. [Kin2015] James King, Sheir Yarkoni, Mayssam M. Nevisi, Jeremy P. Hilton,
Catherine C. McGeoch. Benchmarking a quantum annealing processor with the
time-to-target metric. https://arxiv.org/abs/1508.05087
"""
if not isinstance(r, int):
raise TypeError("r should be a positive integer")
if r < 1:
raise ValueError("r should be a positive integer")
if seed is None:
seed = numpy.random.randint(2**32, dtype=np.uint32)
rnd = numpy.random.RandomState(seed)
variables, edges = graph
index = {v: idx for idx, v in enumerate(variables)}
if edges:
irow, icol = zip(*((index[u], index[v]) for u, v in edges))
else:
irow = icol = tuple()
ldata = np.zeros(len(variables))
rvals = np.empty(2*r)
rvals[0:r] = range(-r, 0)
rvals[r:] = range(1, r+1)
qdata = rnd.choice(rvals, size=len(irow))
offset = 0
return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype='SPIN',
variable_order=variables) | [
"def",
"ran_r",
"(",
"r",
",",
"graph",
",",
"cls",
"=",
"BinaryQuadraticModel",
",",
"seed",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"r",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"r should be a positive integer\"",
")",
"if",
"r... | Generate an Ising model for a RANr problem.
In RANr problems all linear biases are zero and quadratic values are uniformly
selected integers between -r to r, excluding zero. This class of problems is relevant
for binary quadratic models (BQM) with spin variables (Ising models).
This generator of RANr problems follows the definition in [Kin2015]_\ .
Args:
r (int):
Order of the RANr problem.
graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
The graph to build the BQM for. Either an
integer n, interpreted as a complete graph of size n, or
a nodes/edges pair, or a NetworkX graph.
cls (:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`.
Examples:
>>> import networkx as nx
>>> K_7 = nx.complete_graph(7)
>>> bqm = dimod.generators.random.ran_r(1, K_7)
.. [Kin2015] James King, Sheir Yarkoni, Mayssam M. Nevisi, Jeremy P. Hilton,
Catherine C. McGeoch. Benchmarking a quantum annealing processor with the
time-to-target metric. https://arxiv.org/abs/1508.05087 | [
"Generate",
"an",
"Ising",
"model",
"for",
"a",
"RANr",
"problem",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/generators/random.py#L139-L205 | train | 212,554 |
dwavesystems/dimod | dimod/decorators.py | bqm_index_labels | def bqm_index_labels(f):
"""Decorator to convert a bqm to index-labels and relabel the sample set
output.
Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped
function or method to accept a :obj:`.BinaryQuadraticModel` as the second
input and to return a :obj:`.SampleSet`.
"""
@wraps(f)
def _index_label(sampler, bqm, **kwargs):
if not hasattr(bqm, 'linear'):
raise TypeError('expected input to be a BinaryQuadraticModel')
linear = bqm.linear
# if already index-labelled, just continue
if all(v in linear for v in range(len(bqm))):
return f(sampler, bqm, **kwargs)
try:
inverse_mapping = dict(enumerate(sorted(linear)))
except TypeError:
# in python3 unlike types cannot be sorted
inverse_mapping = dict(enumerate(linear))
mapping = {v: i for i, v in iteritems(inverse_mapping)}
response = f(sampler, bqm.relabel_variables(mapping, inplace=False), **kwargs)
# unapply the relabeling
return response.relabel_variables(inverse_mapping, inplace=True)
return _index_label | python | def bqm_index_labels(f):
"""Decorator to convert a bqm to index-labels and relabel the sample set
output.
Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped
function or method to accept a :obj:`.BinaryQuadraticModel` as the second
input and to return a :obj:`.SampleSet`.
"""
@wraps(f)
def _index_label(sampler, bqm, **kwargs):
if not hasattr(bqm, 'linear'):
raise TypeError('expected input to be a BinaryQuadraticModel')
linear = bqm.linear
# if already index-labelled, just continue
if all(v in linear for v in range(len(bqm))):
return f(sampler, bqm, **kwargs)
try:
inverse_mapping = dict(enumerate(sorted(linear)))
except TypeError:
# in python3 unlike types cannot be sorted
inverse_mapping = dict(enumerate(linear))
mapping = {v: i for i, v in iteritems(inverse_mapping)}
response = f(sampler, bqm.relabel_variables(mapping, inplace=False), **kwargs)
# unapply the relabeling
return response.relabel_variables(inverse_mapping, inplace=True)
return _index_label | [
"def",
"bqm_index_labels",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_index_label",
"(",
"sampler",
",",
"bqm",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"bqm",
",",
"'linear'",
")",
":",
"raise",
"TypeError",
"... | Decorator to convert a bqm to index-labels and relabel the sample set
output.
Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped
function or method to accept a :obj:`.BinaryQuadraticModel` as the second
input and to return a :obj:`.SampleSet`. | [
"Decorator",
"to",
"convert",
"a",
"bqm",
"to",
"index",
"-",
"labels",
"and",
"relabel",
"the",
"sample",
"set",
"output",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/decorators.py#L42-L74 | train | 212,555 |
dwavesystems/dimod | dimod/decorators.py | bqm_index_labelled_input | def bqm_index_labelled_input(var_labels_arg_name, samples_arg_names):
"""Returns a decorator which ensures bqm variable labeling and all other
specified sample-like inputs are index labeled and consistent.
Args:
var_labels_arg_name (str):
The name of the argument that the user should use to pass in an
index labeling for the bqm.
samples_arg_names (list[str]):
The names of the expected sample-like inputs which should be
indexed according to the labels passed to the argument
`var_labels_arg_name`.
Returns:
Function decorator.
"""
def index_label_decorator(f):
@wraps(f)
def _index_label(sampler, bqm, **kwargs):
if not hasattr(bqm, 'linear'):
raise TypeError('expected input to be a BinaryQuadraticModel')
linear = bqm.linear
var_labels = kwargs.get(var_labels_arg_name, None)
has_samples_input = any(kwargs.get(arg_name, None) is not None
for arg_name in samples_arg_names)
if var_labels is None:
# if already index-labelled, just continue
if all(v in linear for v in range(len(bqm))):
return f(sampler, bqm, **kwargs)
if has_samples_input:
err_str = ("Argument `{}` must be provided if any of the"
" samples arguments {} are provided and the "
"bqm is not already index-labelled".format(
var_labels_arg_name,
samples_arg_names))
raise ValueError(err_str)
try:
inverse_mapping = dict(enumerate(sorted(linear)))
except TypeError:
# in python3 unlike types cannot be sorted
inverse_mapping = dict(enumerate(linear))
var_labels = {v: i for i, v in iteritems(inverse_mapping)}
else:
inverse_mapping = {i: v for v, i in iteritems(var_labels)}
response = f(sampler,
bqm.relabel_variables(var_labels, inplace=False),
**kwargs)
# unapply the relabeling
return response.relabel_variables(inverse_mapping, inplace=True)
return _index_label
return index_label_decorator | python | def bqm_index_labelled_input(var_labels_arg_name, samples_arg_names):
"""Returns a decorator which ensures bqm variable labeling and all other
specified sample-like inputs are index labeled and consistent.
Args:
var_labels_arg_name (str):
The name of the argument that the user should use to pass in an
index labeling for the bqm.
samples_arg_names (list[str]):
The names of the expected sample-like inputs which should be
indexed according to the labels passed to the argument
`var_labels_arg_name`.
Returns:
Function decorator.
"""
def index_label_decorator(f):
@wraps(f)
def _index_label(sampler, bqm, **kwargs):
if not hasattr(bqm, 'linear'):
raise TypeError('expected input to be a BinaryQuadraticModel')
linear = bqm.linear
var_labels = kwargs.get(var_labels_arg_name, None)
has_samples_input = any(kwargs.get(arg_name, None) is not None
for arg_name in samples_arg_names)
if var_labels is None:
# if already index-labelled, just continue
if all(v in linear for v in range(len(bqm))):
return f(sampler, bqm, **kwargs)
if has_samples_input:
err_str = ("Argument `{}` must be provided if any of the"
" samples arguments {} are provided and the "
"bqm is not already index-labelled".format(
var_labels_arg_name,
samples_arg_names))
raise ValueError(err_str)
try:
inverse_mapping = dict(enumerate(sorted(linear)))
except TypeError:
# in python3 unlike types cannot be sorted
inverse_mapping = dict(enumerate(linear))
var_labels = {v: i for i, v in iteritems(inverse_mapping)}
else:
inverse_mapping = {i: v for v, i in iteritems(var_labels)}
response = f(sampler,
bqm.relabel_variables(var_labels, inplace=False),
**kwargs)
# unapply the relabeling
return response.relabel_variables(inverse_mapping, inplace=True)
return _index_label
return index_label_decorator | [
"def",
"bqm_index_labelled_input",
"(",
"var_labels_arg_name",
",",
"samples_arg_names",
")",
":",
"def",
"index_label_decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_index_label",
"(",
"sampler",
",",
"bqm",
",",
"*",
"*",
"kwargs",
")... | Returns a decorator which ensures bqm variable labeling and all other
specified sample-like inputs are index labeled and consistent.
Args:
var_labels_arg_name (str):
The name of the argument that the user should use to pass in an
index labeling for the bqm.
samples_arg_names (list[str]):
The names of the expected sample-like inputs which should be
indexed according to the labels passed to the argument
`var_labels_arg_name`.
Returns:
Function decorator. | [
"Returns",
"a",
"decorator",
"which",
"ensures",
"bqm",
"variable",
"labeling",
"and",
"all",
"other",
"specified",
"sample",
"-",
"like",
"inputs",
"are",
"index",
"labeled",
"and",
"consistent",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/decorators.py#L77-L138 | train | 212,556 |
dwavesystems/dimod | dimod/decorators.py | bqm_structured | def bqm_structured(f):
"""Decorator to raise an error if the given bqm does not match the sampler's
structure.
Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped
function or method to accept a :obj:`.BinaryQuadraticModel` as the second
input and for the :class:`.Sampler` to also be :class:`.Structured`.
"""
@wraps(f)
def new_f(sampler, bqm, **kwargs):
try:
structure = sampler.structure
adjacency = structure.adjacency
except AttributeError:
if isinstance(sampler, Structured):
raise RuntimeError("something is wrong with the structured sampler")
else:
raise TypeError("sampler does not have a structure property")
if not all(v in adjacency for v in bqm.linear):
# todo: better error message
raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure")
if not all(u in adjacency[v] for u, v in bqm.quadratic):
# todo: better error message
raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure")
return f(sampler, bqm, **kwargs)
return new_f | python | def bqm_structured(f):
"""Decorator to raise an error if the given bqm does not match the sampler's
structure.
Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped
function or method to accept a :obj:`.BinaryQuadraticModel` as the second
input and for the :class:`.Sampler` to also be :class:`.Structured`.
"""
@wraps(f)
def new_f(sampler, bqm, **kwargs):
try:
structure = sampler.structure
adjacency = structure.adjacency
except AttributeError:
if isinstance(sampler, Structured):
raise RuntimeError("something is wrong with the structured sampler")
else:
raise TypeError("sampler does not have a structure property")
if not all(v in adjacency for v in bqm.linear):
# todo: better error message
raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure")
if not all(u in adjacency[v] for u, v in bqm.quadratic):
# todo: better error message
raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure")
return f(sampler, bqm, **kwargs)
return new_f | [
"def",
"bqm_structured",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"new_f",
"(",
"sampler",
",",
"bqm",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"structure",
"=",
"sampler",
".",
"structure",
"adjacency",
"=",
"structure",
".",
... | Decorator to raise an error if the given bqm does not match the sampler's
structure.
Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped
function or method to accept a :obj:`.BinaryQuadraticModel` as the second
input and for the :class:`.Sampler` to also be :class:`.Structured`. | [
"Decorator",
"to",
"raise",
"an",
"error",
"if",
"the",
"given",
"bqm",
"does",
"not",
"match",
"the",
"sampler",
"s",
"structure",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/decorators.py#L141-L170 | train | 212,557 |
dwavesystems/dimod | dimod/decorators.py | graph_argument | def graph_argument(*arg_names, **options):
"""Decorator to coerce given graph arguments into a consistent form.
The wrapped function will accept either an integer n, interpreted as a
complete graph of size n, or a nodes/edges pair, or a NetworkX graph. The
argument will then be converted into a nodes/edges 2-tuple.
Args:
*arg_names (optional, default='G'):
The names of the arguments for input graphs.
allow_None (bool, optional, default=False):
Allow None as an input graph in which case it is passed through as
None.
"""
# by default, constrain only one argument, the 'G`
if not arg_names:
arg_names = ['G']
# we only allow one option allow_None
allow_None = options.pop("allow_None", False)
if options:
# to keep it consistent with python3
# behaviour like graph_argument(*arg_names, allow_None=False)
key, _ = options.popitem()
msg = "graph_argument() for an unexpected keyword argument '{}'".format(key)
raise TypeError(msg)
def _graph_arg(f):
argspec = getargspec(f)
def _enforce_single_arg(name, args, kwargs):
try:
G = kwargs[name]
except KeyError:
raise TypeError('Graph argument missing')
if hasattr(G, 'edges') and hasattr(G, 'nodes'):
# networkx or perhaps a named tuple
kwargs[name] = (list(G.nodes), list(G.edges))
elif _is_integer(G):
# an integer, cast to a complete graph
kwargs[name] = (list(range(G)), list(itertools.combinations(range(G), 2)))
elif isinstance(G, abc.Sequence) and len(G) == 2:
# is a pair nodes/edges
if isinstance(G[0], integer_types):
# if nodes is an int
kwargs[name] = (list(range(G[0])), G[1])
elif allow_None and G is None:
# allow None to be passed through
return G
else:
raise ValueError('Unexpected graph input form')
return
@wraps(f)
def new_f(*args, **kwargs):
# bound actual f arguments (including defaults) to f argument names
# (note: if call arguments don't match actual function signature,
# we'll fail here with the standard `TypeError`)
bound_args = inspect.getcallargs(f, *args, **kwargs)
# `getcallargs` doesn't merge additional positional/keyword arguments,
# so do it manually
final_args = list(bound_args.pop(argspec.varargs, ()))
final_kwargs = bound_args.pop(argspec.keywords, {})
final_kwargs.update(bound_args)
for name in arg_names:
_enforce_single_arg(name, final_args, final_kwargs)
return f(*final_args, **final_kwargs)
return new_f
return _graph_arg | python | def graph_argument(*arg_names, **options):
"""Decorator to coerce given graph arguments into a consistent form.
The wrapped function will accept either an integer n, interpreted as a
complete graph of size n, or a nodes/edges pair, or a NetworkX graph. The
argument will then be converted into a nodes/edges 2-tuple.
Args:
*arg_names (optional, default='G'):
The names of the arguments for input graphs.
allow_None (bool, optional, default=False):
Allow None as an input graph in which case it is passed through as
None.
"""
# by default, constrain only one argument, the 'G`
if not arg_names:
arg_names = ['G']
# we only allow one option allow_None
allow_None = options.pop("allow_None", False)
if options:
# to keep it consistent with python3
# behaviour like graph_argument(*arg_names, allow_None=False)
key, _ = options.popitem()
msg = "graph_argument() for an unexpected keyword argument '{}'".format(key)
raise TypeError(msg)
def _graph_arg(f):
argspec = getargspec(f)
def _enforce_single_arg(name, args, kwargs):
try:
G = kwargs[name]
except KeyError:
raise TypeError('Graph argument missing')
if hasattr(G, 'edges') and hasattr(G, 'nodes'):
# networkx or perhaps a named tuple
kwargs[name] = (list(G.nodes), list(G.edges))
elif _is_integer(G):
# an integer, cast to a complete graph
kwargs[name] = (list(range(G)), list(itertools.combinations(range(G), 2)))
elif isinstance(G, abc.Sequence) and len(G) == 2:
# is a pair nodes/edges
if isinstance(G[0], integer_types):
# if nodes is an int
kwargs[name] = (list(range(G[0])), G[1])
elif allow_None and G is None:
# allow None to be passed through
return G
else:
raise ValueError('Unexpected graph input form')
return
@wraps(f)
def new_f(*args, **kwargs):
# bound actual f arguments (including defaults) to f argument names
# (note: if call arguments don't match actual function signature,
# we'll fail here with the standard `TypeError`)
bound_args = inspect.getcallargs(f, *args, **kwargs)
# `getcallargs` doesn't merge additional positional/keyword arguments,
# so do it manually
final_args = list(bound_args.pop(argspec.varargs, ()))
final_kwargs = bound_args.pop(argspec.keywords, {})
final_kwargs.update(bound_args)
for name in arg_names:
_enforce_single_arg(name, final_args, final_kwargs)
return f(*final_args, **final_kwargs)
return new_f
return _graph_arg | [
"def",
"graph_argument",
"(",
"*",
"arg_names",
",",
"*",
"*",
"options",
")",
":",
"# by default, constrain only one argument, the 'G`",
"if",
"not",
"arg_names",
":",
"arg_names",
"=",
"[",
"'G'",
"]",
"# we only allow one option allow_None",
"allow_None",
"=",
"opt... | Decorator to coerce given graph arguments into a consistent form.
The wrapped function will accept either an integer n, interpreted as a
complete graph of size n, or a nodes/edges pair, or a NetworkX graph. The
argument will then be converted into a nodes/edges 2-tuple.
Args:
*arg_names (optional, default='G'):
The names of the arguments for input graphs.
allow_None (bool, optional, default=False):
Allow None as an input graph in which case it is passed through as
None. | [
"Decorator",
"to",
"coerce",
"given",
"graph",
"arguments",
"into",
"a",
"consistent",
"form",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/decorators.py#L269-L351 | train | 212,558 |
dwavesystems/dimod | dimod/serialization/utils.py | array2bytes | def array2bytes(arr, bytes_type=bytes):
"""Wraps NumPy's save function to return bytes.
We use :func:`numpy.save` rather than :meth:`numpy.ndarray.tobytes` because
it encodes endianness and order.
Args:
arr (:obj:`numpy.ndarray`):
Array to be saved.
bytes_type (class, optional, default=bytes):
This class will be used to wrap the bytes objects in the
serialization if `use_bytes` is true. Useful for when using
Python 2 and using BSON encoding, which will not accept the raw
`bytes` type, so `bson.Binary` can be used instead.
Returns:
bytes_type
"""
bio = io.BytesIO()
np.save(bio, arr, allow_pickle=False)
return bytes_type(bio.getvalue()) | python | def array2bytes(arr, bytes_type=bytes):
"""Wraps NumPy's save function to return bytes.
We use :func:`numpy.save` rather than :meth:`numpy.ndarray.tobytes` because
it encodes endianness and order.
Args:
arr (:obj:`numpy.ndarray`):
Array to be saved.
bytes_type (class, optional, default=bytes):
This class will be used to wrap the bytes objects in the
serialization if `use_bytes` is true. Useful for when using
Python 2 and using BSON encoding, which will not accept the raw
`bytes` type, so `bson.Binary` can be used instead.
Returns:
bytes_type
"""
bio = io.BytesIO()
np.save(bio, arr, allow_pickle=False)
return bytes_type(bio.getvalue()) | [
"def",
"array2bytes",
"(",
"arr",
",",
"bytes_type",
"=",
"bytes",
")",
":",
"bio",
"=",
"io",
".",
"BytesIO",
"(",
")",
"np",
".",
"save",
"(",
"bio",
",",
"arr",
",",
"allow_pickle",
"=",
"False",
")",
"return",
"bytes_type",
"(",
"bio",
".",
"ge... | Wraps NumPy's save function to return bytes.
We use :func:`numpy.save` rather than :meth:`numpy.ndarray.tobytes` because
it encodes endianness and order.
Args:
arr (:obj:`numpy.ndarray`):
Array to be saved.
bytes_type (class, optional, default=bytes):
This class will be used to wrap the bytes objects in the
serialization if `use_bytes` is true. Useful for when using
Python 2 and using BSON encoding, which will not accept the raw
`bytes` type, so `bson.Binary` can be used instead.
Returns:
bytes_type | [
"Wraps",
"NumPy",
"s",
"save",
"function",
"to",
"return",
"bytes",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/serialization/utils.py#L24-L47 | train | 212,559 |
dwavesystems/dimod | dimod/reference/composites/truncatecomposite.py | TruncateComposite.sample | def sample(self, bqm, **kwargs):
"""Sample from the problem provided by bqm and truncate output.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
**kwargs:
Parameters for the sampling method, specified by the child
sampler.
Returns:
:obj:`dimod.SampleSet`
"""
tkw = self._truncate_kwargs
if self._aggregate:
return self.child.sample(bqm, **kwargs).aggregate().truncate(**tkw)
else:
return self.child.sample(bqm, **kwargs).truncate(**tkw) | python | def sample(self, bqm, **kwargs):
"""Sample from the problem provided by bqm and truncate output.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
**kwargs:
Parameters for the sampling method, specified by the child
sampler.
Returns:
:obj:`dimod.SampleSet`
"""
tkw = self._truncate_kwargs
if self._aggregate:
return self.child.sample(bqm, **kwargs).aggregate().truncate(**tkw)
else:
return self.child.sample(bqm, **kwargs).truncate(**tkw) | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"*",
"*",
"kwargs",
")",
":",
"tkw",
"=",
"self",
".",
"_truncate_kwargs",
"if",
"self",
".",
"_aggregate",
":",
"return",
"self",
".",
"child",
".",
"sample",
"(",
"bqm",
",",
"*",
"*",
"kwargs",
")",... | Sample from the problem provided by bqm and truncate output.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
**kwargs:
Parameters for the sampling method, specified by the child
sampler.
Returns:
:obj:`dimod.SampleSet` | [
"Sample",
"from",
"the",
"problem",
"provided",
"by",
"bqm",
"and",
"truncate",
"output",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/truncatecomposite.py#L78-L97 | train | 212,560 |
dwavesystems/dimod | dimod/reference/samplers/exact_solver.py | ExactSolver.sample | def sample(self, bqm):
"""Sample from a binary quadratic model.
Args:
bqm (:obj:`~dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
Returns:
:obj:`~dimod.SampleSet`
"""
M = bqm.binary.to_numpy_matrix()
off = bqm.binary.offset
if M.shape == (0, 0):
return SampleSet.from_samples([], bqm.vartype, energy=[])
sample = np.zeros((len(bqm),), dtype=bool)
# now we iterate, flipping one bit at a time until we have
# traversed all samples. This is a Gray code.
# https://en.wikipedia.org/wiki/Gray_code
def iter_samples():
sample = np.zeros((len(bqm)), dtype=bool)
energy = 0.0
yield sample.copy(), energy + off
for i in range(1, 1 << len(bqm)):
v = _ffs(i)
# flip the bit in the sample
sample[v] = not sample[v]
# for now just calculate the energy, but there is a more clever way by calculating
# the energy delta for the single bit flip, don't have time, pull requests
# appreciated!
energy = sample.dot(M).dot(sample.transpose())
yield sample.copy(), float(energy) + off
samples, energies = zip(*iter_samples())
response = SampleSet.from_samples(np.array(samples, dtype='int8'), Vartype.BINARY, energies)
# make sure the response matches the given vartype, in-place.
response.change_vartype(bqm.vartype, inplace=True)
return response | python | def sample(self, bqm):
"""Sample from a binary quadratic model.
Args:
bqm (:obj:`~dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
Returns:
:obj:`~dimod.SampleSet`
"""
M = bqm.binary.to_numpy_matrix()
off = bqm.binary.offset
if M.shape == (0, 0):
return SampleSet.from_samples([], bqm.vartype, energy=[])
sample = np.zeros((len(bqm),), dtype=bool)
# now we iterate, flipping one bit at a time until we have
# traversed all samples. This is a Gray code.
# https://en.wikipedia.org/wiki/Gray_code
def iter_samples():
sample = np.zeros((len(bqm)), dtype=bool)
energy = 0.0
yield sample.copy(), energy + off
for i in range(1, 1 << len(bqm)):
v = _ffs(i)
# flip the bit in the sample
sample[v] = not sample[v]
# for now just calculate the energy, but there is a more clever way by calculating
# the energy delta for the single bit flip, don't have time, pull requests
# appreciated!
energy = sample.dot(M).dot(sample.transpose())
yield sample.copy(), float(energy) + off
samples, energies = zip(*iter_samples())
response = SampleSet.from_samples(np.array(samples, dtype='int8'), Vartype.BINARY, energies)
# make sure the response matches the given vartype, in-place.
response.change_vartype(bqm.vartype, inplace=True)
return response | [
"def",
"sample",
"(",
"self",
",",
"bqm",
")",
":",
"M",
"=",
"bqm",
".",
"binary",
".",
"to_numpy_matrix",
"(",
")",
"off",
"=",
"bqm",
".",
"binary",
".",
"offset",
"if",
"M",
".",
"shape",
"==",
"(",
"0",
",",
"0",
")",
":",
"return",
"Sampl... | Sample from a binary quadratic model.
Args:
bqm (:obj:`~dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
Returns:
:obj:`~dimod.SampleSet` | [
"Sample",
"from",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/samplers/exact_solver.py#L78-L126 | train | 212,561 |
dwavesystems/dimod | dimod/vartypes.py | as_vartype | def as_vartype(vartype):
"""Cast various inputs to a valid vartype object.
Args:
vartype (:class:`.Vartype`/str/set):
Variable type. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:class:`.Vartype`: Either :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
See also:
:func:`~dimod.decorators.vartype_argument`
"""
if isinstance(vartype, Vartype):
return vartype
try:
if isinstance(vartype, str):
vartype = Vartype[vartype]
elif isinstance(vartype, frozenset):
vartype = Vartype(vartype)
else:
vartype = Vartype(frozenset(vartype))
except (ValueError, KeyError):
raise TypeError(("expected input vartype to be one of: "
"Vartype.SPIN, 'SPIN', {-1, 1}, "
"Vartype.BINARY, 'BINARY', or {0, 1}."))
return vartype | python | def as_vartype(vartype):
"""Cast various inputs to a valid vartype object.
Args:
vartype (:class:`.Vartype`/str/set):
Variable type. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:class:`.Vartype`: Either :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
See also:
:func:`~dimod.decorators.vartype_argument`
"""
if isinstance(vartype, Vartype):
return vartype
try:
if isinstance(vartype, str):
vartype = Vartype[vartype]
elif isinstance(vartype, frozenset):
vartype = Vartype(vartype)
else:
vartype = Vartype(frozenset(vartype))
except (ValueError, KeyError):
raise TypeError(("expected input vartype to be one of: "
"Vartype.SPIN, 'SPIN', {-1, 1}, "
"Vartype.BINARY, 'BINARY', or {0, 1}."))
return vartype | [
"def",
"as_vartype",
"(",
"vartype",
")",
":",
"if",
"isinstance",
"(",
"vartype",
",",
"Vartype",
")",
":",
"return",
"vartype",
"try",
":",
"if",
"isinstance",
"(",
"vartype",
",",
"str",
")",
":",
"vartype",
"=",
"Vartype",
"[",
"vartype",
"]",
"eli... | Cast various inputs to a valid vartype object.
Args:
vartype (:class:`.Vartype`/str/set):
Variable type. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Returns:
:class:`.Vartype`: Either :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
See also:
:func:`~dimod.decorators.vartype_argument` | [
"Cast",
"various",
"inputs",
"to",
"a",
"valid",
"vartype",
"object",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/vartypes.py#L80-L114 | train | 212,562 |
dwavesystems/dimod | dimod/higherorder/polynomial.py | BinaryPolynomial.energy | def energy(self, sample_like, dtype=np.float):
"""The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned energies. Defaults to float.
Returns:
The energy.
"""
energy, = self.energies(sample_like, dtype=dtype)
return energy | python | def energy(self, sample_like, dtype=np.float):
"""The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned energies. Defaults to float.
Returns:
The energy.
"""
energy, = self.energies(sample_like, dtype=dtype)
return energy | [
"def",
"energy",
"(",
"self",
",",
"sample_like",
",",
"dtype",
"=",
"np",
".",
"float",
")",
":",
"energy",
",",
"=",
"self",
".",
"energies",
"(",
"sample_like",
",",
"dtype",
"=",
"dtype",
")",
"return",
"energy"
] | The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned energies. Defaults to float.
Returns:
The energy. | [
"The",
"energy",
"of",
"the",
"given",
"sample",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L182-L198 | train | 212,563 |
dwavesystems/dimod | dimod/higherorder/polynomial.py | BinaryPolynomial.energies | def energies(self, samples_like, dtype=np.float):
"""The energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned energies. Defaults to float.
Returns:
:obj:`numpy.ndarray`: The energies.
"""
samples, labels = as_samples(samples_like)
if labels:
idx, label = zip(*enumerate(labels))
labeldict = dict(zip(label, idx))
else:
labeldict = {}
num_samples = samples.shape[0]
energies = np.zeros(num_samples, dtype=dtype)
for term, bias in self.items():
if len(term) == 0:
energies += bias
else:
energies += np.prod([samples[:, labeldict[v]] for v in term], axis=0) * bias
return energies | python | def energies(self, samples_like, dtype=np.float):
"""The energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned energies. Defaults to float.
Returns:
:obj:`numpy.ndarray`: The energies.
"""
samples, labels = as_samples(samples_like)
if labels:
idx, label = zip(*enumerate(labels))
labeldict = dict(zip(label, idx))
else:
labeldict = {}
num_samples = samples.shape[0]
energies = np.zeros(num_samples, dtype=dtype)
for term, bias in self.items():
if len(term) == 0:
energies += bias
else:
energies += np.prod([samples[:, labeldict[v]] for v in term], axis=0) * bias
return energies | [
"def",
"energies",
"(",
"self",
",",
"samples_like",
",",
"dtype",
"=",
"np",
".",
"float",
")",
":",
"samples",
",",
"labels",
"=",
"as_samples",
"(",
"samples_like",
")",
"if",
"labels",
":",
"idx",
",",
"label",
"=",
"zip",
"(",
"*",
"enumerate",
... | The energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned energies. Defaults to float.
Returns:
:obj:`numpy.ndarray`: The energies. | [
"The",
"energies",
"of",
"the",
"given",
"samples",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L200-L231 | train | 212,564 |
dwavesystems/dimod | dimod/higherorder/polynomial.py | BinaryPolynomial.relabel_variables | def relabel_variables(self, mapping, inplace=True):
"""Relabel variables of a binary polynomial as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an
incomplete mapping is provided, unmapped variables retain their
current labels.
inplace (bool, optional, default=True):
If True, the binary polynomial is updated in-place; otherwise, a
new binary polynomial is returned.
Returns:
:class:`.BinaryPolynomial`: A binary polynomial with the variables
relabeled. If `inplace` is set to True, returns itself.
"""
if not inplace:
return self.copy().relabel_variables(mapping, inplace=True)
try:
old_labels = set(mapping)
new_labels = set(mapping.values())
except TypeError:
raise ValueError("mapping targets must be hashable objects")
variables = self.variables
for v in new_labels:
if v in variables and v not in old_labels:
raise ValueError(('A variable cannot be relabeled "{}" without also relabeling '
"the existing variable of the same name").format(v))
shared = old_labels & new_labels
if shared:
old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels)
self.relabel_variables(old_to_intermediate, inplace=True)
self.relabel_variables(intermediate_to_new, inplace=True)
return self
for oldterm, bias in list(self.items()):
newterm = frozenset((mapping.get(v, v) for v in oldterm))
if newterm != oldterm:
self[newterm] = bias
del self[oldterm]
return self | python | def relabel_variables(self, mapping, inplace=True):
"""Relabel variables of a binary polynomial as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an
incomplete mapping is provided, unmapped variables retain their
current labels.
inplace (bool, optional, default=True):
If True, the binary polynomial is updated in-place; otherwise, a
new binary polynomial is returned.
Returns:
:class:`.BinaryPolynomial`: A binary polynomial with the variables
relabeled. If `inplace` is set to True, returns itself.
"""
if not inplace:
return self.copy().relabel_variables(mapping, inplace=True)
try:
old_labels = set(mapping)
new_labels = set(mapping.values())
except TypeError:
raise ValueError("mapping targets must be hashable objects")
variables = self.variables
for v in new_labels:
if v in variables and v not in old_labels:
raise ValueError(('A variable cannot be relabeled "{}" without also relabeling '
"the existing variable of the same name").format(v))
shared = old_labels & new_labels
if shared:
old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels)
self.relabel_variables(old_to_intermediate, inplace=True)
self.relabel_variables(intermediate_to_new, inplace=True)
return self
for oldterm, bias in list(self.items()):
newterm = frozenset((mapping.get(v, v) for v in oldterm))
if newterm != oldterm:
self[newterm] = bias
del self[oldterm]
return self | [
"def",
"relabel_variables",
"(",
"self",
",",
"mapping",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"not",
"inplace",
":",
"return",
"self",
".",
"copy",
"(",
")",
".",
"relabel_variables",
"(",
"mapping",
",",
"inplace",
"=",
"True",
")",
"try",
":"... | Relabel variables of a binary polynomial as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an
incomplete mapping is provided, unmapped variables retain their
current labels.
inplace (bool, optional, default=True):
If True, the binary polynomial is updated in-place; otherwise, a
new binary polynomial is returned.
Returns:
:class:`.BinaryPolynomial`: A binary polynomial with the variables
relabeled. If `inplace` is set to True, returns itself. | [
"Relabel",
"variables",
"of",
"a",
"binary",
"polynomial",
"as",
"specified",
"by",
"mapping",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L233-L281 | train | 212,565 |
dwavesystems/dimod | dimod/higherorder/polynomial.py | BinaryPolynomial.scale | def scale(self, scalar, ignored_terms=None):
"""Multiply the polynomial by the given scalar.
Args:
scalar (number):
Value to multiply the polynomial by.
ignored_terms (iterable, optional):
Biases associated with these terms are not scaled.
"""
if ignored_terms is None:
ignored_terms = set()
else:
ignored_terms = {asfrozenset(term) for term in ignored_terms}
for term in self:
if term not in ignored_terms:
self[term] *= scalar | python | def scale(self, scalar, ignored_terms=None):
"""Multiply the polynomial by the given scalar.
Args:
scalar (number):
Value to multiply the polynomial by.
ignored_terms (iterable, optional):
Biases associated with these terms are not scaled.
"""
if ignored_terms is None:
ignored_terms = set()
else:
ignored_terms = {asfrozenset(term) for term in ignored_terms}
for term in self:
if term not in ignored_terms:
self[term] *= scalar | [
"def",
"scale",
"(",
"self",
",",
"scalar",
",",
"ignored_terms",
"=",
"None",
")",
":",
"if",
"ignored_terms",
"is",
"None",
":",
"ignored_terms",
"=",
"set",
"(",
")",
"else",
":",
"ignored_terms",
"=",
"{",
"asfrozenset",
"(",
"term",
")",
"for",
"t... | Multiply the polynomial by the given scalar.
Args:
scalar (number):
Value to multiply the polynomial by.
ignored_terms (iterable, optional):
Biases associated with these terms are not scaled. | [
"Multiply",
"the",
"polynomial",
"by",
"the",
"given",
"scalar",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L343-L362 | train | 212,566 |
dwavesystems/dimod | dimod/higherorder/polynomial.py | BinaryPolynomial.from_hising | def from_hising(cls, h, J, offset=None):
"""Construct a binary polynomial from a higher-order Ising problem.
Args:
h (dict):
The linear biases.
J (dict):
The higher-order biases.
offset (optional, default=0.0):
Constant offset applied to the model.
Returns:
:obj:`.BinaryPolynomial`
Examples:
>>> poly = dimod.BinaryPolynomial.from_hising({'a': 2}, {'ab': -1}, 0)
"""
poly = {(k,): v for k, v in h.items()}
poly.update(J)
if offset is not None:
poly[frozenset([])] = offset
return cls(poly, Vartype.SPIN) | python | def from_hising(cls, h, J, offset=None):
"""Construct a binary polynomial from a higher-order Ising problem.
Args:
h (dict):
The linear biases.
J (dict):
The higher-order biases.
offset (optional, default=0.0):
Constant offset applied to the model.
Returns:
:obj:`.BinaryPolynomial`
Examples:
>>> poly = dimod.BinaryPolynomial.from_hising({'a': 2}, {'ab': -1}, 0)
"""
poly = {(k,): v for k, v in h.items()}
poly.update(J)
if offset is not None:
poly[frozenset([])] = offset
return cls(poly, Vartype.SPIN) | [
"def",
"from_hising",
"(",
"cls",
",",
"h",
",",
"J",
",",
"offset",
"=",
"None",
")",
":",
"poly",
"=",
"{",
"(",
"k",
",",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"h",
".",
"items",
"(",
")",
"}",
"poly",
".",
"update",
"(",
"J",
")"... | Construct a binary polynomial from a higher-order Ising problem.
Args:
h (dict):
The linear biases.
J (dict):
The higher-order biases.
offset (optional, default=0.0):
Constant offset applied to the model.
Returns:
:obj:`.BinaryPolynomial`
Examples:
>>> poly = dimod.BinaryPolynomial.from_hising({'a': 2}, {'ab': -1}, 0) | [
"Construct",
"a",
"binary",
"polynomial",
"from",
"a",
"higher",
"-",
"order",
"Ising",
"problem",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L365-L389 | train | 212,567 |
dwavesystems/dimod | dimod/higherorder/polynomial.py | BinaryPolynomial.to_hising | def to_hising(self):
"""Construct a higher-order Ising problem from a binary polynomial.
Returns:
tuple: A 3-tuple of the form (`h`, `J`, `offset`) where `h` includes
the linear biases, `J` has the higher-order biases and `offset` is
the linear offset.
Examples:
>>> poly = dimod.BinaryPolynomial({'a': -1, 'ab': 1, 'abc': -1}, dimod.SPIN)
>>> h, J, off = poly.to_hising()
>>> h
{'a': -1}
"""
if self.vartype is Vartype.BINARY:
return self.to_spin().to_hising()
h = {}
J = {}
offset = 0
for term, bias in self.items():
if len(term) == 0:
offset += bias
elif len(term) == 1:
v, = term
h[v] = bias
else:
J[tuple(term)] = bias
return h, J, offset | python | def to_hising(self):
"""Construct a higher-order Ising problem from a binary polynomial.
Returns:
tuple: A 3-tuple of the form (`h`, `J`, `offset`) where `h` includes
the linear biases, `J` has the higher-order biases and `offset` is
the linear offset.
Examples:
>>> poly = dimod.BinaryPolynomial({'a': -1, 'ab': 1, 'abc': -1}, dimod.SPIN)
>>> h, J, off = poly.to_hising()
>>> h
{'a': -1}
"""
if self.vartype is Vartype.BINARY:
return self.to_spin().to_hising()
h = {}
J = {}
offset = 0
for term, bias in self.items():
if len(term) == 0:
offset += bias
elif len(term) == 1:
v, = term
h[v] = bias
else:
J[tuple(term)] = bias
return h, J, offset | [
"def",
"to_hising",
"(",
"self",
")",
":",
"if",
"self",
".",
"vartype",
"is",
"Vartype",
".",
"BINARY",
":",
"return",
"self",
".",
"to_spin",
"(",
")",
".",
"to_hising",
"(",
")",
"h",
"=",
"{",
"}",
"J",
"=",
"{",
"}",
"offset",
"=",
"0",
"f... | Construct a higher-order Ising problem from a binary polynomial.
Returns:
tuple: A 3-tuple of the form (`h`, `J`, `offset`) where `h` includes
the linear biases, `J` has the higher-order biases and `offset` is
the linear offset.
Examples:
>>> poly = dimod.BinaryPolynomial({'a': -1, 'ab': 1, 'abc': -1}, dimod.SPIN)
>>> h, J, off = poly.to_hising()
>>> h
{'a': -1} | [
"Construct",
"a",
"higher",
"-",
"order",
"Ising",
"problem",
"from",
"a",
"binary",
"polynomial",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/higherorder/polynomial.py#L391-L421 | train | 212,568 |
dwavesystems/dimod | dimod/reference/samplers/simulated_annealing.py | greedy_coloring | def greedy_coloring(adj):
"""Determines a vertex coloring.
Args:
adj (dict): The edge structure of the graph to be colored.
`adj` should be of the form {node: neighbors, ...} where
neighbors is a set.
Returns:
dict: the coloring {node: color, ...}
dict: the colors {color: [node, ...], ...}
Note:
This is a greedy heuristic: the resulting coloring is not
necessarily minimal.
"""
# now let's start coloring
coloring = {}
colors = {}
possible_colors = {n: set(range(len(adj))) for n in adj}
while possible_colors:
# get the n with the fewest possible colors
n = min(possible_colors, key=lambda n: len(possible_colors[n]))
# assign that node the lowest color it can still have
color = min(possible_colors[n])
coloring[n] = color
if color not in colors:
colors[color] = {n}
else:
colors[color].add(n)
# also remove color from the possible colors for n's neighbors
for neighbor in adj[n]:
if neighbor in possible_colors and color in possible_colors[neighbor]:
possible_colors[neighbor].remove(color)
# finally remove n from nodes
del possible_colors[n]
return coloring, colors | python | def greedy_coloring(adj):
"""Determines a vertex coloring.
Args:
adj (dict): The edge structure of the graph to be colored.
`adj` should be of the form {node: neighbors, ...} where
neighbors is a set.
Returns:
dict: the coloring {node: color, ...}
dict: the colors {color: [node, ...], ...}
Note:
This is a greedy heuristic: the resulting coloring is not
necessarily minimal.
"""
# now let's start coloring
coloring = {}
colors = {}
possible_colors = {n: set(range(len(adj))) for n in adj}
while possible_colors:
# get the n with the fewest possible colors
n = min(possible_colors, key=lambda n: len(possible_colors[n]))
# assign that node the lowest color it can still have
color = min(possible_colors[n])
coloring[n] = color
if color not in colors:
colors[color] = {n}
else:
colors[color].add(n)
# also remove color from the possible colors for n's neighbors
for neighbor in adj[n]:
if neighbor in possible_colors and color in possible_colors[neighbor]:
possible_colors[neighbor].remove(color)
# finally remove n from nodes
del possible_colors[n]
return coloring, colors | [
"def",
"greedy_coloring",
"(",
"adj",
")",
":",
"# now let's start coloring",
"coloring",
"=",
"{",
"}",
"colors",
"=",
"{",
"}",
"possible_colors",
"=",
"{",
"n",
":",
"set",
"(",
"range",
"(",
"len",
"(",
"adj",
")",
")",
")",
"for",
"n",
"in",
"ad... | Determines a vertex coloring.
Args:
adj (dict): The edge structure of the graph to be colored.
`adj` should be of the form {node: neighbors, ...} where
neighbors is a set.
Returns:
dict: the coloring {node: color, ...}
dict: the colors {color: [node, ...], ...}
Note:
This is a greedy heuristic: the resulting coloring is not
necessarily minimal. | [
"Determines",
"a",
"vertex",
"coloring",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/samplers/simulated_annealing.py#L230-L273 | train | 212,569 |
dwavesystems/dimod | dimod/reference/samplers/simulated_annealing.py | SimulatedAnnealingSampler.sample | def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000):
"""Sample from low-energy spin states using simulated annealing.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
beta_range (tuple, optional): Beginning and end of the beta schedule
(beta is the inverse temperature) as a 2-tuple. The schedule is applied
linearly in beta. Default is chosen based on the total bias associated
with each node.
num_reads (int, optional, default=10):
Number of reads. Each sample is the result of a single run of
the simulated annealing algorithm.
num_sweeps (int, optional, default=1000):
Number of sweeps or steps.
Returns:
:obj:`.SampleSet`
Note:
This is a reference implementation, not optimized for speed
and therefore not an appropriate sampler for benchmarking.
"""
# input checking
# h, J are handled by the @ising decorator
# beta_range, sweeps are handled by ising_simulated_annealing
if not isinstance(num_reads, int):
raise TypeError("'samples' should be a positive integer")
if num_reads < 1:
raise ValueError("'samples' should be a positive integer")
h, J, offset = bqm.to_ising()
# run the simulated annealing algorithm
samples = []
energies = []
for __ in range(num_reads):
sample, energy = ising_simulated_annealing(h, J, beta_range, num_sweeps)
samples.append(sample)
energies.append(energy)
response = SampleSet.from_samples(samples, Vartype.SPIN, energies)
response.change_vartype(bqm.vartype, offset, inplace=True)
return response | python | def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000):
"""Sample from low-energy spin states using simulated annealing.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
beta_range (tuple, optional): Beginning and end of the beta schedule
(beta is the inverse temperature) as a 2-tuple. The schedule is applied
linearly in beta. Default is chosen based on the total bias associated
with each node.
num_reads (int, optional, default=10):
Number of reads. Each sample is the result of a single run of
the simulated annealing algorithm.
num_sweeps (int, optional, default=1000):
Number of sweeps or steps.
Returns:
:obj:`.SampleSet`
Note:
This is a reference implementation, not optimized for speed
and therefore not an appropriate sampler for benchmarking.
"""
# input checking
# h, J are handled by the @ising decorator
# beta_range, sweeps are handled by ising_simulated_annealing
if not isinstance(num_reads, int):
raise TypeError("'samples' should be a positive integer")
if num_reads < 1:
raise ValueError("'samples' should be a positive integer")
h, J, offset = bqm.to_ising()
# run the simulated annealing algorithm
samples = []
energies = []
for __ in range(num_reads):
sample, energy = ising_simulated_annealing(h, J, beta_range, num_sweeps)
samples.append(sample)
energies.append(energy)
response = SampleSet.from_samples(samples, Vartype.SPIN, energies)
response.change_vartype(bqm.vartype, offset, inplace=True)
return response | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"beta_range",
"=",
"None",
",",
"num_reads",
"=",
"10",
",",
"num_sweeps",
"=",
"1000",
")",
":",
"# input checking",
"# h, J are handled by the @ising decorator",
"# beta_range, sweeps are handled by ising_simulated_annealin... | Sample from low-energy spin states using simulated annealing.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
beta_range (tuple, optional): Beginning and end of the beta schedule
(beta is the inverse temperature) as a 2-tuple. The schedule is applied
linearly in beta. Default is chosen based on the total bias associated
with each node.
num_reads (int, optional, default=10):
Number of reads. Each sample is the result of a single run of
the simulated annealing algorithm.
num_sweeps (int, optional, default=1000):
Number of sweeps or steps.
Returns:
:obj:`.SampleSet`
Note:
This is a reference implementation, not optimized for speed
and therefore not an appropriate sampler for benchmarking. | [
"Sample",
"from",
"low",
"-",
"energy",
"spin",
"states",
"using",
"simulated",
"annealing",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/samplers/simulated_annealing.py#L61-L109 | train | 212,570 |
dwavesystems/dimod | dimod/reference/composites/scalecomposite.py | _scale_back_response | def _scale_back_response(bqm, response, scalar, ignored_interactions,
ignored_variables, ignore_offset):
"""Helper function to scale back the response of sample method"""
if len(ignored_interactions) + len(
ignored_variables) + ignore_offset == 0:
response.record.energy = np.divide(response.record.energy, scalar)
else:
response.record.energy = bqm.energies((response.record.sample,
response.variables))
return response | python | def _scale_back_response(bqm, response, scalar, ignored_interactions,
ignored_variables, ignore_offset):
"""Helper function to scale back the response of sample method"""
if len(ignored_interactions) + len(
ignored_variables) + ignore_offset == 0:
response.record.energy = np.divide(response.record.energy, scalar)
else:
response.record.energy = bqm.energies((response.record.sample,
response.variables))
return response | [
"def",
"_scale_back_response",
"(",
"bqm",
",",
"response",
",",
"scalar",
",",
"ignored_interactions",
",",
"ignored_variables",
",",
"ignore_offset",
")",
":",
"if",
"len",
"(",
"ignored_interactions",
")",
"+",
"len",
"(",
"ignored_variables",
")",
"+",
"igno... | Helper function to scale back the response of sample method | [
"Helper",
"function",
"to",
"scale",
"back",
"the",
"response",
"of",
"sample",
"method"
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L213-L222 | train | 212,571 |
dwavesystems/dimod | dimod/reference/composites/scalecomposite.py | _check_params | def _check_params(ignored_variables, ignored_interactions):
"""Helper for sample methods"""
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
ignored_interactions = set()
elif not isinstance(ignored_interactions, abc.Container):
ignored_interactions = set(ignored_interactions)
return ignored_variables, ignored_interactions | python | def _check_params(ignored_variables, ignored_interactions):
"""Helper for sample methods"""
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
ignored_interactions = set()
elif not isinstance(ignored_interactions, abc.Container):
ignored_interactions = set(ignored_interactions)
return ignored_variables, ignored_interactions | [
"def",
"_check_params",
"(",
"ignored_variables",
",",
"ignored_interactions",
")",
":",
"if",
"ignored_variables",
"is",
"None",
":",
"ignored_variables",
"=",
"set",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"ignored_variables",
",",
"abc",
".",
"Container",
... | Helper for sample methods | [
"Helper",
"for",
"sample",
"methods"
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L225-L238 | train | 212,572 |
dwavesystems/dimod | dimod/reference/composites/scalecomposite.py | _calc_norm_coeff | def _calc_norm_coeff(h, J, bias_range, quadratic_range, ignored_variables,
ignored_interactions):
"""Helper function to calculate normalization coefficient"""
if ignored_variables is None or ignored_interactions is None:
raise ValueError('ignored interactions or variables cannot be None')
def parse_range(r):
if isinstance(r, Number):
return -abs(r), abs(r)
return r
def min_and_max(iterable):
if not iterable:
return 0, 0
return min(iterable), max(iterable)
if quadratic_range is None:
linear_range, quadratic_range = bias_range, bias_range
else:
linear_range = bias_range
lin_range, quad_range = map(parse_range, (linear_range,
quadratic_range))
lin_min, lin_max = min_and_max([v for k, v in h.items()
if k not in ignored_variables])
quad_min, quad_max = min_and_max([v for k, v in J.items()
if not check_isin(k,
ignored_interactions)])
inv_scalar = max(lin_min / lin_range[0], lin_max / lin_range[1],
quad_min / quad_range[0], quad_max / quad_range[1])
if inv_scalar != 0:
return 1. / inv_scalar
else:
return 1. | python | def _calc_norm_coeff(h, J, bias_range, quadratic_range, ignored_variables,
ignored_interactions):
"""Helper function to calculate normalization coefficient"""
if ignored_variables is None or ignored_interactions is None:
raise ValueError('ignored interactions or variables cannot be None')
def parse_range(r):
if isinstance(r, Number):
return -abs(r), abs(r)
return r
def min_and_max(iterable):
if not iterable:
return 0, 0
return min(iterable), max(iterable)
if quadratic_range is None:
linear_range, quadratic_range = bias_range, bias_range
else:
linear_range = bias_range
lin_range, quad_range = map(parse_range, (linear_range,
quadratic_range))
lin_min, lin_max = min_and_max([v for k, v in h.items()
if k not in ignored_variables])
quad_min, quad_max = min_and_max([v for k, v in J.items()
if not check_isin(k,
ignored_interactions)])
inv_scalar = max(lin_min / lin_range[0], lin_max / lin_range[1],
quad_min / quad_range[0], quad_max / quad_range[1])
if inv_scalar != 0:
return 1. / inv_scalar
else:
return 1. | [
"def",
"_calc_norm_coeff",
"(",
"h",
",",
"J",
",",
"bias_range",
",",
"quadratic_range",
",",
"ignored_variables",
",",
"ignored_interactions",
")",
":",
"if",
"ignored_variables",
"is",
"None",
"or",
"ignored_interactions",
"is",
"None",
":",
"raise",
"ValueErro... | Helper function to calculate normalization coefficient | [
"Helper",
"function",
"to",
"calculate",
"normalization",
"coefficient"
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L241-L278 | train | 212,573 |
dwavesystems/dimod | dimod/reference/composites/scalecomposite.py | _scaled_bqm | def _scaled_bqm(bqm, scalar, bias_range, quadratic_range,
ignored_variables, ignored_interactions,
ignore_offset):
"""Helper function of sample for scaling"""
bqm_copy = bqm.copy()
if scalar is None:
scalar = _calc_norm_coeff(bqm_copy.linear, bqm_copy.quadratic,
bias_range, quadratic_range,
ignored_variables, ignored_interactions)
bqm_copy.scale(scalar, ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions,
ignore_offset=ignore_offset)
bqm_copy.info.update({'scalar': scalar})
return bqm_copy | python | def _scaled_bqm(bqm, scalar, bias_range, quadratic_range,
ignored_variables, ignored_interactions,
ignore_offset):
"""Helper function of sample for scaling"""
bqm_copy = bqm.copy()
if scalar is None:
scalar = _calc_norm_coeff(bqm_copy.linear, bqm_copy.quadratic,
bias_range, quadratic_range,
ignored_variables, ignored_interactions)
bqm_copy.scale(scalar, ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions,
ignore_offset=ignore_offset)
bqm_copy.info.update({'scalar': scalar})
return bqm_copy | [
"def",
"_scaled_bqm",
"(",
"bqm",
",",
"scalar",
",",
"bias_range",
",",
"quadratic_range",
",",
"ignored_variables",
",",
"ignored_interactions",
",",
"ignore_offset",
")",
":",
"bqm_copy",
"=",
"bqm",
".",
"copy",
"(",
")",
"if",
"scalar",
"is",
"None",
":... | Helper function of sample for scaling | [
"Helper",
"function",
"of",
"sample",
"for",
"scaling"
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L281-L296 | train | 212,574 |
dwavesystems/dimod | dimod/reference/composites/scalecomposite.py | ScaleComposite.sample | def sample(self, bqm, scalar=None, bias_range=1, quadratic_range=None,
ignored_variables=None, ignored_interactions=None,
ignore_offset=False, **parameters):
""" Scale and sample from the provided binary quadratic model.
if scalar is not given, problem is scaled based on bias and quadratic
ranges. See :meth:`.BinaryQuadraticModel.scale` and
:meth:`.BinaryQuadraticModel.normalize`
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
**parameters:
Parameters for the sampling method, specified by the child sampler.
Returns:
:obj:`dimod.SampleSet`
"""
ignored_variables, ignored_interactions = _check_params(
ignored_variables, ignored_interactions)
child = self.child
bqm_copy = _scaled_bqm(bqm, scalar, bias_range, quadratic_range,
ignored_variables, ignored_interactions,
ignore_offset)
response = child.sample(bqm_copy, **parameters)
return _scale_back_response(bqm, response, bqm_copy.info['scalar'],
ignored_variables, ignored_interactions,
ignore_offset) | python | def sample(self, bqm, scalar=None, bias_range=1, quadratic_range=None,
ignored_variables=None, ignored_interactions=None,
ignore_offset=False, **parameters):
""" Scale and sample from the provided binary quadratic model.
if scalar is not given, problem is scaled based on bias and quadratic
ranges. See :meth:`.BinaryQuadraticModel.scale` and
:meth:`.BinaryQuadraticModel.normalize`
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
**parameters:
Parameters for the sampling method, specified by the child sampler.
Returns:
:obj:`dimod.SampleSet`
"""
ignored_variables, ignored_interactions = _check_params(
ignored_variables, ignored_interactions)
child = self.child
bqm_copy = _scaled_bqm(bqm, scalar, bias_range, quadratic_range,
ignored_variables, ignored_interactions,
ignore_offset)
response = child.sample(bqm_copy, **parameters)
return _scale_back_response(bqm, response, bqm_copy.info['scalar'],
ignored_variables, ignored_interactions,
ignore_offset) | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"scalar",
"=",
"None",
",",
"bias_range",
"=",
"1",
",",
"quadratic_range",
"=",
"None",
",",
"ignored_variables",
"=",
"None",
",",
"ignored_interactions",
"=",
"None",
",",
"ignore_offset",
"=",
"False",
","... | Scale and sample from the provided binary quadratic model.
if scalar is not given, problem is scaled based on bias and quadratic
ranges. See :meth:`.BinaryQuadraticModel.scale` and
:meth:`.BinaryQuadraticModel.normalize`
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
**parameters:
Parameters for the sampling method, specified by the child sampler.
Returns:
:obj:`dimod.SampleSet` | [
"Scale",
"and",
"sample",
"from",
"the",
"provided",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L82-L132 | train | 212,575 |
dwavesystems/dimod | dimod/reference/composites/scalecomposite.py | ScaleComposite.sample_ising | def sample_ising(self, h, J, offset=0, scalar=None,
bias_range=1, quadratic_range=None,
ignored_variables=None, ignored_interactions=None,
ignore_offset=False, **parameters):
""" Scale and sample from the problem provided by h, J, offset
if scalar is not given, problem is scaled based on bias and quadratic
ranges.
Args:
h (dict): linear biases
J (dict): quadratic or higher order biases
offset (float, optional): constant energy offset
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
**parameters:
Parameters for the sampling method, specified by the child sampler.
Returns:
:obj:`dimod.SampleSet`
"""
if any(len(inter) > 2 for inter in J):
# handle HUBO
import warnings
msg = ("Support for higher order Ising models in ScaleComposite is "
"deprecated and will be removed in dimod 0.9.0. Please use "
"PolyScaleComposite.sample_hising instead.")
warnings.warn(msg, DeprecationWarning)
from dimod.reference.composites.higherordercomposites import PolyScaleComposite
from dimod.higherorder.polynomial import BinaryPolynomial
poly = BinaryPolynomial.from_hising(h, J, offset=offset)
ignored_terms = set()
if ignored_variables is not None:
ignored_terms.update(frozenset(v) for v in ignored_variables)
if ignored_interactions is not None:
ignored_terms.update(frozenset(inter) for inter in ignored_interactions)
if ignore_offset:
ignored_terms.add(frozenset())
return PolyScaleComposite(self.child).sample_poly(poly, scalar=scalar,
bias_range=bias_range,
poly_range=quadratic_range,
ignored_terms=ignored_terms,
**parameters)
bqm = BinaryQuadraticModel.from_ising(h, J, offset=offset)
return self.sample(bqm, scalar=scalar,
bias_range=bias_range,
quadratic_range=quadratic_range,
ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions,
ignore_offset=ignore_offset, **parameters) | python | def sample_ising(self, h, J, offset=0, scalar=None,
bias_range=1, quadratic_range=None,
ignored_variables=None, ignored_interactions=None,
ignore_offset=False, **parameters):
""" Scale and sample from the problem provided by h, J, offset
if scalar is not given, problem is scaled based on bias and quadratic
ranges.
Args:
h (dict): linear biases
J (dict): quadratic or higher order biases
offset (float, optional): constant energy offset
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
**parameters:
Parameters for the sampling method, specified by the child sampler.
Returns:
:obj:`dimod.SampleSet`
"""
if any(len(inter) > 2 for inter in J):
# handle HUBO
import warnings
msg = ("Support for higher order Ising models in ScaleComposite is "
"deprecated and will be removed in dimod 0.9.0. Please use "
"PolyScaleComposite.sample_hising instead.")
warnings.warn(msg, DeprecationWarning)
from dimod.reference.composites.higherordercomposites import PolyScaleComposite
from dimod.higherorder.polynomial import BinaryPolynomial
poly = BinaryPolynomial.from_hising(h, J, offset=offset)
ignored_terms = set()
if ignored_variables is not None:
ignored_terms.update(frozenset(v) for v in ignored_variables)
if ignored_interactions is not None:
ignored_terms.update(frozenset(inter) for inter in ignored_interactions)
if ignore_offset:
ignored_terms.add(frozenset())
return PolyScaleComposite(self.child).sample_poly(poly, scalar=scalar,
bias_range=bias_range,
poly_range=quadratic_range,
ignored_terms=ignored_terms,
**parameters)
bqm = BinaryQuadraticModel.from_ising(h, J, offset=offset)
return self.sample(bqm, scalar=scalar,
bias_range=bias_range,
quadratic_range=quadratic_range,
ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions,
ignore_offset=ignore_offset, **parameters) | [
"def",
"sample_ising",
"(",
"self",
",",
"h",
",",
"J",
",",
"offset",
"=",
"0",
",",
"scalar",
"=",
"None",
",",
"bias_range",
"=",
"1",
",",
"quadratic_range",
"=",
"None",
",",
"ignored_variables",
"=",
"None",
",",
"ignored_interactions",
"=",
"None"... | Scale and sample from the problem provided by h, J, offset
if scalar is not given, problem is scaled based on bias and quadratic
ranges.
Args:
h (dict): linear biases
J (dict): quadratic or higher order biases
offset (float, optional): constant energy offset
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
**parameters:
Parameters for the sampling method, specified by the child sampler.
Returns:
:obj:`dimod.SampleSet` | [
"Scale",
"and",
"sample",
"from",
"the",
"problem",
"provided",
"by",
"h",
"J",
"offset"
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L134-L210 | train | 212,576 |
dwavesystems/dimod | dimod/generators/chimera.py | chimera_anticluster | def chimera_anticluster(m, n=None, t=4, multiplier=3.0,
cls=BinaryQuadraticModel, subgraph=None, seed=None):
"""Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
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=t):
Size of the shore within each Chimera tile.
multiplier (number, optional, default=3.0):
Strength of the intertile edges.
cls (class, optional, default=:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
subgraph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
A subgraph of a Chimera(m, n, t) graph to build the anticluster
problem on.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`: spin-valued binary quadratic model.
"""
if seed is None:
seed = numpy.random.randint(2**32, dtype=np.uint32)
r = numpy.random.RandomState(seed)
m = int(m)
if n is None:
n = m
else:
n = int(n)
t = int(t)
ldata = np.zeros(m*n*t*2) # number of nodes
if m and n and t:
inrow, incol = zip(*_iter_chimera_tile_edges(m, n, t))
if m > 1 or n > 1:
outrow, outcol = zip(*_iter_chimera_intertile_edges(m, n, t))
else:
outrow = outcol = tuple()
qdata = r.choice((-1., 1.), size=len(inrow)+len(outrow))
qdata[len(inrow):] *= multiplier
irow = inrow + outrow
icol = incol + outcol
else:
irow = icol = qdata = tuple()
bqm = cls.from_numpy_vectors(ldata, (irow, icol, qdata), 0.0, SPIN)
if subgraph is not None:
nodes, edges = subgraph
subbqm = cls.empty(SPIN)
try:
subbqm.add_variables_from((v, bqm.linear[v]) for v in nodes)
except KeyError:
msg = "given 'subgraph' contains nodes not in Chimera({}, {}, {})".format(m, n, t)
raise ValueError(msg)
try:
subbqm.add_interactions_from((u, v, bqm.adj[u][v]) for u, v in edges)
except KeyError:
msg = "given 'subgraph' contains edges not in Chimera({}, {}, {})".format(m, n, t)
raise ValueError(msg)
bqm = subbqm
return bqm | python | def chimera_anticluster(m, n=None, t=4, multiplier=3.0,
cls=BinaryQuadraticModel, subgraph=None, seed=None):
"""Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
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=t):
Size of the shore within each Chimera tile.
multiplier (number, optional, default=3.0):
Strength of the intertile edges.
cls (class, optional, default=:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
subgraph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
A subgraph of a Chimera(m, n, t) graph to build the anticluster
problem on.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`: spin-valued binary quadratic model.
"""
if seed is None:
seed = numpy.random.randint(2**32, dtype=np.uint32)
r = numpy.random.RandomState(seed)
m = int(m)
if n is None:
n = m
else:
n = int(n)
t = int(t)
ldata = np.zeros(m*n*t*2) # number of nodes
if m and n and t:
inrow, incol = zip(*_iter_chimera_tile_edges(m, n, t))
if m > 1 or n > 1:
outrow, outcol = zip(*_iter_chimera_intertile_edges(m, n, t))
else:
outrow = outcol = tuple()
qdata = r.choice((-1., 1.), size=len(inrow)+len(outrow))
qdata[len(inrow):] *= multiplier
irow = inrow + outrow
icol = incol + outcol
else:
irow = icol = qdata = tuple()
bqm = cls.from_numpy_vectors(ldata, (irow, icol, qdata), 0.0, SPIN)
if subgraph is not None:
nodes, edges = subgraph
subbqm = cls.empty(SPIN)
try:
subbqm.add_variables_from((v, bqm.linear[v]) for v in nodes)
except KeyError:
msg = "given 'subgraph' contains nodes not in Chimera({}, {}, {})".format(m, n, t)
raise ValueError(msg)
try:
subbqm.add_interactions_from((u, v, bqm.adj[u][v]) for u, v in edges)
except KeyError:
msg = "given 'subgraph' contains edges not in Chimera({}, {}, {})".format(m, n, t)
raise ValueError(msg)
bqm = subbqm
return bqm | [
"def",
"chimera_anticluster",
"(",
"m",
",",
"n",
"=",
"None",
",",
"t",
"=",
"4",
",",
"multiplier",
"=",
"3.0",
",",
"cls",
"=",
"BinaryQuadraticModel",
",",
"subgraph",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"None",
... | Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
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=t):
Size of the shore within each Chimera tile.
multiplier (number, optional, default=3.0):
Strength of the intertile edges.
cls (class, optional, default=:class:`.BinaryQuadraticModel`):
Binary quadratic model class to build from.
subgraph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`):
A subgraph of a Chimera(m, n, t) graph to build the anticluster
problem on.
seed (int, optional, default=None):
Random seed.
Returns:
:obj:`.BinaryQuadraticModel`: spin-valued binary quadratic model. | [
"Generate",
"an",
"anticluster",
"problem",
"on",
"a",
"Chimera",
"lattice",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/generators/chimera.py#L29-L116 | train | 212,577 |
dwavesystems/dimod | dimod/serialization/coo.py | dump | def dump(bqm, fp, vartype_header=False):
"""Dump a binary quadratic model to a string in COOrdinate format."""
for triplet in _iter_triplets(bqm, vartype_header):
fp.write('%s\n' % triplet) | python | def dump(bqm, fp, vartype_header=False):
"""Dump a binary quadratic model to a string in COOrdinate format."""
for triplet in _iter_triplets(bqm, vartype_header):
fp.write('%s\n' % triplet) | [
"def",
"dump",
"(",
"bqm",
",",
"fp",
",",
"vartype_header",
"=",
"False",
")",
":",
"for",
"triplet",
"in",
"_iter_triplets",
"(",
"bqm",
",",
"vartype_header",
")",
":",
"fp",
".",
"write",
"(",
"'%s\\n'",
"%",
"triplet",
")"
] | Dump a binary quadratic model to a string in COOrdinate format. | [
"Dump",
"a",
"binary",
"quadratic",
"model",
"to",
"a",
"string",
"in",
"COOrdinate",
"format",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/serialization/coo.py#L44-L47 | train | 212,578 |
dwavesystems/dimod | dimod/serialization/coo.py | loads | def loads(s, cls=BinaryQuadraticModel, vartype=None):
"""Load a COOrdinate formatted binary quadratic model from a string."""
return load(s.split('\n'), cls=cls, vartype=vartype) | python | def loads(s, cls=BinaryQuadraticModel, vartype=None):
"""Load a COOrdinate formatted binary quadratic model from a string."""
return load(s.split('\n'), cls=cls, vartype=vartype) | [
"def",
"loads",
"(",
"s",
",",
"cls",
"=",
"BinaryQuadraticModel",
",",
"vartype",
"=",
"None",
")",
":",
"return",
"load",
"(",
"s",
".",
"split",
"(",
"'\\n'",
")",
",",
"cls",
"=",
"cls",
",",
"vartype",
"=",
"vartype",
")"
] | Load a COOrdinate formatted binary quadratic model from a string. | [
"Load",
"a",
"COOrdinate",
"formatted",
"binary",
"quadratic",
"model",
"from",
"a",
"string",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/serialization/coo.py#L50-L52 | train | 212,579 |
dwavesystems/dimod | dimod/serialization/coo.py | load | def load(fp, cls=BinaryQuadraticModel, vartype=None):
"""Load a COOrdinate formatted binary quadratic model from a file."""
pattern = re.compile(_LINE_REGEX)
vartype_pattern = re.compile(_VARTYPE_HEADER_REGEX)
triplets = []
for line in fp:
triplets.extend(pattern.findall(line))
vt = vartype_pattern.findall(line)
if vt:
if vartype is None:
vartype = vt[0]
else:
if isinstance(vartype, str):
vartype = Vartype[vartype]
else:
vartype = Vartype(vartype)
if Vartype[vt[0]] != vartype:
raise ValueError("vartypes from headers and/or inputs do not match")
if vartype is None:
raise ValueError("vartype must be provided either as a header or as an argument")
bqm = cls.empty(vartype)
for u, v, bias in triplets:
if u == v:
bqm.add_variable(int(u), float(bias))
else:
bqm.add_interaction(int(u), int(v), float(bias))
return bqm | python | def load(fp, cls=BinaryQuadraticModel, vartype=None):
"""Load a COOrdinate formatted binary quadratic model from a file."""
pattern = re.compile(_LINE_REGEX)
vartype_pattern = re.compile(_VARTYPE_HEADER_REGEX)
triplets = []
for line in fp:
triplets.extend(pattern.findall(line))
vt = vartype_pattern.findall(line)
if vt:
if vartype is None:
vartype = vt[0]
else:
if isinstance(vartype, str):
vartype = Vartype[vartype]
else:
vartype = Vartype(vartype)
if Vartype[vt[0]] != vartype:
raise ValueError("vartypes from headers and/or inputs do not match")
if vartype is None:
raise ValueError("vartype must be provided either as a header or as an argument")
bqm = cls.empty(vartype)
for u, v, bias in triplets:
if u == v:
bqm.add_variable(int(u), float(bias))
else:
bqm.add_interaction(int(u), int(v), float(bias))
return bqm | [
"def",
"load",
"(",
"fp",
",",
"cls",
"=",
"BinaryQuadraticModel",
",",
"vartype",
"=",
"None",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"_LINE_REGEX",
")",
"vartype_pattern",
"=",
"re",
".",
"compile",
"(",
"_VARTYPE_HEADER_REGEX",
")",
"tripl... | Load a COOrdinate formatted binary quadratic model from a file. | [
"Load",
"a",
"COOrdinate",
"formatted",
"binary",
"quadratic",
"model",
"from",
"a",
"file",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/serialization/coo.py#L55-L87 | train | 212,580 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.remove_variable | def remove_variable(self, v):
"""Remove variable v and all its interactions from a binary quadratic model.
Args:
v (variable):
The variable to be removed from the binary quadratic model.
Notes:
If the specified variable is not in the binary quadratic model, this function does nothing.
Examples:
This example creates an Ising model and then removes one variable.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': 1.0, 'c': 2.0},
... {('a', 'b'): 0.25, ('a','c'): 0.5, ('b','c'): 0.75},
... -0.5, dimod.SPIN)
>>> bqm.remove_variable('a')
>>> 'a' in bqm.linear
False
>>> ('b','c') in bqm.quadratic
True
"""
if v not in self:
return
adj = self.adj
# first remove all the interactions associated with v
while adj[v]:
self.remove_interaction(v, next(iter(adj[v])))
# remove the variable
del self.linear[v]
try:
# invalidates counterpart
del self._counterpart
if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):
del self._binary
elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):
del self._spin
except AttributeError:
pass | python | def remove_variable(self, v):
"""Remove variable v and all its interactions from a binary quadratic model.
Args:
v (variable):
The variable to be removed from the binary quadratic model.
Notes:
If the specified variable is not in the binary quadratic model, this function does nothing.
Examples:
This example creates an Ising model and then removes one variable.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': 1.0, 'c': 2.0},
... {('a', 'b'): 0.25, ('a','c'): 0.5, ('b','c'): 0.75},
... -0.5, dimod.SPIN)
>>> bqm.remove_variable('a')
>>> 'a' in bqm.linear
False
>>> ('b','c') in bqm.quadratic
True
"""
if v not in self:
return
adj = self.adj
# first remove all the interactions associated with v
while adj[v]:
self.remove_interaction(v, next(iter(adj[v])))
# remove the variable
del self.linear[v]
try:
# invalidates counterpart
del self._counterpart
if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):
del self._binary
elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):
del self._spin
except AttributeError:
pass | [
"def",
"remove_variable",
"(",
"self",
",",
"v",
")",
":",
"if",
"v",
"not",
"in",
"self",
":",
"return",
"adj",
"=",
"self",
".",
"adj",
"# first remove all the interactions associated with v",
"while",
"adj",
"[",
"v",
"]",
":",
"self",
".",
"remove_intera... | Remove variable v and all its interactions from a binary quadratic model.
Args:
v (variable):
The variable to be removed from the binary quadratic model.
Notes:
If the specified variable is not in the binary quadratic model, this function does nothing.
Examples:
This example creates an Ising model and then removes one variable.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': 1.0, 'c': 2.0},
... {('a', 'b'): 0.25, ('a','c'): 0.5, ('b','c'): 0.75},
... -0.5, dimod.SPIN)
>>> bqm.remove_variable('a')
>>> 'a' in bqm.linear
False
>>> ('b','c') in bqm.quadratic
True | [
"Remove",
"variable",
"v",
"and",
"all",
"its",
"interactions",
"from",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L636-L681 | train | 212,581 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.remove_interaction | def remove_interaction(self, u, v):
"""Remove interaction of variables u, v from a binary quadratic model.
Args:
u (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
v (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interaction('b', 'c')
>>> ('b', 'c') in bqm.quadratic
False
>>> bqm.remove_interaction('a', 'c') # not an interaction, so ignored
>>> len(bqm.quadratic)
1
"""
try:
del self.quadratic[(u, v)]
except KeyError:
return # no interaction with that name
try:
# invalidates counterpart
del self._counterpart
if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):
del self._binary
elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):
del self._spin
except AttributeError:
pass | python | def remove_interaction(self, u, v):
"""Remove interaction of variables u, v from a binary quadratic model.
Args:
u (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
v (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interaction('b', 'c')
>>> ('b', 'c') in bqm.quadratic
False
>>> bqm.remove_interaction('a', 'c') # not an interaction, so ignored
>>> len(bqm.quadratic)
1
"""
try:
del self.quadratic[(u, v)]
except KeyError:
return # no interaction with that name
try:
# invalidates counterpart
del self._counterpart
if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):
del self._binary
elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):
del self._spin
except AttributeError:
pass | [
"def",
"remove_interaction",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"try",
":",
"del",
"self",
".",
"quadratic",
"[",
"(",
"u",
",",
"v",
")",
"]",
"except",
"KeyError",
":",
"return",
"# no interaction with that name",
"try",
":",
"# invalidates count... | Remove interaction of variables u, v from a binary quadratic model.
Args:
u (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
v (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interaction('b', 'c')
>>> ('b', 'c') in bqm.quadratic
False
>>> bqm.remove_interaction('a', 'c') # not an interaction, so ignored
>>> len(bqm.quadratic)
1 | [
"Remove",
"interaction",
"of",
"variables",
"u",
"v",
"from",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L710-L754 | train | 212,582 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.remove_interactions_from | def remove_interactions_from(self, interactions):
"""Remove all specified interactions from the binary quadratic model.
Args:
interactions (iterable[[variable, variable]]):
A collection of interactions. Each interaction should be a 2-tuple of variables
in the binary quadratic model.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interactions_from([('b', 'c'), ('a', 'c')]) # ('a', 'c') is not an interaction, so ignored
>>> len(bqm.quadratic)
1
"""
for u, v in interactions:
self.remove_interaction(u, v) | python | def remove_interactions_from(self, interactions):
"""Remove all specified interactions from the binary quadratic model.
Args:
interactions (iterable[[variable, variable]]):
A collection of interactions. Each interaction should be a 2-tuple of variables
in the binary quadratic model.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interactions_from([('b', 'c'), ('a', 'c')]) # ('a', 'c') is not an interaction, so ignored
>>> len(bqm.quadratic)
1
"""
for u, v in interactions:
self.remove_interaction(u, v) | [
"def",
"remove_interactions_from",
"(",
"self",
",",
"interactions",
")",
":",
"for",
"u",
",",
"v",
"in",
"interactions",
":",
"self",
".",
"remove_interaction",
"(",
"u",
",",
"v",
")"
] | Remove all specified interactions from the binary quadratic model.
Args:
interactions (iterable[[variable, variable]]):
A collection of interactions. Each interaction should be a 2-tuple of variables
in the binary quadratic model.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interactions_from([('b', 'c'), ('a', 'c')]) # ('a', 'c') is not an interaction, so ignored
>>> len(bqm.quadratic)
1 | [
"Remove",
"all",
"specified",
"interactions",
"from",
"the",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L756-L780 | train | 212,583 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.add_offset | def add_offset(self, offset):
"""Add specified value to the offset of a binary quadratic model.
Args:
offset (number):
Value to be added to the constant energy offset of the binary quadratic model.
Examples:
This example creates an Ising model with an offset of -0.5 and then
adds to it.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> bqm.add_offset(1.0)
>>> bqm.offset
0.5
"""
self.offset += offset
try:
self._counterpart.add_offset(offset)
except AttributeError:
pass | python | def add_offset(self, offset):
"""Add specified value to the offset of a binary quadratic model.
Args:
offset (number):
Value to be added to the constant energy offset of the binary quadratic model.
Examples:
This example creates an Ising model with an offset of -0.5 and then
adds to it.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> bqm.add_offset(1.0)
>>> bqm.offset
0.5
"""
self.offset += offset
try:
self._counterpart.add_offset(offset)
except AttributeError:
pass | [
"def",
"add_offset",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"offset",
"+=",
"offset",
"try",
":",
"self",
".",
"_counterpart",
".",
"add_offset",
"(",
"offset",
")",
"except",
"AttributeError",
":",
"pass"
] | Add specified value to the offset of a binary quadratic model.
Args:
offset (number):
Value to be added to the constant energy offset of the binary quadratic model.
Examples:
This example creates an Ising model with an offset of -0.5 and then
adds to it.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> bqm.add_offset(1.0)
>>> bqm.offset
0.5 | [
"Add",
"specified",
"value",
"to",
"the",
"offset",
"of",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L782-L807 | train | 212,584 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.scale | def scale(self, scalar, ignored_variables=None, ignored_interactions=None,
ignore_offset=False):
"""Multiply by the specified scalar all the biases and offset of a binary quadratic model.
Args:
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
Examples:
This example creates a binary quadratic model and then scales it to half
the original energy range.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 2.0}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN)
>>> bqm.scale(0.5)
>>> bqm.linear['a']
-1.0
>>> bqm.quadratic[('a', 'b')]
-0.5
>>> bqm.offset
0.5
"""
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
ignored_interactions = set()
elif not isinstance(ignored_interactions, abc.Container):
ignored_interactions = set(ignored_interactions)
linear = self.linear
for v in linear:
if v in ignored_variables:
continue
linear[v] *= scalar
quadratic = self.quadratic
for u, v in quadratic:
if (u, v) in ignored_interactions or (v, u) in ignored_interactions:
continue
quadratic[(u, v)] *= scalar
if not ignore_offset:
self.offset *= scalar
try:
self._counterpart.scale(scalar, ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions)
except AttributeError:
pass | python | def scale(self, scalar, ignored_variables=None, ignored_interactions=None,
ignore_offset=False):
"""Multiply by the specified scalar all the biases and offset of a binary quadratic model.
Args:
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
Examples:
This example creates a binary quadratic model and then scales it to half
the original energy range.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 2.0}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN)
>>> bqm.scale(0.5)
>>> bqm.linear['a']
-1.0
>>> bqm.quadratic[('a', 'b')]
-0.5
>>> bqm.offset
0.5
"""
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
ignored_interactions = set()
elif not isinstance(ignored_interactions, abc.Container):
ignored_interactions = set(ignored_interactions)
linear = self.linear
for v in linear:
if v in ignored_variables:
continue
linear[v] *= scalar
quadratic = self.quadratic
for u, v in quadratic:
if (u, v) in ignored_interactions or (v, u) in ignored_interactions:
continue
quadratic[(u, v)] *= scalar
if not ignore_offset:
self.offset *= scalar
try:
self._counterpart.scale(scalar, ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions)
except AttributeError:
pass | [
"def",
"scale",
"(",
"self",
",",
"scalar",
",",
"ignored_variables",
"=",
"None",
",",
"ignored_interactions",
"=",
"None",
",",
"ignore_offset",
"=",
"False",
")",
":",
"if",
"ignored_variables",
"is",
"None",
":",
"ignored_variables",
"=",
"set",
"(",
")"... | Multiply by the specified scalar all the biases and offset of a binary quadratic model.
Args:
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
Examples:
This example creates a binary quadratic model and then scales it to half
the original energy range.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 2.0}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN)
>>> bqm.scale(0.5)
>>> bqm.linear['a']
-1.0
>>> bqm.quadratic[('a', 'b')]
-0.5
>>> bqm.offset
0.5 | [
"Multiply",
"by",
"the",
"specified",
"scalar",
"all",
"the",
"biases",
"and",
"offset",
"of",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L826-L890 | train | 212,585 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.fix_variable | def fix_variable(self, v, value):
"""Fix the value of a variable and remove it from a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model to be fixed.
value (int):
Value assigned to the variable. Values must match the :class:`.Vartype` of the binary
quadratic model.
Examples:
This example creates a binary quadratic model with one variable and fixes
its value.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0.}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variable('a', -1)
>>> bqm.offset
0.5
>>> bqm.linear['b']
1.0
>>> 'a' in bqm
False
"""
adj = self.adj
linear = self.linear
if value not in self.vartype.value:
raise ValueError("expected value to be in {}, received {} instead".format(self.vartype.value, value))
removed_interactions = []
for u in adj[v]:
self.add_variable(u, value * adj[v][u])
removed_interactions.append((u, v))
self.remove_interactions_from(removed_interactions)
self.add_offset(value * linear[v])
self.remove_variable(v) | python | def fix_variable(self, v, value):
"""Fix the value of a variable and remove it from a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model to be fixed.
value (int):
Value assigned to the variable. Values must match the :class:`.Vartype` of the binary
quadratic model.
Examples:
This example creates a binary quadratic model with one variable and fixes
its value.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0.}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variable('a', -1)
>>> bqm.offset
0.5
>>> bqm.linear['b']
1.0
>>> 'a' in bqm
False
"""
adj = self.adj
linear = self.linear
if value not in self.vartype.value:
raise ValueError("expected value to be in {}, received {} instead".format(self.vartype.value, value))
removed_interactions = []
for u in adj[v]:
self.add_variable(u, value * adj[v][u])
removed_interactions.append((u, v))
self.remove_interactions_from(removed_interactions)
self.add_offset(value * linear[v])
self.remove_variable(v) | [
"def",
"fix_variable",
"(",
"self",
",",
"v",
",",
"value",
")",
":",
"adj",
"=",
"self",
".",
"adj",
"linear",
"=",
"self",
".",
"linear",
"if",
"value",
"not",
"in",
"self",
".",
"vartype",
".",
"value",
":",
"raise",
"ValueError",
"(",
"\"expected... | Fix the value of a variable and remove it from a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model to be fixed.
value (int):
Value assigned to the variable. Values must match the :class:`.Vartype` of the binary
quadratic model.
Examples:
This example creates a binary quadratic model with one variable and fixes
its value.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0.}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variable('a', -1)
>>> bqm.offset
0.5
>>> bqm.linear['b']
1.0
>>> 'a' in bqm
False | [
"Fix",
"the",
"value",
"of",
"a",
"variable",
"and",
"remove",
"it",
"from",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L979-L1020 | train | 212,586 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.fix_variables | def fix_variables(self, fixed):
"""Fix the value of the variables and remove it from a binary quadratic model.
Args:
fixed (dict):
A dictionary of variable assignments.
Examples:
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variables({'a': -1, 'b': +1})
"""
for v, val in fixed.items():
self.fix_variable(v, val) | python | def fix_variables(self, fixed):
"""Fix the value of the variables and remove it from a binary quadratic model.
Args:
fixed (dict):
A dictionary of variable assignments.
Examples:
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variables({'a': -1, 'b': +1})
"""
for v, val in fixed.items():
self.fix_variable(v, val) | [
"def",
"fix_variables",
"(",
"self",
",",
"fixed",
")",
":",
"for",
"v",
",",
"val",
"in",
"fixed",
".",
"items",
"(",
")",
":",
"self",
".",
"fix_variable",
"(",
"v",
",",
"val",
")"
] | Fix the value of the variables and remove it from a binary quadratic model.
Args:
fixed (dict):
A dictionary of variable assignments.
Examples:
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variables({'a': -1, 'b': +1}) | [
"Fix",
"the",
"value",
"of",
"the",
"variables",
"and",
"remove",
"it",
"from",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1022-L1035 | train | 212,587 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.flip_variable | def flip_variable(self, v):
"""Flip variable v in a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model. If v is not in the binary
quadratic model, it is ignored.
Examples:
This example creates a binary quadratic model with two variables and inverts
the value of one.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm.flip_variable(1)
>>> bqm.linear[1], bqm.linear[2], bqm.quadratic[(1, 2)]
(-1.0, 2, -0.5)
"""
adj = self.adj
linear = self.linear
quadratic = self.quadratic
if v not in adj:
return
if self.vartype is Vartype.SPIN:
# in this case we just multiply by -1
linear[v] *= -1.
for u in adj[v]:
adj[v][u] *= -1.
adj[u][v] *= -1.
if (u, v) in quadratic:
quadratic[(u, v)] *= -1.
elif (v, u) in quadratic:
quadratic[(v, u)] *= -1.
else:
raise RuntimeError("quadratic is missing an interaction")
elif self.vartype is Vartype.BINARY:
self.offset += linear[v]
linear[v] *= -1
for u in adj[v]:
bias = adj[v][u]
adj[v][u] *= -1.
adj[u][v] *= -1.
linear[u] += bias
if (u, v) in quadratic:
quadratic[(u, v)] *= -1.
elif (v, u) in quadratic:
quadratic[(v, u)] *= -1.
else:
raise RuntimeError("quadratic is missing an interaction")
else:
raise RuntimeError("Unexpected vartype")
try:
self._counterpart.flip_variable(v)
except AttributeError:
pass | python | def flip_variable(self, v):
"""Flip variable v in a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model. If v is not in the binary
quadratic model, it is ignored.
Examples:
This example creates a binary quadratic model with two variables and inverts
the value of one.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm.flip_variable(1)
>>> bqm.linear[1], bqm.linear[2], bqm.quadratic[(1, 2)]
(-1.0, 2, -0.5)
"""
adj = self.adj
linear = self.linear
quadratic = self.quadratic
if v not in adj:
return
if self.vartype is Vartype.SPIN:
# in this case we just multiply by -1
linear[v] *= -1.
for u in adj[v]:
adj[v][u] *= -1.
adj[u][v] *= -1.
if (u, v) in quadratic:
quadratic[(u, v)] *= -1.
elif (v, u) in quadratic:
quadratic[(v, u)] *= -1.
else:
raise RuntimeError("quadratic is missing an interaction")
elif self.vartype is Vartype.BINARY:
self.offset += linear[v]
linear[v] *= -1
for u in adj[v]:
bias = adj[v][u]
adj[v][u] *= -1.
adj[u][v] *= -1.
linear[u] += bias
if (u, v) in quadratic:
quadratic[(u, v)] *= -1.
elif (v, u) in quadratic:
quadratic[(v, u)] *= -1.
else:
raise RuntimeError("quadratic is missing an interaction")
else:
raise RuntimeError("Unexpected vartype")
try:
self._counterpart.flip_variable(v)
except AttributeError:
pass | [
"def",
"flip_variable",
"(",
"self",
",",
"v",
")",
":",
"adj",
"=",
"self",
".",
"adj",
"linear",
"=",
"self",
".",
"linear",
"quadratic",
"=",
"self",
".",
"quadratic",
"if",
"v",
"not",
"in",
"adj",
":",
"return",
"if",
"self",
".",
"vartype",
"... | Flip variable v in a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model. If v is not in the binary
quadratic model, it is ignored.
Examples:
This example creates a binary quadratic model with two variables and inverts
the value of one.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm.flip_variable(1)
>>> bqm.linear[1], bqm.linear[2], bqm.quadratic[(1, 2)]
(-1.0, 2, -0.5) | [
"Flip",
"variable",
"v",
"in",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1038-L1104 | train | 212,588 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.update | def update(self, bqm, ignore_info=True):
"""Update one binary quadratic model from another.
Args:
bqm (:class:`.BinaryQuadraticModel`):
The updating binary quadratic model. Any variables in the updating
model are added to the updated model. Values of biases and the offset
in the updating model are added to the corresponding values in
the updated model.
ignore_info (bool, optional, default=True):
If True, info in the given binary quadratic model is ignored, otherwise
:attr:`.BinaryQuadraticModel.info` is updated with the given binary quadratic
model's info, potentially overwriting values.
Examples:
This example creates two binary quadratic models and updates the first
from the second.
>>> import dimod
...
>>> linear1 = {1: 1, 2: 2}
>>> quadratic1 = {(1, 2): 12}
>>> bqm1 = dimod.BinaryQuadraticModel(linear1, quadratic1, 0.5, dimod.SPIN)
>>> bqm1.info = {'BQM number 1'}
>>> linear2 = {2: 0.25, 3: 0.35}
>>> quadratic2 = {(2, 3): 23}
>>> bqm2 = dimod.BinaryQuadraticModel(linear2, quadratic2, 0.75, dimod.SPIN)
>>> bqm2.info = {'BQM number 2'}
>>> bqm1.update(bqm2)
>>> bqm1.offset
1.25
>>> 'BQM number 2' in bqm1.info
False
>>> bqm1.update(bqm2, ignore_info=False)
>>> 'BQM number 2' in bqm1.info
True
>>> bqm1.offset
2.0
"""
self.add_variables_from(bqm.linear, vartype=bqm.vartype)
self.add_interactions_from(bqm.quadratic, vartype=bqm.vartype)
self.add_offset(bqm.offset)
if not ignore_info:
self.info.update(bqm.info) | python | def update(self, bqm, ignore_info=True):
"""Update one binary quadratic model from another.
Args:
bqm (:class:`.BinaryQuadraticModel`):
The updating binary quadratic model. Any variables in the updating
model are added to the updated model. Values of biases and the offset
in the updating model are added to the corresponding values in
the updated model.
ignore_info (bool, optional, default=True):
If True, info in the given binary quadratic model is ignored, otherwise
:attr:`.BinaryQuadraticModel.info` is updated with the given binary quadratic
model's info, potentially overwriting values.
Examples:
This example creates two binary quadratic models and updates the first
from the second.
>>> import dimod
...
>>> linear1 = {1: 1, 2: 2}
>>> quadratic1 = {(1, 2): 12}
>>> bqm1 = dimod.BinaryQuadraticModel(linear1, quadratic1, 0.5, dimod.SPIN)
>>> bqm1.info = {'BQM number 1'}
>>> linear2 = {2: 0.25, 3: 0.35}
>>> quadratic2 = {(2, 3): 23}
>>> bqm2 = dimod.BinaryQuadraticModel(linear2, quadratic2, 0.75, dimod.SPIN)
>>> bqm2.info = {'BQM number 2'}
>>> bqm1.update(bqm2)
>>> bqm1.offset
1.25
>>> 'BQM number 2' in bqm1.info
False
>>> bqm1.update(bqm2, ignore_info=False)
>>> 'BQM number 2' in bqm1.info
True
>>> bqm1.offset
2.0
"""
self.add_variables_from(bqm.linear, vartype=bqm.vartype)
self.add_interactions_from(bqm.quadratic, vartype=bqm.vartype)
self.add_offset(bqm.offset)
if not ignore_info:
self.info.update(bqm.info) | [
"def",
"update",
"(",
"self",
",",
"bqm",
",",
"ignore_info",
"=",
"True",
")",
":",
"self",
".",
"add_variables_from",
"(",
"bqm",
".",
"linear",
",",
"vartype",
"=",
"bqm",
".",
"vartype",
")",
"self",
".",
"add_interactions_from",
"(",
"bqm",
".",
"... | Update one binary quadratic model from another.
Args:
bqm (:class:`.BinaryQuadraticModel`):
The updating binary quadratic model. Any variables in the updating
model are added to the updated model. Values of biases and the offset
in the updating model are added to the corresponding values in
the updated model.
ignore_info (bool, optional, default=True):
If True, info in the given binary quadratic model is ignored, otherwise
:attr:`.BinaryQuadraticModel.info` is updated with the given binary quadratic
model's info, potentially overwriting values.
Examples:
This example creates two binary quadratic models and updates the first
from the second.
>>> import dimod
...
>>> linear1 = {1: 1, 2: 2}
>>> quadratic1 = {(1, 2): 12}
>>> bqm1 = dimod.BinaryQuadraticModel(linear1, quadratic1, 0.5, dimod.SPIN)
>>> bqm1.info = {'BQM number 1'}
>>> linear2 = {2: 0.25, 3: 0.35}
>>> quadratic2 = {(2, 3): 23}
>>> bqm2 = dimod.BinaryQuadraticModel(linear2, quadratic2, 0.75, dimod.SPIN)
>>> bqm2.info = {'BQM number 2'}
>>> bqm1.update(bqm2)
>>> bqm1.offset
1.25
>>> 'BQM number 2' in bqm1.info
False
>>> bqm1.update(bqm2, ignore_info=False)
>>> 'BQM number 2' in bqm1.info
True
>>> bqm1.offset
2.0 | [
"Update",
"one",
"binary",
"quadratic",
"model",
"from",
"another",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1106-L1152 | train | 212,589 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.contract_variables | def contract_variables(self, u, v):
"""Enforce u, v being the same variable in a binary quadratic model.
The resulting variable is labeled 'u'. Values of interactions between `v` and
variables that `u` interacts with are added to the corresponding interactions
of `u`.
Args:
u (variable):
Variable in the binary quadratic model.
v (variable):
Variable in the binary quadratic model.
Examples:
This example creates a binary quadratic model representing the K4 complete graph
and contracts node (variable) 3 into node 2. The interactions between
3 and its neighbors 1 and 4 are added to the corresponding interactions
between 2 and those same neighbors.
>>> import dimod
...
>>> linear = {1: 1, 2: 2, 3: 3, 4: 4}
>>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
... (2, 3): 23, (2, 4): 24,
... (3, 4): 34}
>>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)
>>> bqm.contract_variables(2, 3)
>>> 3 in bqm.linear
False
>>> bqm.quadratic[(1, 2)]
25
"""
adj = self.adj
if u not in adj:
raise ValueError("{} is not a variable in the binary quadratic model".format(u))
if v not in adj:
raise ValueError("{} is not a variable in the binary quadratic model".format(v))
# if there is an interaction between u, v it becomes linear for u
if v in adj[u]:
if self.vartype is Vartype.BINARY:
self.add_variable(u, adj[u][v])
elif self.vartype is Vartype.SPIN:
self.add_offset(adj[u][v])
else:
raise RuntimeError("unexpected vartype")
self.remove_interaction(u, v)
# all of the interactions that v has become interactions for u
neighbors = list(adj[v])
for w in neighbors:
self.add_interaction(u, w, adj[v][w])
self.remove_interaction(v, w)
# finally remove v
self.remove_variable(v) | python | def contract_variables(self, u, v):
"""Enforce u, v being the same variable in a binary quadratic model.
The resulting variable is labeled 'u'. Values of interactions between `v` and
variables that `u` interacts with are added to the corresponding interactions
of `u`.
Args:
u (variable):
Variable in the binary quadratic model.
v (variable):
Variable in the binary quadratic model.
Examples:
This example creates a binary quadratic model representing the K4 complete graph
and contracts node (variable) 3 into node 2. The interactions between
3 and its neighbors 1 and 4 are added to the corresponding interactions
between 2 and those same neighbors.
>>> import dimod
...
>>> linear = {1: 1, 2: 2, 3: 3, 4: 4}
>>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
... (2, 3): 23, (2, 4): 24,
... (3, 4): 34}
>>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)
>>> bqm.contract_variables(2, 3)
>>> 3 in bqm.linear
False
>>> bqm.quadratic[(1, 2)]
25
"""
adj = self.adj
if u not in adj:
raise ValueError("{} is not a variable in the binary quadratic model".format(u))
if v not in adj:
raise ValueError("{} is not a variable in the binary quadratic model".format(v))
# if there is an interaction between u, v it becomes linear for u
if v in adj[u]:
if self.vartype is Vartype.BINARY:
self.add_variable(u, adj[u][v])
elif self.vartype is Vartype.SPIN:
self.add_offset(adj[u][v])
else:
raise RuntimeError("unexpected vartype")
self.remove_interaction(u, v)
# all of the interactions that v has become interactions for u
neighbors = list(adj[v])
for w in neighbors:
self.add_interaction(u, w, adj[v][w])
self.remove_interaction(v, w)
# finally remove v
self.remove_variable(v) | [
"def",
"contract_variables",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"adj",
"=",
"self",
".",
"adj",
"if",
"u",
"not",
"in",
"adj",
":",
"raise",
"ValueError",
"(",
"\"{} is not a variable in the binary quadratic model\"",
".",
"format",
"(",
"u",
")",
... | Enforce u, v being the same variable in a binary quadratic model.
The resulting variable is labeled 'u'. Values of interactions between `v` and
variables that `u` interacts with are added to the corresponding interactions
of `u`.
Args:
u (variable):
Variable in the binary quadratic model.
v (variable):
Variable in the binary quadratic model.
Examples:
This example creates a binary quadratic model representing the K4 complete graph
and contracts node (variable) 3 into node 2. The interactions between
3 and its neighbors 1 and 4 are added to the corresponding interactions
between 2 and those same neighbors.
>>> import dimod
...
>>> linear = {1: 1, 2: 2, 3: 3, 4: 4}
>>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
... (2, 3): 23, (2, 4): 24,
... (3, 4): 34}
>>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)
>>> bqm.contract_variables(2, 3)
>>> 3 in bqm.linear
False
>>> bqm.quadratic[(1, 2)]
25 | [
"Enforce",
"u",
"v",
"being",
"the",
"same",
"variable",
"in",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1154-L1212 | train | 212,590 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.relabel_variables | def relabel_variables(self, mapping, inplace=True):
"""Relabel variables of a binary quadratic model as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an incomplete mapping is
provided, unmapped variables retain their current labels.
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place; otherwise, a new binary
quadratic model is returned.
Returns:
:class:`.BinaryQuadraticModel`: A binary quadratic model
with the variables relabeled. If `inplace` is set to True, returns
itself.
Examples:
This example creates a binary quadratic model with two variables and relables one.
>>> import dimod
...
>>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)
>>> model.relabel_variables({0: 'a'}) # doctest: +SKIP
BinaryQuadraticModel({1: 1.0, 'a': 0.0}, {('a', 1): -1}, 0.0, Vartype.SPIN)
This example creates a binary quadratic model with two variables and returns a new
model with relabled variables.
>>> import dimod
...
>>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)
>>> new_model = model.relabel_variables({0: 'a', 1: 'b'}, inplace=False) # doctest: +SKIP
>>> new_model.quadratic # doctest: +SKIP
{('a', 'b'): -1}
"""
try:
old_labels = set(mapping)
new_labels = set(itervalues(mapping))
except TypeError:
raise ValueError("mapping targets must be hashable objects")
for v in new_labels:
if v in self.linear and v not in old_labels:
raise ValueError(('A variable cannot be relabeled "{}" without also relabeling '
"the existing variable of the same name").format(v))
if inplace:
shared = old_labels & new_labels
if shared:
old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels)
self.relabel_variables(old_to_intermediate, inplace=True)
self.relabel_variables(intermediate_to_new, inplace=True)
return self
linear = self.linear
quadratic = self.quadratic
adj = self.adj
# rebuild linear and adj with the new labels
for old in list(linear):
if old not in mapping:
continue
new = mapping[old]
# get the new interactions that need to be added
new_interactions = [(new, v, adj[old][v]) for v in adj[old]]
self.add_variable(new, linear[old])
self.add_interactions_from(new_interactions)
self.remove_variable(old)
return self
else:
return BinaryQuadraticModel({mapping.get(v, v): bias for v, bias in iteritems(self.linear)},
{(mapping.get(u, u), mapping.get(v, v)): bias
for (u, v), bias in iteritems(self.quadratic)},
self.offset, self.vartype) | python | def relabel_variables(self, mapping, inplace=True):
"""Relabel variables of a binary quadratic model as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an incomplete mapping is
provided, unmapped variables retain their current labels.
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place; otherwise, a new binary
quadratic model is returned.
Returns:
:class:`.BinaryQuadraticModel`: A binary quadratic model
with the variables relabeled. If `inplace` is set to True, returns
itself.
Examples:
This example creates a binary quadratic model with two variables and relables one.
>>> import dimod
...
>>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)
>>> model.relabel_variables({0: 'a'}) # doctest: +SKIP
BinaryQuadraticModel({1: 1.0, 'a': 0.0}, {('a', 1): -1}, 0.0, Vartype.SPIN)
This example creates a binary quadratic model with two variables and returns a new
model with relabled variables.
>>> import dimod
...
>>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)
>>> new_model = model.relabel_variables({0: 'a', 1: 'b'}, inplace=False) # doctest: +SKIP
>>> new_model.quadratic # doctest: +SKIP
{('a', 'b'): -1}
"""
try:
old_labels = set(mapping)
new_labels = set(itervalues(mapping))
except TypeError:
raise ValueError("mapping targets must be hashable objects")
for v in new_labels:
if v in self.linear and v not in old_labels:
raise ValueError(('A variable cannot be relabeled "{}" without also relabeling '
"the existing variable of the same name").format(v))
if inplace:
shared = old_labels & new_labels
if shared:
old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels)
self.relabel_variables(old_to_intermediate, inplace=True)
self.relabel_variables(intermediate_to_new, inplace=True)
return self
linear = self.linear
quadratic = self.quadratic
adj = self.adj
# rebuild linear and adj with the new labels
for old in list(linear):
if old not in mapping:
continue
new = mapping[old]
# get the new interactions that need to be added
new_interactions = [(new, v, adj[old][v]) for v in adj[old]]
self.add_variable(new, linear[old])
self.add_interactions_from(new_interactions)
self.remove_variable(old)
return self
else:
return BinaryQuadraticModel({mapping.get(v, v): bias for v, bias in iteritems(self.linear)},
{(mapping.get(u, u), mapping.get(v, v)): bias
for (u, v), bias in iteritems(self.quadratic)},
self.offset, self.vartype) | [
"def",
"relabel_variables",
"(",
"self",
",",
"mapping",
",",
"inplace",
"=",
"True",
")",
":",
"try",
":",
"old_labels",
"=",
"set",
"(",
"mapping",
")",
"new_labels",
"=",
"set",
"(",
"itervalues",
"(",
"mapping",
")",
")",
"except",
"TypeError",
":",
... | Relabel variables of a binary quadratic model as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an incomplete mapping is
provided, unmapped variables retain their current labels.
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place; otherwise, a new binary
quadratic model is returned.
Returns:
:class:`.BinaryQuadraticModel`: A binary quadratic model
with the variables relabeled. If `inplace` is set to True, returns
itself.
Examples:
This example creates a binary quadratic model with two variables and relables one.
>>> import dimod
...
>>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)
>>> model.relabel_variables({0: 'a'}) # doctest: +SKIP
BinaryQuadraticModel({1: 1.0, 'a': 0.0}, {('a', 1): -1}, 0.0, Vartype.SPIN)
This example creates a binary quadratic model with two variables and returns a new
model with relabled variables.
>>> import dimod
...
>>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)
>>> new_model = model.relabel_variables({0: 'a', 1: 'b'}, inplace=False) # doctest: +SKIP
>>> new_model.quadratic # doctest: +SKIP
{('a', 'b'): -1} | [
"Relabel",
"variables",
"of",
"a",
"binary",
"quadratic",
"model",
"as",
"specified",
"by",
"mapping",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1218-L1298 | train | 212,591 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.change_vartype | def change_vartype(self, vartype, inplace=True):
"""Create a binary quadratic model with the specified vartype.
Args:
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the changed model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place; otherwise, a new binary
quadratic model is returned.
Returns:
:class:`.BinaryQuadraticModel`. A new binary quadratic model with
vartype matching input 'vartype'.
Examples:
This example creates an Ising model and then creates a QUBO from it.
>>> import dimod
...
>>> bqm_spin = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm_qubo = bqm_spin.change_vartype('BINARY', inplace=False)
>>> bqm_spin.offset, bqm_spin.vartype
(0.5, <Vartype.SPIN: frozenset({1, -1})>)
>>> bqm_qubo.offset, bqm_qubo.vartype
(-2.0, <Vartype.BINARY: frozenset({0, 1})>)
"""
if not inplace:
# create a new model of the appropriate type, then add self's biases to it
new_model = BinaryQuadraticModel({}, {}, 0.0, vartype)
new_model.add_variables_from(self.linear, vartype=self.vartype)
new_model.add_interactions_from(self.quadratic, vartype=self.vartype)
new_model.add_offset(self.offset)
return new_model
# in this case we are doing things in-place, if the desired vartype matches self.vartype,
# then we don't need to do anything
if vartype is self.vartype:
return self
if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:
linear, quadratic, offset = self.spin_to_binary(self.linear, self.quadratic, self.offset)
elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:
linear, quadratic, offset = self.binary_to_spin(self.linear, self.quadratic, self.offset)
else:
raise RuntimeError("something has gone wrong. unknown vartype conversion.")
# drop everything
for v in linear:
self.remove_variable(v)
self.add_offset(-self.offset)
self.vartype = vartype
self.add_variables_from(linear)
self.add_interactions_from(quadratic)
self.add_offset(offset)
return self | python | def change_vartype(self, vartype, inplace=True):
"""Create a binary quadratic model with the specified vartype.
Args:
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the changed model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place; otherwise, a new binary
quadratic model is returned.
Returns:
:class:`.BinaryQuadraticModel`. A new binary quadratic model with
vartype matching input 'vartype'.
Examples:
This example creates an Ising model and then creates a QUBO from it.
>>> import dimod
...
>>> bqm_spin = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm_qubo = bqm_spin.change_vartype('BINARY', inplace=False)
>>> bqm_spin.offset, bqm_spin.vartype
(0.5, <Vartype.SPIN: frozenset({1, -1})>)
>>> bqm_qubo.offset, bqm_qubo.vartype
(-2.0, <Vartype.BINARY: frozenset({0, 1})>)
"""
if not inplace:
# create a new model of the appropriate type, then add self's biases to it
new_model = BinaryQuadraticModel({}, {}, 0.0, vartype)
new_model.add_variables_from(self.linear, vartype=self.vartype)
new_model.add_interactions_from(self.quadratic, vartype=self.vartype)
new_model.add_offset(self.offset)
return new_model
# in this case we are doing things in-place, if the desired vartype matches self.vartype,
# then we don't need to do anything
if vartype is self.vartype:
return self
if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:
linear, quadratic, offset = self.spin_to_binary(self.linear, self.quadratic, self.offset)
elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:
linear, quadratic, offset = self.binary_to_spin(self.linear, self.quadratic, self.offset)
else:
raise RuntimeError("something has gone wrong. unknown vartype conversion.")
# drop everything
for v in linear:
self.remove_variable(v)
self.add_offset(-self.offset)
self.vartype = vartype
self.add_variables_from(linear)
self.add_interactions_from(quadratic)
self.add_offset(offset)
return self | [
"def",
"change_vartype",
"(",
"self",
",",
"vartype",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"not",
"inplace",
":",
"# create a new model of the appropriate type, then add self's biases to it",
"new_model",
"=",
"BinaryQuadraticModel",
"(",
"{",
"}",
",",
"{",
... | Create a binary quadratic model with the specified vartype.
Args:
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the changed model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place; otherwise, a new binary
quadratic model is returned.
Returns:
:class:`.BinaryQuadraticModel`. A new binary quadratic model with
vartype matching input 'vartype'.
Examples:
This example creates an Ising model and then creates a QUBO from it.
>>> import dimod
...
>>> bqm_spin = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm_qubo = bqm_spin.change_vartype('BINARY', inplace=False)
>>> bqm_spin.offset, bqm_spin.vartype
(0.5, <Vartype.SPIN: frozenset({1, -1})>)
>>> bqm_qubo.offset, bqm_qubo.vartype
(-2.0, <Vartype.BINARY: frozenset({0, 1})>) | [
"Create",
"a",
"binary",
"quadratic",
"model",
"with",
"the",
"specified",
"vartype",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1301-L1365 | train | 212,592 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.spin_to_binary | def spin_to_binary(linear, quadratic, offset):
"""convert linear, quadratic, and offset from spin to binary.
Does no checking of vartype. Copies all of the values into new objects.
"""
# the linear biases are the easiest
new_linear = {v: 2. * bias for v, bias in iteritems(linear)}
# next the quadratic biases
new_quadratic = {}
for (u, v), bias in iteritems(quadratic):
new_quadratic[(u, v)] = 4. * bias
new_linear[u] -= 2. * bias
new_linear[v] -= 2. * bias
# finally calculate the offset
offset += sum(itervalues(quadratic)) - sum(itervalues(linear))
return new_linear, new_quadratic, offset | python | def spin_to_binary(linear, quadratic, offset):
"""convert linear, quadratic, and offset from spin to binary.
Does no checking of vartype. Copies all of the values into new objects.
"""
# the linear biases are the easiest
new_linear = {v: 2. * bias for v, bias in iteritems(linear)}
# next the quadratic biases
new_quadratic = {}
for (u, v), bias in iteritems(quadratic):
new_quadratic[(u, v)] = 4. * bias
new_linear[u] -= 2. * bias
new_linear[v] -= 2. * bias
# finally calculate the offset
offset += sum(itervalues(quadratic)) - sum(itervalues(linear))
return new_linear, new_quadratic, offset | [
"def",
"spin_to_binary",
"(",
"linear",
",",
"quadratic",
",",
"offset",
")",
":",
"# the linear biases are the easiest",
"new_linear",
"=",
"{",
"v",
":",
"2.",
"*",
"bias",
"for",
"v",
",",
"bias",
"in",
"iteritems",
"(",
"linear",
")",
"}",
"# next the qu... | convert linear, quadratic, and offset from spin to binary.
Does no checking of vartype. Copies all of the values into new objects. | [
"convert",
"linear",
"quadratic",
"and",
"offset",
"from",
"spin",
"to",
"binary",
".",
"Does",
"no",
"checking",
"of",
"vartype",
".",
"Copies",
"all",
"of",
"the",
"values",
"into",
"new",
"objects",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1372-L1390 | train | 212,593 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.binary_to_spin | def binary_to_spin(linear, quadratic, offset):
"""convert linear, quadratic and offset from binary to spin.
Does no checking of vartype. Copies all of the values into new objects.
"""
h = {}
J = {}
linear_offset = 0.0
quadratic_offset = 0.0
for u, bias in iteritems(linear):
h[u] = .5 * bias
linear_offset += bias
for (u, v), bias in iteritems(quadratic):
J[(u, v)] = .25 * bias
h[u] += .25 * bias
h[v] += .25 * bias
quadratic_offset += bias
offset += .5 * linear_offset + .25 * quadratic_offset
return h, J, offset | python | def binary_to_spin(linear, quadratic, offset):
"""convert linear, quadratic and offset from binary to spin.
Does no checking of vartype. Copies all of the values into new objects.
"""
h = {}
J = {}
linear_offset = 0.0
quadratic_offset = 0.0
for u, bias in iteritems(linear):
h[u] = .5 * bias
linear_offset += bias
for (u, v), bias in iteritems(quadratic):
J[(u, v)] = .25 * bias
h[u] += .25 * bias
h[v] += .25 * bias
quadratic_offset += bias
offset += .5 * linear_offset + .25 * quadratic_offset
return h, J, offset | [
"def",
"binary_to_spin",
"(",
"linear",
",",
"quadratic",
",",
"offset",
")",
":",
"h",
"=",
"{",
"}",
"J",
"=",
"{",
"}",
"linear_offset",
"=",
"0.0",
"quadratic_offset",
"=",
"0.0",
"for",
"u",
",",
"bias",
"in",
"iteritems",
"(",
"linear",
")",
":... | convert linear, quadratic and offset from binary to spin.
Does no checking of vartype. Copies all of the values into new objects. | [
"convert",
"linear",
"quadratic",
"and",
"offset",
"from",
"binary",
"to",
"spin",
".",
"Does",
"no",
"checking",
"of",
"vartype",
".",
"Copies",
"all",
"of",
"the",
"values",
"into",
"new",
"objects",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1393-L1417 | train | 212,594 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.copy | def copy(self):
"""Create a copy of a BinaryQuadraticModel.
Returns:
:class:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm2 = bqm.copy()
"""
# new objects are constructed for each, so we just need to pass them in
return BinaryQuadraticModel(self.linear, self.quadratic, self.offset, self.vartype, **self.info) | python | def copy(self):
"""Create a copy of a BinaryQuadraticModel.
Returns:
:class:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm2 = bqm.copy()
"""
# new objects are constructed for each, so we just need to pass them in
return BinaryQuadraticModel(self.linear, self.quadratic, self.offset, self.vartype, **self.info) | [
"def",
"copy",
"(",
"self",
")",
":",
"# new objects are constructed for each, so we just need to pass them in",
"return",
"BinaryQuadraticModel",
"(",
"self",
".",
"linear",
",",
"self",
".",
"quadratic",
",",
"self",
".",
"offset",
",",
"self",
".",
"vartype",
","... | Create a copy of a BinaryQuadraticModel.
Returns:
:class:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm2 = bqm.copy() | [
"Create",
"a",
"copy",
"of",
"a",
"BinaryQuadraticModel",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1423-L1437 | train | 212,595 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.energy | def energy(self, sample):
"""Determine the energy of the specified sample of a binary quadratic model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the binary quadratic model, of
the sample multipled by the linear bias of the variable and
all its interactions; that is,
.. math::
E(\mathbf{s}) = \sum_v h_v s_v + \sum_{u,v} J_{u,v} s_u s_v + c
where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`
the quadratic bias (interactions), and :math:`c` the energy offset.
Code for the energy calculation might look like the following::
energy = model.offset # doctest: +SKIP
for v in model: # doctest: +SKIP
energy += model.linear[v] * sample[v]
for u, v in model.quadratic: # doctest: +SKIP
energy += model.quadratic[(u, v)] * sample[u] * sample[v]
Args:
sample (dict):
Sample for which to calculate the energy, formatted as a dict where keys
are variables and values are the value associated with each variable.
Returns:
float: Energy for the sample.
Examples:
This example creates a binary quadratic model and returns the energies for
a couple of samples.
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 1}, {(1, 2): 1}, 0.5, dimod.SPIN)
>>> bqm.energy({1: -1, 2: -1})
-0.5
>>> bqm.energy({1: 1, 2: 1})
3.5
"""
linear = self.linear
quadratic = self.quadratic
if isinstance(sample, SampleView):
# because the SampleView object simply reads from an underlying matrix, each read
# is relatively expensive.
# However, sample.items() is ~10x faster than {sample[v] for v in sample}, therefore
# it is much more efficient to dump sample into a dictionary for repeated reads
sample = dict(sample)
en = self.offset
en += sum(linear[v] * sample[v] for v in linear)
en += sum(sample[u] * sample[v] * quadratic[(u, v)] for u, v in quadratic)
return en | python | def energy(self, sample):
"""Determine the energy of the specified sample of a binary quadratic model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the binary quadratic model, of
the sample multipled by the linear bias of the variable and
all its interactions; that is,
.. math::
E(\mathbf{s}) = \sum_v h_v s_v + \sum_{u,v} J_{u,v} s_u s_v + c
where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`
the quadratic bias (interactions), and :math:`c` the energy offset.
Code for the energy calculation might look like the following::
energy = model.offset # doctest: +SKIP
for v in model: # doctest: +SKIP
energy += model.linear[v] * sample[v]
for u, v in model.quadratic: # doctest: +SKIP
energy += model.quadratic[(u, v)] * sample[u] * sample[v]
Args:
sample (dict):
Sample for which to calculate the energy, formatted as a dict where keys
are variables and values are the value associated with each variable.
Returns:
float: Energy for the sample.
Examples:
This example creates a binary quadratic model and returns the energies for
a couple of samples.
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 1}, {(1, 2): 1}, 0.5, dimod.SPIN)
>>> bqm.energy({1: -1, 2: -1})
-0.5
>>> bqm.energy({1: 1, 2: 1})
3.5
"""
linear = self.linear
quadratic = self.quadratic
if isinstance(sample, SampleView):
# because the SampleView object simply reads from an underlying matrix, each read
# is relatively expensive.
# However, sample.items() is ~10x faster than {sample[v] for v in sample}, therefore
# it is much more efficient to dump sample into a dictionary for repeated reads
sample = dict(sample)
en = self.offset
en += sum(linear[v] * sample[v] for v in linear)
en += sum(sample[u] * sample[v] * quadratic[(u, v)] for u, v in quadratic)
return en | [
"def",
"energy",
"(",
"self",
",",
"sample",
")",
":",
"linear",
"=",
"self",
".",
"linear",
"quadratic",
"=",
"self",
".",
"quadratic",
"if",
"isinstance",
"(",
"sample",
",",
"SampleView",
")",
":",
"# because the SampleView object simply reads from an underlyin... | Determine the energy of the specified sample of a binary quadratic model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the binary quadratic model, of
the sample multipled by the linear bias of the variable and
all its interactions; that is,
.. math::
E(\mathbf{s}) = \sum_v h_v s_v + \sum_{u,v} J_{u,v} s_u s_v + c
where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`
the quadratic bias (interactions), and :math:`c` the energy offset.
Code for the energy calculation might look like the following::
energy = model.offset # doctest: +SKIP
for v in model: # doctest: +SKIP
energy += model.linear[v] * sample[v]
for u, v in model.quadratic: # doctest: +SKIP
energy += model.quadratic[(u, v)] * sample[u] * sample[v]
Args:
sample (dict):
Sample for which to calculate the energy, formatted as a dict where keys
are variables and values are the value associated with each variable.
Returns:
float: Energy for the sample.
Examples:
This example creates a binary quadratic model and returns the energies for
a couple of samples.
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 1}, {(1, 2): 1}, 0.5, dimod.SPIN)
>>> bqm.energy({1: -1, 2: -1})
-0.5
>>> bqm.energy({1: 1, 2: 1})
3.5 | [
"Determine",
"the",
"energy",
"of",
"the",
"specified",
"sample",
"of",
"a",
"binary",
"quadratic",
"model",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1439-L1495 | train | 212,596 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.energies | def energies(self, samples_like, dtype=np.float):
"""Determine the energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of NumPy's array_like
structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`):
The data type of the returned energies.
Returns:
:obj:`numpy.ndarray`: The energies.
"""
samples, labels = as_samples(samples_like)
if all(v == idx for idx, v in enumerate(labels)):
ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(dtype=dtype)
else:
ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(variable_order=labels, dtype=dtype)
energies = samples.dot(ldata) + (samples[:, irow]*samples[:, icol]).dot(qdata) + offset
return np.asarray(energies, dtype=dtype) | python | def energies(self, samples_like, dtype=np.float):
"""Determine the energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of NumPy's array_like
structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`):
The data type of the returned energies.
Returns:
:obj:`numpy.ndarray`: The energies.
"""
samples, labels = as_samples(samples_like)
if all(v == idx for idx, v in enumerate(labels)):
ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(dtype=dtype)
else:
ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(variable_order=labels, dtype=dtype)
energies = samples.dot(ldata) + (samples[:, irow]*samples[:, icol]).dot(qdata) + offset
return np.asarray(energies, dtype=dtype) | [
"def",
"energies",
"(",
"self",
",",
"samples_like",
",",
"dtype",
"=",
"np",
".",
"float",
")",
":",
"samples",
",",
"labels",
"=",
"as_samples",
"(",
"samples_like",
")",
"if",
"all",
"(",
"v",
"==",
"idx",
"for",
"idx",
",",
"v",
"in",
"enumerate"... | Determine the energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of NumPy's array_like
structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`):
The data type of the returned energies.
Returns:
:obj:`numpy.ndarray`: The energies. | [
"Determine",
"the",
"energies",
"of",
"the",
"given",
"samples",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1497-L1520 | train | 212,597 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.to_coo | def to_coo(self, fp=None, vartype_header=False):
"""Serialize the binary quadratic model to a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
fp (file, optional):
`.write()`-supporting `file object`_ to save the linear and quadratic biases
of a binary quadratic model to. The model is stored as a list of 3-tuples,
(i, j, bias), where :math:`i=j` for linear biases. If not provided,
returns a string.
vartype_header (bool, optional, default=False):
If true, the binary quadratic model's variable type as prepended to the
string or file as a header.
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. note:: Variables must use index lables (numeric lables). Binary quadratic
models saved to COOrdinate format encoding do not preserve offsets.
Examples:
This is an example of a binary quadratic model encoded in COOrdinate format.
.. code-block:: none
0 0 0.50000
0 1 0.50000
1 1 -1.50000
The Coordinate format with a header
.. code-block:: none
# vartype=SPIN
0 0 0.50000
0 1 0.50000
1 1 -1.50000
This is an example of writing a binary quadratic model to a COOrdinate-format
file.
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)
>>> with open('tmp.ising', 'w') as file: # doctest: +SKIP
... bqm.to_coo(file)
This is an example of writing a binary quadratic model to a COOrdinate-format string.
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)
>>> bqm.to_coo() # doctest: +SKIP
0 0 -1.000000
0 1 -1.000000
1 1 1.000000
"""
import dimod.serialization.coo as coo
if fp is None:
return coo.dumps(self, vartype_header)
else:
coo.dump(self, fp, vartype_header) | python | def to_coo(self, fp=None, vartype_header=False):
"""Serialize the binary quadratic model to a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
fp (file, optional):
`.write()`-supporting `file object`_ to save the linear and quadratic biases
of a binary quadratic model to. The model is stored as a list of 3-tuples,
(i, j, bias), where :math:`i=j` for linear biases. If not provided,
returns a string.
vartype_header (bool, optional, default=False):
If true, the binary quadratic model's variable type as prepended to the
string or file as a header.
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. note:: Variables must use index lables (numeric lables). Binary quadratic
models saved to COOrdinate format encoding do not preserve offsets.
Examples:
This is an example of a binary quadratic model encoded in COOrdinate format.
.. code-block:: none
0 0 0.50000
0 1 0.50000
1 1 -1.50000
The Coordinate format with a header
.. code-block:: none
# vartype=SPIN
0 0 0.50000
0 1 0.50000
1 1 -1.50000
This is an example of writing a binary quadratic model to a COOrdinate-format
file.
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)
>>> with open('tmp.ising', 'w') as file: # doctest: +SKIP
... bqm.to_coo(file)
This is an example of writing a binary quadratic model to a COOrdinate-format string.
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)
>>> bqm.to_coo() # doctest: +SKIP
0 0 -1.000000
0 1 -1.000000
1 1 1.000000
"""
import dimod.serialization.coo as coo
if fp is None:
return coo.dumps(self, vartype_header)
else:
coo.dump(self, fp, vartype_header) | [
"def",
"to_coo",
"(",
"self",
",",
"fp",
"=",
"None",
",",
"vartype_header",
"=",
"False",
")",
":",
"import",
"dimod",
".",
"serialization",
".",
"coo",
"as",
"coo",
"if",
"fp",
"is",
"None",
":",
"return",
"coo",
".",
"dumps",
"(",
"self",
",",
"... | Serialize the binary quadratic model to a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
fp (file, optional):
`.write()`-supporting `file object`_ to save the linear and quadratic biases
of a binary quadratic model to. The model is stored as a list of 3-tuples,
(i, j, bias), where :math:`i=j` for linear biases. If not provided,
returns a string.
vartype_header (bool, optional, default=False):
If true, the binary quadratic model's variable type as prepended to the
string or file as a header.
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. note:: Variables must use index lables (numeric lables). Binary quadratic
models saved to COOrdinate format encoding do not preserve offsets.
Examples:
This is an example of a binary quadratic model encoded in COOrdinate format.
.. code-block:: none
0 0 0.50000
0 1 0.50000
1 1 -1.50000
The Coordinate format with a header
.. code-block:: none
# vartype=SPIN
0 0 0.50000
0 1 0.50000
1 1 -1.50000
This is an example of writing a binary quadratic model to a COOrdinate-format
file.
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)
>>> with open('tmp.ising', 'w') as file: # doctest: +SKIP
... bqm.to_coo(file)
This is an example of writing a binary quadratic model to a COOrdinate-format string.
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)
>>> bqm.to_coo() # doctest: +SKIP
0 0 -1.000000
0 1 -1.000000
1 1 1.000000 | [
"Serialize",
"the",
"binary",
"quadratic",
"model",
"to",
"a",
"COOrdinate_",
"format",
"encoding",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1526-L1586 | train | 212,598 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | BinaryQuadraticModel.from_coo | def from_coo(cls, obj, vartype=None):
"""Deserialize a binary quadratic model from a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
obj: (str/file):
Either a string or a `.read()`-supporting `file object`_ that represents
linear and quadratic biases for a binary quadratic model. This data
is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j`
for linear biases.
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
If not provided, the vartype must be specified with a header in the
file.
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. note:: Variables must use index lables (numeric lables). Binary quadratic
models created from COOrdinate format encoding have offsets set to
zero.
Examples:
An example of a binary quadratic model encoded in COOrdinate format.
.. code-block:: none
0 0 0.50000
0 1 0.50000
1 1 -1.50000
The Coordinate format with a header
.. code-block:: none
# vartype=SPIN
0 0 0.50000
0 1 0.50000
1 1 -1.50000
This example saves a binary quadratic model to a COOrdinate-format file
and creates a new model by reading the saved file.
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.BINARY)
>>> with open('tmp.qubo', 'w') as file: # doctest: +SKIP
... bqm.to_coo(file)
>>> with open('tmp.qubo', 'r') as file: # doctest: +SKIP
... new_bqm = dimod.BinaryQuadraticModel.from_coo(file, dimod.BINARY)
>>> any(new_bqm) # doctest: +SKIP
True
"""
import dimod.serialization.coo as coo
if isinstance(obj, str):
return coo.loads(obj, cls=cls, vartype=vartype)
return coo.load(obj, cls=cls, vartype=vartype) | python | def from_coo(cls, obj, vartype=None):
"""Deserialize a binary quadratic model from a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
obj: (str/file):
Either a string or a `.read()`-supporting `file object`_ that represents
linear and quadratic biases for a binary quadratic model. This data
is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j`
for linear biases.
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
If not provided, the vartype must be specified with a header in the
file.
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. note:: Variables must use index lables (numeric lables). Binary quadratic
models created from COOrdinate format encoding have offsets set to
zero.
Examples:
An example of a binary quadratic model encoded in COOrdinate format.
.. code-block:: none
0 0 0.50000
0 1 0.50000
1 1 -1.50000
The Coordinate format with a header
.. code-block:: none
# vartype=SPIN
0 0 0.50000
0 1 0.50000
1 1 -1.50000
This example saves a binary quadratic model to a COOrdinate-format file
and creates a new model by reading the saved file.
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.BINARY)
>>> with open('tmp.qubo', 'w') as file: # doctest: +SKIP
... bqm.to_coo(file)
>>> with open('tmp.qubo', 'r') as file: # doctest: +SKIP
... new_bqm = dimod.BinaryQuadraticModel.from_coo(file, dimod.BINARY)
>>> any(new_bqm) # doctest: +SKIP
True
"""
import dimod.serialization.coo as coo
if isinstance(obj, str):
return coo.loads(obj, cls=cls, vartype=vartype)
return coo.load(obj, cls=cls, vartype=vartype) | [
"def",
"from_coo",
"(",
"cls",
",",
"obj",
",",
"vartype",
"=",
"None",
")",
":",
"import",
"dimod",
".",
"serialization",
".",
"coo",
"as",
"coo",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"coo",
".",
"loads",
"(",
"obj",
","... | Deserialize a binary quadratic model from a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
obj: (str/file):
Either a string or a `.read()`-supporting `file object`_ that represents
linear and quadratic biases for a binary quadratic model. This data
is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j`
for linear biases.
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
If not provided, the vartype must be specified with a header in the
file.
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. note:: Variables must use index lables (numeric lables). Binary quadratic
models created from COOrdinate format encoding have offsets set to
zero.
Examples:
An example of a binary quadratic model encoded in COOrdinate format.
.. code-block:: none
0 0 0.50000
0 1 0.50000
1 1 -1.50000
The Coordinate format with a header
.. code-block:: none
# vartype=SPIN
0 0 0.50000
0 1 0.50000
1 1 -1.50000
This example saves a binary quadratic model to a COOrdinate-format file
and creates a new model by reading the saved file.
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.BINARY)
>>> with open('tmp.qubo', 'w') as file: # doctest: +SKIP
... bqm.to_coo(file)
>>> with open('tmp.qubo', 'r') as file: # doctest: +SKIP
... new_bqm = dimod.BinaryQuadraticModel.from_coo(file, dimod.BINARY)
>>> any(new_bqm) # doctest: +SKIP
True | [
"Deserialize",
"a",
"binary",
"quadratic",
"model",
"from",
"a",
"COOrdinate_",
"format",
"encoding",
"."
] | beff1b7f86b559d923ac653c1de6d593876d6d38 | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L1589-L1652 | train | 212,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.