text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_head_repr( expr: Any, sub_render=None, key_sub_render=None) -> str: """Render a textual representation of `expr` using Positional and keyword arguments are recursively rendered using `sub_render`, which defaults to `render_head_repr` by default. If desired, a different renderer may be used for keyword arguments by giving `key_sub_renderer` Raises: AttributeError: if `expr` is not an instance of :class:`Expression`, or more specifically, if `expr` does not have `args` and `kwargs` (respectively `minimal_kwargs`) properties """
|
head_repr_fmt = r'{head}({args}{kwargs})'
if sub_render is None:
sub_render = render_head_repr
if key_sub_render is None:
key_sub_render = sub_render
if isinstance(expr.__class__, Singleton):
# We exploit that Singletons override __expr__ to directly return
# their name
return repr(expr)
if isinstance(expr, Expression):
args = expr.args
keys = expr.minimal_kwargs.keys()
kwargs = ''
if len(keys) > 0:
kwargs = ", ".join([
"%s=%s" % (key, key_sub_render(expr.kwargs[key]))
for key in keys])
if len(args) > 0:
kwargs = ", " + kwargs
return head_repr_fmt.format(
head=expr.__class__.__name__,
args=", ".join([sub_render(arg) for arg in args]),
kwargs=kwargs)
elif isinstance(expr, (tuple, list)):
delims = ("(", ")") if isinstance(expr, tuple) else ("[", "]")
if len(expr) == 1:
delims = (delims[0], "," + delims[1])
return (
delims[0] +
", ".join([
render_head_repr(
v, sub_render=sub_render, key_sub_render=key_sub_render)
for v in expr]) +
delims[1])
else:
return sympy_srepr(expr)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_rules_dict(rules):
"""Verify the `rules` that classes may use for the `_rules` or `_binary_rules` class attribute. Specifically, `rules` must be a :class:`~collections.OrderedDict`-compatible object (list of key-value tuples, :class:`dict`, :class:`~collections.OrderedDict`) that maps a rule name (:class:`str`) to a rule. Each rule consists of a :class:`~qnet.algebra.pattern_matching.Pattern` and a replaceent callable. The Pattern must be set up to match a :class:`~qnet.algebra.pattern_matching.ProtoExpr`. That is, the Pattern should be constructed through the :func:`~qnet.algebra.pattern_matching.pattern_head` routine. Raises: TypeError: If `rules` is not compatible with :class:`~collections.OrderedDict`, the keys in `rules` are not strings, or rule is not a tuple of (:class:`~qnet.algebra.pattern_matching.Pattern`, `callable`) ValueError: If the `head`-attribute of each Pattern is not an instance of :class:`~qnet.algebra.pattern_matching.ProtoExpr`, or if there are duplicate keys in `rules` Returns: :class:`~collections.OrderedDict` of rules """
|
from qnet.algebra.pattern_matching import Pattern, ProtoExpr
if hasattr(rules, 'items'):
items = rules.items() # `rules` is already a dict / OrderedDict
else:
items = rules # `rules` is a list of (key, value) tuples
keys = set()
for key_rule in items:
try:
key, rule = key_rule
except ValueError:
raise TypeError("rules does not contain (key, rule) tuples")
if not isinstance(key, str):
raise TypeError("Key '%s' is not a string" % key)
if key in keys:
raise ValueError("Duplicate key '%s'" % key)
else:
keys.add(key)
try:
pat, replacement = rule
except TypeError:
raise TypeError(
"Rule in '%s' is not a (pattern, replacement) tuple" % key)
if not isinstance(pat, Pattern):
raise TypeError(
"Pattern in '%s' is not a Pattern instance" % key)
if pat.head is not ProtoExpr:
raise ValueError(
"Pattern in '%s' does not match a ProtoExpr" % key)
if not callable(replacement):
raise ValueError(
"replacement in '%s' is not callable" % key)
else:
arg_names = inspect.signature(replacement).parameters.keys()
if not arg_names == pat.wc_names:
raise ValueError(
"arguments (%s) of replacement function differ from the "
"wildcard names (%s) in pattern" % (
", ".join(sorted(arg_names)),
", ".join(sorted(pat.wc_names))))
return OrderedDict(rules)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def derationalize_denom(expr):
"""Try to de-rationalize the denominator of the given expression. The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from ``sqrt(2)/2``. Specifically, this matches `expr` against the following pattern:: and returns a tuple ``(numerator, denom_sq, post_factor)``, where ``numerator`` and ``denom_sq`` are ``n`` and ``d`` in the above pattern (of type `int`), respectively, and ``post_factor`` is the product of the following identity:: (numerator / sqrt(denom_sq)) * post_factor == expr If `expr` does not follow the appropriate pattern, a :exc:`ValueError` is raised. """
|
r_pos = -1
p_pos = -1
numerator = S.Zero
denom_sq = S.One
post_factors = []
if isinstance(expr, Mul):
for pos, factor in enumerate(expr.args):
if isinstance(factor, Rational) and r_pos < 0:
r_pos = pos
numerator, denom_sq = factor.p, factor.q
elif isinstance(factor, Pow) and r_pos >= 0:
if factor == sqrt(denom_sq):
p_pos = pos
else:
post_factors.append(factor)
else:
post_factors.append(factor)
if r_pos >= 0 and p_pos >= 0:
return numerator, denom_sq, Mul(*post_factors)
else:
raise ValueError("Cannot derationalize")
else:
raise ValueError("expr is not a Mul instance")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entries(self):
""" Return the entries that are published under this node. """
|
# Since there is currently no filtering in place, return all entries.
EntryModel = get_entry_model()
qs = get_entry_model().objects.order_by('-publication_date')
# Only limit to current language when this makes sense.
if issubclass(EntryModel, TranslatableModel):
admin_form_language = self.get_current_language() # page object is in current language tab.
qs = qs.active_translations(admin_form_language).language(admin_form_language)
return qs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_entry_url(self, entry):
""" Return the URL of a blog entry, relative to this page. """
|
# It could be possible this page is fetched as fallback, while the 'entry' does have a translation.
# - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the language of retrieval
# as current object language. The page is not assigned a fallback language instead.
# - With i18n_patterns() that would make strange URLs, such as '/en/blog/2016/05/dutch-entry-title/'
# Hence, respect the entry language as starting point to make the language consistent.
with switch_language(self, entry.get_current_language()):
return self.get_absolute_url() + entry.get_relative_url()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_placeholder(self, slot="blog_contents", role='m', title=None):
""" Create a placeholder on this blog entry. To fill the content items, use :func:`ContentItemModel.objects.create_for_placeholder() <fluent_contents.models.managers.ContentItemManager.create_for_placeholder>`. :rtype: :class:`~fluent_contents.models.Placeholder` """
|
return Placeholder.objects.create_for_object(self, slot, role=role, title=title)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_as_png(self, filename, width=300, height=250, render_time=1):
"""Open saved html file in an virtual browser and save a screen shot to PNG format."""
|
self.driver.set_window_size(width, height)
self.driver.get('file://{path}/{filename}'.format(
path=os.getcwd(), filename=filename + ".html"))
time.sleep(render_time)
self.driver.save_screenshot(filename + ".png")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version(filename):
"""Extract the package version"""
|
with open(filename) as in_fh:
for line in in_fh:
if line.startswith('__version__'):
return line.split('=')[1].strip()[1:-1]
raise ValueError("Cannot extract version from %s" % filename)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_year(year):
""" Format the year value of the ``YearArchiveView``, which can be a integer or date object. This tag is no longer needed, but exists for template compatibility. It was a compatibility tag for Django 1.4. """
|
if isinstance(year, (date, datetime)):
# Django 1.5 and up, 'year' is a date object, consistent with month+day views.
return unicode(year.year)
else:
# Django 1.4 just passes the kwarg as string.
return unicode(year)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def free_symbols(self):
"""Set of all free symbols"""
|
return set([
sym for sym in self.term.free_symbols
if sym not in self.bound_symbols])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terms(self):
"""Iterator over the terms of the sum Yield from the (possibly) infinite list of terms of the indexed sum, if the sum was written out explicitly. Each yielded term in an instance of :class:`.Expression` """
|
from qnet.algebra.core.scalar_algebra import ScalarValue
for mapping in yield_from_ranges(self.ranges):
term = self.term.substitute(mapping)
if isinstance(term, ScalarValue._val_types):
term = ScalarValue.create(term)
assert isinstance(term, Expression)
yield term
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doit( self, classes=None, recursive=True, indices=None, max_terms=None, **kwargs):
"""Write out the indexed sum explicitly If `classes` is None or :class:`IndexedSum` is in `classes`, (partially) write out the indexed sum in to an explicit sum of terms. If `recursive` is True, write out each of the new sum's summands by calling its :meth:`doit` method. Args: classes (None or list):
see :meth:`.Expression.doit` recursive (bool):
see :meth:`.Expression.doit` indices (list):
List of :class:`IdxSym` indices for which the sum should be expanded. If `indices` is a subset of the indices over which the sum runs, it will be partially expanded. If not given, expand the sum completely max_terms (int):
Number of terms after which to truncate the sum. This is particularly useful for infinite sums. If not given, expand all terms of the sum. Cannot be combined with `indices` kwargs: keyword arguments for recursive calls to :meth:`doit`. See :meth:`.Expression.doit` """
|
return super().doit(
classes, recursive, indices=indices, max_terms=max_terms, **kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_disjunct_indices(self, *others):
"""Return a copy with modified indices to ensure disjunct indices with `others`. Each element in `others` may be an index symbol (:class:`.IdxSym`), a index-range object (:class:`.IndexRangeBase`) or list of index-range objects, or an indexed operation (something with a ``ranges`` attribute) Each index symbol is primed until it does not match any index symbol in `others`. """
|
new = self
other_index_symbols = set()
for other in others:
try:
if isinstance(other, IdxSym):
other_index_symbols.add(other)
elif isinstance(other, IndexRangeBase):
other_index_symbols.add(other.index_symbol)
elif hasattr(other, 'ranges'):
other_index_symbols.update(
[r.index_symbol for r in other.ranges])
else:
other_index_symbols.update(
[r.index_symbol for r in other])
except AttributeError:
raise ValueError(
"Each element of other must be an an instance of IdxSym, "
"IndexRangeBase, an object with a `ranges` attribute "
"with a list of IndexRangeBase instances, or a list of"
"IndexRangeBase objects.")
for r in self.ranges:
index_symbol = r.index_symbol
modified = False
while index_symbol in other_index_symbols:
modified = True
index_symbol = index_symbol.incr_primed()
if modified:
new = new._substitute(
{r.index_symbol: index_symbol}, safe=True)
return new
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_field_js_assets(*args):
""" Tag to render CodeMirror Javascript assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_js_assets form.myfield1 form.myfield2 %} """
|
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(*args)
return mark_safe(manifesto.js_html())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_field_css_assets(*args):
""" Tag to render CodeMirror CSS assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_css_assets form.myfield1 form.myfield2 %} """
|
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(*args)
return mark_safe(manifesto.css_html())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_field_js_bundle(field):
""" Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_js_bundle }} Arguments: field (django.forms.fields.Field):
A form field that contains a widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Raises: CodeMirrorFieldBundleError: If Codemirror configuration form field does not have a bundle name. Returns: string: Bundle name to load with webassets. """
|
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(field)
try:
bundle_name = manifesto.js_bundle_names()[0]
except IndexError:
msg = ("Given field with configuration name '{}' does not have a "
"Javascript bundle name")
raise CodeMirrorFieldBundleError(msg.format(field.config_name))
return bundle_name
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_field_css_bundle(field):
""" Filter to get CodeMirror CSS bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_css_bundle }} Arguments: field (djangocodemirror.fields.CodeMirrorField):
A form field. Raises: CodeMirrorFieldBundleError: Raised if Codemirror configuration from field does not have a bundle name. Returns: string: Bundle name to load with webassets. """
|
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(field)
try:
bundle_name = manifesto.css_bundle_names()[0]
except IndexError:
msg = ("Given field with configuration name '{}' does not have a "
"Javascript bundle name")
raise CodeMirrorFieldBundleError(msg.format(field.config_name))
return bundle_name
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_parameters(field):
""" Filter to include CodeMirror parameters as a JSON string for a single field. This must be called only on an allready rendered field, meaning you must not use this filter on a field before a form. Else, the field widget won't be correctly initialized. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_parameters }} Arguments: field (djangocodemirror.fields.CodeMirrorField):
A form field. Returns: string: JSON object for parameters, marked safe for Django templates. """
|
manifesto = CodemirrorAssetTagRender()
names = manifesto.register_from_fields(field)
config = manifesto.get_codemirror_parameters(names[0])
return mark_safe(json.dumps(config))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_instance(config_name, varname, element_id, assets=True):
""" Return HTML to init a CodeMirror instance for an element. This will output the whole HTML needed to initialize a CodeMirror instance with needed assets loading. Assets can be omitted with the ``assets`` option. Example: :: {% load djangocodemirror_tags %} {% codemirror_instance 'a-config-name' 'foo_codemirror' 'foo' %} Arguments: config_name (string):
A registred config name. varname (string):
A Javascript variable name. element_id (string):
An HTML element identifier (without leading ``#``) to attach to a CodeMirror instance. Keyword Arguments: assets (Bool):
Adds needed assets before the HTML if ``True``, else only CodeMirror instance will be outputed. Default value is ``True``. Returns: string: HTML. """
|
output = io.StringIO()
manifesto = CodemirrorAssetTagRender()
manifesto.register(config_name)
if assets:
output.write(manifesto.css_html())
output.write(manifesto.js_html())
html = manifesto.codemirror_html(config_name, varname, element_id)
output.write(html)
content = output.getvalue()
output.close()
return mark_safe(content)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_widget(self, field):
""" Given a Field or BoundField, return widget instance. Todo: Raise an exception if given field object does not have a widget. Arguments: field (Field or BoundField):
A field instance. Returns: django.forms.widgets.Widget: Retrieved widget from given field. """
|
# When filter is used within template we have to reach the field
# instance through the BoundField.
if hasattr(field, 'field'):
widget = field.field.widget
# When used out of template, we have a direct field instance
else:
widget = field.widget
return widget
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_from_fields(self, *args):
""" Register config name from field widgets Arguments: *args: Fields that contains widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Returns: list: List of registered config names from fields. """
|
names = []
for field in args:
widget = self.resolve_widget(field)
self.register(widget.config_name)
if widget.config_name not in names:
names.append(widget.config_name)
return names
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_asset_html(self, path, tag_template):
""" Render HTML tag for a given path. Arguments: path (string):
Relative path from static directory. tag_template (string):
Template string for HTML tag. Returns: string: HTML tag with url from given path. """
|
url = os.path.join(settings.STATIC_URL, path)
return tag_template.format(url=url)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_html(self, config_name, varname, element_id):
""" Render HTML for a CodeMirror instance. Since a CodeMirror instance have to be attached to a HTML element, this method requires a HTML element identifier with or without the ``#`` prefix, it depends from template in ``settings.CODEMIRROR_FIELD_INIT_JS`` (default one require to not prefix with ``#``). Arguments: config_name (string):
A registred config name. varname (string):
A Javascript variable name. element_id (string):
An HTML element identifier (without leading ``#``) to attach to a CodeMirror instance. Returns: string: HTML to instanciate CodeMirror for a field input. """
|
parameters = json.dumps(self.get_codemirror_parameters(config_name),
sort_keys=True)
return settings.CODEMIRROR_FIELD_INIT_JS.format(
varname=varname,
inputid=element_id,
settings=parameters,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_apidoc(_):
"""Generage API documentation"""
|
import better_apidoc
better_apidoc.main([
'better-apidoc',
'-t',
os.path.join('.', '_templates'),
'--force',
'--no-toc',
'--separate',
'-o',
os.path.join('.', 'API'),
os.path.join('..', 'src', 'qnet'),
])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shorten_render(renderer, max_len):
that representation is longer than `max_len`"""
|
def short_renderer(expr):
res = renderer(expr)
if len(res) > max_len:
return '...'
else:
return res
return short_renderer
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_algebra(*, default_hs_cls='LocalSpace'):
"""Initialize the algebra system Args: default_hs_cls (str):
The name of the :class:`.LocalSpace` subclass that should be used when implicitly creating Hilbert spaces, e.g. in :class:`.OperatorSymbol` """
|
from qnet.algebra.core.hilbert_space_algebra import LocalSpace
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression
default_hs_cls = getattr(importlib.import_module('qnet'), default_hs_cls)
if issubclass(default_hs_cls, LocalSpace):
QuantumExpression._default_hs_cls = default_hs_cls
else:
raise TypeError("default_hs_cls must be a subclass of LocalSpace")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, name):
""" Register configuration for an editor instance. Arguments: name (string):
Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Raises: UnknowConfigError: If given config name does not exist in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Registred config dict. """
|
if name not in settings.CODEMIRROR_SETTINGS:
msg = ("Given config name '{}' does not exists in "
"'settings.CODEMIRROR_SETTINGS'.")
raise UnknowConfigError(msg.format(name))
parameters = copy.deepcopy(self.default_internal_config)
parameters.update(copy.deepcopy(
settings.CODEMIRROR_SETTINGS[name]
))
# Add asset bundles name
if 'css_bundle_name' not in parameters:
css_template_name = settings.CODEMIRROR_BUNDLE_CSS_NAME
parameters['css_bundle_name'] = css_template_name.format(
settings_name=name
)
if 'js_bundle_name' not in parameters:
js_template_name = settings.CODEMIRROR_BUNDLE_JS_NAME
parameters['js_bundle_name'] = js_template_name.format(
settings_name=name
)
self.registry[name] = parameters
return parameters
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_many(self, *args):
""" Register many configuration names. Arguments: *args: Config names as strings. Returns: list: List of registered configs. """
|
params = []
for name in args:
params.append(self.register(name))
return params
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_mode(self, name):
""" From given mode name, return mode file path from ``settings.CODEMIRROR_MODES`` map. Arguments: name (string):
Mode name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_MODES``. Returns: string: Mode file path. """
|
if name not in settings.CODEMIRROR_MODES:
msg = ("Given config name '{}' does not exists in "
"'settings.CODEMIRROR_MODES'.")
raise UnknowModeError(msg.format(name))
return settings.CODEMIRROR_MODES.get(name)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_theme(self, name):
""" From given theme name, return theme file path from ``settings.CODEMIRROR_THEMES`` map. Arguments: name (string):
Theme name. Raises: KeyError: When given name does not exist in ``settings.CODEMIRROR_THEMES``. Returns: string: Theme file path. """
|
if name not in settings.CODEMIRROR_THEMES:
msg = ("Given theme name '{}' does not exists in "
"'settings.CODEMIRROR_THEMES'.")
raise UnknowThemeError(msg.format(name))
return settings.CODEMIRROR_THEMES.get(name)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_configs(self, name=None):
""" Returns registred configurations. * If ``name`` argument is not given, default behavior is to return every config from all registred config; * If ``name`` argument is given, just return its config and nothing else; Keyword Arguments: name (string):
Specific configuration name to return. Raises: NotRegisteredError: If given config name does not exist in registry. Returns: dict: Configurations. """
|
if name:
if name not in self.registry:
msg = "Given config name '{}' is not registered."
raise NotRegisteredError(msg.format(name))
return {name: self.registry[name]}
return self.registry
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_config(self, name):
""" Return a registred configuration for given config name. Arguments: name (string):
A registred config name. Raises: NotRegisteredError: If given config name does not exist in registry. Returns: dict: Configuration. """
|
if name not in self.registry:
msg = "Given config name '{}' is not registered."
raise NotRegisteredError(msg.format(name))
return copy.deepcopy(self.registry[name])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_codemirror_parameters(self, name):
""" Return CodeMirror parameters for given configuration name. This is a reduced configuration from internal parameters. Arguments: name (string):
Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Parameters. """
|
config = self.get_config(name)
return {k: config[k] for k in config if k not in self._internal_only}
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commutator(A, B=None):
"""Commutator of `A` and `B` If ``B != None``, return the commutator :math:`[A,B]`, otherwise return the super-operator :math:`[A,\cdot]`. The super-operator :math:`[A,\cdot]` maps any other operator ``B`` to the commutator :math:`[A, B] = A B - B A`. Args: A: The first operator to form the commutator of. B: The second operator to form the commutator of, or None. Returns: SuperOperator: The linear superoperator :math:`[A,\cdot]` """
|
if B:
return A * B - B * A
return SPre(A) - SPost(A)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def liouvillian(H, Ls=None):
r"""Return the Liouvillian super-operator associated with `H` and `Ls` The Liouvillian :math:`\mathcal{L}` generates the Markovian-dynamics of a system via the Master equation: .. math:: \dot{\rho} = \mathcal{L}\rho = -i[H,\rho] + \sum_{j=1}^n \mathcal{D}[L_j] \rho Args: H (Operator):
The associated Hamilton operator Ls (sequence or Matrix):
A sequence of Lindblad operators. Returns: SuperOperator: The Liouvillian super-operator. """
|
if Ls is None:
Ls = []
elif isinstance(Ls, Matrix):
Ls = Ls.matrix.ravel().tolist()
summands = [-I * commutator(H), ]
summands.extend([lindblad(L) for L in Ls])
return SuperOperatorPlus.create(*summands)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_matrix(A, B, C, D):
r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix):
Matrix of shape ``(n, m)`` B (Matrix):
Matrix of shape ``(n, k)`` C (Matrix):
Matrix of shape ``(l, m)`` D (Matrix):
Matrix of shape ``(l, k)`` Returns: Matrix: The combined block matrix ``[[A, B], [C, D]]``. """
|
return vstackm((hstackm((A, B)), hstackm((C, D))))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permutation_matrix(permutation):
r"""Return orthogonal permutation matrix for permutation tuple Return an orthogonal permutation matrix :math:`M_\sigma` for a permutation :math:`\sigma` defined by the image tuple :math:`(\sigma(1), \sigma(2),\dots \sigma(n))`, such that .. math:: M_\sigma \vec{e}_i = \vec{e}_{\sigma(i)} where :math:`\vec{e}_k` is the k-th standard basis vector. This definition ensures a composition law: .. math:: M_{\sigma \cdot \tau} = M_\sigma M_\tau. The column form of :math:`M_\sigma` is thus given by .. math:: M = ( \vec{e}_{\sigma(1)}, \vec{e}_{\sigma(2)}, \dots \vec{e}_{\sigma(n)}). Args: permutation (tuple):
A permutation image tuple (zero-based indices!) """
|
assert check_permutation(permutation)
n = len(permutation)
op_matrix = np_zeros((n, n), dtype=int)
for i, j in enumerate(permutation):
op_matrix[j, i] = 1
return Matrix(op_matrix)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_zero(self):
"""Are all elements of the matrix zero?"""
|
for o in self.matrix.ravel():
try:
if not o.is_zero:
return False
except AttributeError:
if not o == 0:
return False
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conjugate(self):
"""The element-wise conjugate matrix This is defined only if all the entries in the matrix have a defined conjugate (i.e., they have a `conjugate` method). This is *not* the case for a matrix of operators. In such a case, only an :meth:`elementwise` :func:`adjoint` would be applicable, but this is mathematically different from a complex conjugate. Raises: NoConjugateMatrix: if any entries have no `conjugate` method """
|
try:
return Matrix(np_conjugate(self.matrix))
except AttributeError:
raise NoConjugateMatrix(
"Matrix %s contains entries that have no defined "
"conjugate" % str(self))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def real(self):
"""Element-wise real part Raises: NoConjugateMatrix: if entries have no `conjugate` method and no other way to determine the real part Note: A mathematically equivalent way to obtain a real matrix from a complex matrix ``M`` is:: (M.conjugate() + M) / 2 However, the result may not be identical to ``M.real``, as the latter tries to convert elements of the matrix to real values directly, if possible, and only uses the conjugate as a fall-back """
|
def re(val):
if hasattr(val, 'real'):
return val.real
elif hasattr(val, 'as_real_imag'):
return val.as_real_imag()[0]
elif hasattr(val, 'conjugate'):
return (val.conjugate() + val) / 2
else:
raise NoConjugateMatrix(
"Matrix entry %s contains has no defined "
"conjugate" % str(val))
# Note: Do NOT use self.matrix.real! This will give wrong results, as
# numpy thinks of objects (Operators) as real, even if they have no
# defined real part
return self.element_wise(re)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def imag(self):
"""Element-wise imaginary part Raises: NoConjugateMatrix: if entries have no `conjugate` method and no other way to determine the imaginary part Note: A mathematically equivalent way to obtain an imaginary matrix from a complex matrix ``M`` is:: (M.conjugate() - M) / (I * 2) with same same caveats as :attr:`real`. """
|
def im(val):
if hasattr(val, 'imag'):
return val.imag
elif hasattr(val, 'as_real_imag'):
return val.as_real_imag()[1]
elif hasattr(val, 'conjugate'):
return (val.conjugate() - val) / (2 * I)
else:
raise NoConjugateMatrix(
"Matrix entry %s contains has no defined "
"conjugate" % str(val))
# Note: Do NOT use self.matrix.real! This will give wrong results, as
# numpy thinks of objects (Operators) as real, even if they have no
# defined real part
return self.element_wise(im)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def element_wise(self, func, *args, **kwargs):
"""Apply a function to each matrix element and return the result in a new operator matrix of the same shape. Args: func (FunctionType):
A function to be applied to each element. It must take the element as its first argument. args: Additional positional arguments to be passed to `func` kwargs: Additional keyword arguments to be passed to `func` Returns: Matrix: Matrix with results of `func`, applied element-wise. """
|
s = self.shape
emat = [func(o, *args, **kwargs) for o in self.matrix.ravel()]
return Matrix(np_array(emat).reshape(s))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def series_expand(self, param: Symbol, about, order: int):
"""Expand the matrix expression as a truncated power series in a scalar parameter. Args: param: Expansion parameter. about (.Scalar):
Point about which to expand. order: Maximum order of expansion >= 0 Returns: tuple of length (order+1), where the entries are the expansion coefficients. """
|
s = self.shape
emats = zip(*[o.series_expand(param, about, order)
for o in self.matrix.ravel()])
return tuple((Matrix(np_array(em).reshape(s)) for em in emats))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand(self):
"""Expand each matrix element distributively. Returns: Matrix: Expanded matrix. """
|
return self.element_wise(
lambda o: o.expand() if isinstance(o, QuantumExpression) else o)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def space(self):
"""Combined Hilbert space of all matrix elements."""
|
arg_spaces = [o.space for o in self.matrix.ravel()
if hasattr(o, 'space')]
if len(arg_spaces) == 0:
return TrivialSpace
else:
return ProductSpace.create(*arg_spaces)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simplify_scalar(self, func=sympy.simplify):
"""Simplify all scalar expressions appearing in the Matrix."""
|
def element_simplify(v):
if isinstance(v, sympy.Basic):
return func(v)
elif isinstance(v, QuantumExpression):
return v.simplify_scalar(func=func)
else:
return v
return self.element_wise(element_simplify)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_initial(self):
""" Try to find a demo source for given mode if any, if finded use it to fill the demo textarea. """
|
initial = {}
if self.kwargs.get('mode', None):
filename = "{}.txt".format(self.kwargs['mode'])
filepath = os.path.join(settings.BASE_DIR, 'demo_datas', filename)
if os.path.exists(filepath):
with io.open(filepath, 'r', encoding='utf-8') as fp:
initial['foo'] = fp.read()
return initial
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_order_by(order, orderby, order_by_fields):
""" Return the order by syntax for a model. Checks whether use ascending or descending order, and maps the fieldnames. """
|
try:
# Find the actual database fieldnames for the keyword.
db_fieldnames = order_by_fields[orderby]
except KeyError:
raise ValueError("Invalid value for 'orderby': '{0}', supported values are: {1}".format(orderby, ', '.join(sorted(order_by_fields.keys()))))
# Default to descending for some fields, otherwise be ascending
is_desc = (not order and orderby in ORDER_BY_DESC) \
or (order or 'asc').lower() in ('desc', 'descending')
if is_desc:
return map(lambda name: '-' + name, db_fieldnames)
else:
return db_fieldnames
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_entries( queryset=None, year=None, month=None, day=None, category=None, category_slug=None, tag=None, tag_slug=None, author=None, author_slug=None, future=False, order=None, orderby=None, limit=None, ):
""" Query the entries using a set of predefined filters. This interface is mainly used by the ``get_entries`` template tag. """
|
if queryset is None:
queryset = get_entry_model().objects.all()
if appsettings.FLUENT_BLOGS_FILTER_SITE_ID:
queryset = queryset.parent_site(settings.SITE_ID)
if not future:
queryset = queryset.published()
if year:
queryset = queryset.filter(publication_date__year=year)
if month:
queryset = queryset.filter(publication_date__month=month)
if day:
queryset = queryset.filter(publication_date__day=day)
# The main category/tag/author filters
if category:
if isinstance(category, basestring):
queryset = queryset.categories(category)
elif isinstance(category, (int, long)):
queryset = queryset.filter(categories=category)
else:
raise ValueError("Expected slug or ID for the 'category' parameter")
if category_slug:
queryset = queryset.categories(category)
if tag:
if isinstance(tag, basestring):
queryset = queryset.tagged(tag)
elif isinstance(tag, (int, long)):
queryset = queryset.filter(tags=tag)
else:
raise ValueError("Expected slug or ID for 'tag' parameter.")
if tag_slug:
queryset = queryset.tagged(tag)
if author:
if isinstance(author, basestring):
queryset = queryset.authors(author)
elif isinstance(author, (int, long)):
queryset = queryset.filter(author=author)
else:
raise ValueError("Expected slug or ID for 'author' parameter.")
if author_slug:
queryset = queryset.authors(author_slug)
# Ordering
if orderby:
queryset = queryset.order_by(*_get_order_by(order, orderby, ENTRY_ORDER_BY_FIELDS))
else:
queryset = queryset.order_by('-publication_date')
# Limit
if limit:
queryset = queryset[:limit]
return queryset
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_tags(order=None, orderby=None, limit=None):
""" Query the tags, with usage count included. This interface is mainly used by the ``get_tags`` template tag. """
|
from taggit.models import Tag, TaggedItem # feature is still optional
# Get queryset filters for published entries
EntryModel = get_entry_model()
ct = ContentType.objects.get_for_model(EntryModel) # take advantage of local caching.
entry_filter = {
'status': EntryModel.PUBLISHED
}
if appsettings.FLUENT_BLOGS_FILTER_SITE_ID:
entry_filter['parent_site'] = settings.SITE_ID
entry_qs = EntryModel.objects.filter(**entry_filter).values_list('pk')
# get tags
queryset = Tag.objects.filter(
taggit_taggeditem_items__content_type=ct,
taggit_taggeditem_items__object_id__in=entry_qs
).annotate(
count=Count('taggit_taggeditem_items')
)
# Ordering
if orderby:
queryset = queryset.order_by(*_get_order_by(order, orderby, TAG_ORDER_BY_FIELDS))
else:
queryset = queryset.order_by('-count')
# Limit
if limit:
queryset = queryset[:limit]
return queryset
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_category_for_slug(slug, language_code=None):
""" Find the category for a given slug """
|
Category = get_category_model()
if issubclass(Category, TranslatableModel):
return Category.objects.active_translations(language_code, slug=slug).get()
else:
return Category.objects.get(slug=slug)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_date_range(year=None, month=None, day=None):
""" Return a start..end range to query for a specific month, day or year. """
|
if year is None:
return None
if month is None:
# year only
start = datetime(year, 1, 1, 0, 0, 0, tzinfo=utc)
end = datetime(year, 12, 31, 23, 59, 59, 999, tzinfo=utc)
return (start, end)
if day is None:
# year + month only
start = datetime(year, month, 1, 0, 0, 0, tzinfo=utc)
end = start + timedelta(days=monthrange(year, month)[1], microseconds=-1)
return (start, end)
else:
# Exact day
start = datetime(year, month, day, 0, 0, 0, tzinfo=utc)
end = start + timedelta(days=1, microseconds=-1)
return (start, end)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pattern(head, *args, mode=1, wc_name=None, conditions=None, **kwargs) \ -> Pattern: """'Flat' constructor for the Pattern class Positional and keyword arguments are mapped into `args` and `kwargs`, respectively. Useful for defining rules that match an instantiated Expression with specific arguments """
|
if len(args) == 0:
args = None
if len(kwargs) == 0:
kwargs = None
return Pattern(head, args, kwargs, mode=mode, wc_name=wc_name,
conditions=conditions)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict: """Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either a direct expression (equal to `expr` for a successful match), or an instance of :class:`Pattern`. expr: the expression to be matched """
|
try: # first try expr_or_pattern as a Pattern
return expr_or_pattern.match(expr)
except AttributeError: # expr_or_pattern is an expr, not a Pattern
if expr_or_pattern == expr:
return MatchDict() # success
else:
res = MatchDict()
res.success = False
res.reason = "Expressions '%s' and '%s' are not the same" % (
repr(expr_or_pattern), repr(expr))
return res
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, *others):
"""Update dict with entries from `other` If `other` has an attribute ``success=False`` and ``reason``, those attributes are copied as well """
|
for other in others:
for key, val in other.items():
self[key] = val
try:
if not other.success:
self.success = False
self.reason = other.reason
except AttributeError:
pass
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extended_arg_patterns(self):
"""Iterator over patterns for positional arguments to be matched This yields the elements of :attr:`args`, extended by their `mode` value """
|
for arg in self._arg_iterator(self.args):
if isinstance(arg, Pattern):
if arg.mode > self.single:
while True:
yield arg
else:
yield arg
else:
yield arg
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finditer(self, expr):
"""Return an iterator over all matches in `expr` Iterate over all :class:`MatchDict` results of matches for any matching (sub-)expressions in `expr`. The order of the matches conforms to the equivalent matched expressions returned by :meth:`findall`. """
|
try:
for arg in expr.args:
for m in self.finditer(arg):
yield m
for arg in expr.kwargs.values():
for m in self.finditer(arg):
yield m
except AttributeError:
pass
m = self.match(expr)
if m:
yield m
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wc_names(self):
"""Set of all wildcard names occurring in the pattern"""
|
if self.wc_name is None:
res = set()
else:
res = set([self.wc_name])
if self.args is not None:
for arg in self.args:
if isinstance(arg, Pattern):
res.update(arg.wc_names)
if self.kwargs is not None:
for val in self.kwargs.values():
if isinstance(val, Pattern):
res.update(val.wc_names)
return res
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_expr(cls, expr):
"""Instantiate proto-expression from the given Expression"""
|
return cls(expr.args, expr.kwargs, cls=expr.__class__)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_entry_model():
""" Return the actual entry model that is in use. This function reads the :ref:`FLUENT_BLOGS_ENTRY_MODEL` setting to find the model. The model is automatically registered with *django-fluent-comments* and *django-any-urlfield* when it's installed. """
|
global _EntryModel
if _EntryModel is None:
# This method is likely called the first time when the admin initializes, the sitemaps module is imported, or BaseBlogMixin is used.
# Either way, it needs to happen after all apps have initialized, to make sure the model can be imported.
if not appsettings.FLUENT_BLOGS_ENTRY_MODEL:
_EntryModel = Entry
else:
app_label, model_name = appsettings.FLUENT_BLOGS_ENTRY_MODEL.rsplit('.', 1)
_EntryModel = apps.get_model(app_label, model_name)
if _EntryModel is None:
raise ImportError("{app_label}.{model_name} could not be imported.".format(app_label=app_label, model_name=model_name))
# Auto-register with django-fluent-comments moderation
if 'fluent_comments' in settings.INSTALLED_APPS and issubclass(_EntryModel, CommentsEntryMixin):
from fluent_comments.moderation import moderate_model
moderate_model(
_EntryModel,
publication_date_field='publication_date',
enable_comments_field='enable_comments',
)
# Auto-register with django-any-urlfield
if 'any_urlfield' in settings.INSTALLED_APPS:
from any_urlfield.models import AnyUrlField
from any_urlfield.forms.widgets import SimpleRawIdWidget
AnyUrlField.register_model(_EntryModel, widget=SimpleRawIdWidget(_EntryModel))
return _EntryModel
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_category_model():
""" Return the category model to use. This function reads the :ref:`FLUENT_BLOGS_CATEGORY_MODEL` setting to find the model. """
|
app_label, model_name = appsettings.FLUENT_BLOGS_CATEGORY_MODEL.rsplit('.', 1)
try:
return apps.get_model(app_label, model_name)
except Exception as e: # ImportError/LookupError
raise ImproperlyConfigured("Failed to import FLUENT_BLOGS_CATEGORY_MODEL '{0}': {1}".format(
appsettings.FLUENT_BLOGS_CATEGORY_MODEL, str(e)
))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def blog_reverse(viewname, args=None, kwargs=None, current_app='fluent_blogs', **page_kwargs):
""" Reverse a URL to the blog, taking various configuration options into account. This is a compatibility function to allow django-fluent-blogs to operate stand-alone. Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of *django-fluent-pages*. """
|
return mixed_reverse(viewname, args=args, kwargs=kwargs, current_app=current_app, **page_kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_commutators_leibniz(expr, expand_expr=True):
"""Recursively expand commutators in `expr` according to the Leibniz rule. .. math:: [A B, C] = A [B, C] + [A, C] B .. math:: [A, B C] = [A, B] C + B [A, C] If `expand_expr` is True, expand products of sums in `expr`, as well as in the result. """
|
recurse = partial(expand_commutators_leibniz, expand_expr=expand_expr)
A = wc('A', head=Operator)
C = wc('C', head=Operator)
AB = wc('AB', head=OperatorTimes)
BC = wc('BC', head=OperatorTimes)
def leibniz_right(A, BC):
"""[A, BC] -> [A, B] C + B [A, C]"""
B = BC.operands[0]
C = OperatorTimes.create(*BC.operands[1:])
return Commutator.create(A, B) * C + B * Commutator.create(A, C)
def leibniz_left(AB, C):
"""[AB, C] -> A [B, C] C + [A, C] B"""
A = AB.operands[0]
B = OperatorTimes(*AB.operands[1:])
return A * Commutator.create(B, C) + Commutator.create(A, C) * B
rules = OrderedDict([
('leibniz1', (
pattern(Commutator, A, BC),
lambda A, BC: recurse(leibniz_right(A, BC).expand()))),
('leibniz2', (
pattern(Commutator, AB, C),
lambda AB, C: recurse(leibniz_left(AB, C).expand())))])
if expand_expr:
res = _apply_rules(expr.expand(), rules).expand()
else:
res = _apply_rules(expr, rules)
return res
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_printing(*, reset=False, init_sympy=True, **kwargs):
"""Initialize the printing system. This determines the behavior of the :func:`ascii`, :func:`unicode`, and :func:`latex` functions, as well as the ``__str__`` and ``__repr__`` of any :class:`.Expression`. The routine may be called in one of two forms. First, :: init_printing( str_format=<str_fmt>, repr_format=<repr_fmt>, caching=<use_caching>, **settings) provides a simplified, "manual" setup with the following parameters. Args: str_format (str):
Format for ``__str__`` representation of an :class:`.Expression`. One of 'ascii', 'unicode', 'latex', 'srepr', 'indsrepr' ("indented `srepr`"), or 'tree'. The string representation will be affected by the settings for the corresponding print routine, e.g. :func:`unicode` for ``str_format='unicode'`` repr_format (str):
Like `str_format`, but for ``__repr__``. This is what gets displayed in an interactive (I)Python session. caching (bool):
By default, the printing functions (:func:`ascii`, :func:`unicode`, :func:`latex`) cache their result for any expression and sub-expression. This is both for efficiency and to give the ability to to supply custom strings for subexpression by passing a `cache` parameter to the printing functions. Initializing the printing system with ``caching=False`` disables this possibility. settings: Any setting understood by any of the printing routines. Second, :: init_printing(inifile=<path_to_file>) allows for more detailed settings through a config file, see the :ref:`notes on using an INI file <ini_file_printing>`. If `str_format` or `repr_format` are not given, they will be set to 'unicode' if the current terminal is known to support an UTF8 (accordig to ``sys.stdout.encoding``), and 'ascii' otherwise. Generally, :func:`init_printing` should be called only once at the beginning of a script or notebook. If it is called multiple times, any settings accumulate. To avoid this and to reset the printing system to the defaults, you may pass ``reset=True``. In a Jupyter notebook, expressions are rendered graphically via LaTeX, using the settings as they affect the :func:`latex` printer. The :func:`sympy.init_printing()` routine is called automatically, unless `init_sympy` is given as ``False``. See also: :func:`configure_printing` allows to temporarily change the printing system from what was configured in :func:`init_printing`. """
|
# return either None (default) or a dict of frozen attributes if
# ``_freeze=True`` is given as a keyword argument (internal use in
# `configure_printing` only)
logger = logging.getLogger(__name__)
if reset:
SympyPrinter._global_settings = {}
if init_sympy:
if kwargs.get('repr_format', '') == 'unicode':
sympy_init_printing(use_unicode=True)
if kwargs.get('repr_format', '') == 'ascii':
sympy_init_printing(use_unicode=False)
else:
sympy_init_printing() # let sympy decide by itself
if 'inifile' in kwargs:
invalid_kwargs = False
if '_freeze' in kwargs:
_freeze = kwargs['_freeze']
if len(kwargs) != 2:
invalid_kwargs = True
else:
_freeze = False
if len(kwargs) != 1:
invalid_kwargs = True
if invalid_kwargs:
raise TypeError(
"The `inifile` argument cannot be combined with any "
"other keyword arguments")
logger.debug(
"Initializating printing from INI file %s", kwargs['inifile'])
return _init_printing_from_file(kwargs['inifile'], _freeze=_freeze)
else:
logger.debug(
"Initializating printing with direct settings: %s", repr(kwargs))
return _init_printing(**kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_printing(**kwargs):
"""Context manager for temporarily changing the printing system. This takes the same parameters as :func:`init_printing` Example: A + B A^(1) + B^(1) """
|
freeze = init_printing(_freeze=True, **kwargs)
try:
yield
finally:
for obj, attr_map in freeze.items():
for attr, val in attr_map.items():
setattr(obj, attr, val)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_qutip(expr, full_space=None, mapping=None):
"""Convert a QNET expression to a qutip object Args: expr: a QNET expression full_space (HilbertSpace):
The Hilbert space in which `expr` is defined. If not given, ``expr.space`` is used. The Hilbert space must have a well-defined basis. mapping (dict):
A mapping of any (sub-)expression to either a `quip.Qobj` directly, or to a callable that will convert the expression into a `qutip.Qobj`. Useful for e.g. supplying objects for symbols Raises: ValueError: if `expr` is not in `full_space`, or if `expr` cannot be converted. """
|
if full_space is None:
full_space = expr.space
if not expr.space.is_tensor_factor_of(full_space):
raise ValueError(
"expr '%s' must be in full_space %s" % (expr, full_space))
if full_space == TrivialSpace:
raise AlgebraError(
"Cannot convert object in TrivialSpace to qutip. "
"You may pass a non-trivial `full_space`")
if mapping is not None:
if expr in mapping:
ret = mapping[expr]
if isinstance(ret, qutip.Qobj):
return ret
else:
assert callable(ret)
return ret(expr)
if expr is IdentityOperator:
local_spaces = full_space.local_factors
if len(local_spaces) == 0:
raise ValueError("full_space %s does not have local factors"
% full_space)
else:
return qutip.tensor(*[qutip.qeye(s.dimension)
for s in local_spaces])
elif expr is ZeroOperator:
return qutip.tensor(
*[qutip.Qobj(csr_matrix((s.dimension, s.dimension)))
for s in full_space.local_factors]
)
elif isinstance(expr, LocalOperator):
return _convert_local_operator_to_qutip(expr, full_space, mapping)
elif (isinstance(expr, Operator) and isinstance(expr, Operation)):
return _convert_operator_operation_to_qutip(expr, full_space, mapping)
elif isinstance(expr, OperatorTrace):
raise NotImplementedError('Cannot convert OperatorTrace to '
'qutip')
# actually, this is perfectly doable in principle, but requires a bit
# of work
elif isinstance(expr, State):
return _convert_ket_to_qutip(expr, full_space, mapping)
elif isinstance(expr, SuperOperator):
return _convert_superoperator_to_qutip(expr, full_space, mapping)
elif isinstance(expr, Operation):
# This is assumed to be an Operation on states, as we have handled all
# other Operations above. Eventually, a StateOperation should be
# defined as a common superclass for the Operations in the state
# algebra
return _convert_state_operation_to_qutip(expr, full_space, mapping)
elif isinstance(expr, SLH):
# SLH object cannot be converted to a single qutip object, only to a
# nested list of qutip object. That's why a separate routine
# SLH_to_qutip exists
raise ValueError("SLH objects can only be converted using "
"SLH_to_qutip routine")
else:
raise ValueError("Cannot convert '%s' of type %s"
% (str(expr), type(expr)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_local_operator_to_qutip(expr, full_space, mapping):
"""Convert a LocalOperator instance to qutip"""
|
n = full_space.dimension
if full_space != expr.space:
all_spaces = full_space.local_factors
own_space_index = all_spaces.index(expr.space)
return qutip.tensor(
*([qutip.qeye(s.dimension)
for s in all_spaces[:own_space_index]] +
[convert_to_qutip(expr, expr.space, mapping=mapping), ] +
[qutip.qeye(s.dimension)
for s in all_spaces[own_space_index + 1:]])
)
if isinstance(expr, Create):
return qutip.create(n)
elif isinstance(expr, Jz):
return qutip.jmat((expr.space.dimension-1)/2., "z")
elif isinstance(expr, Jplus):
return qutip.jmat((expr.space.dimension-1)/2., "+")
elif isinstance(expr, Jminus):
return qutip.jmat((expr.space.dimension-1)/2., "-")
elif isinstance(expr, Destroy):
return qutip.destroy(n)
elif isinstance(expr, Phase):
arg = complex(expr.operands[1]) * arange(n)
d = np_cos(arg) + 1j * np_sin(arg)
return qutip.Qobj(np_diag(d))
elif isinstance(expr, Displace):
alpha = expr.operands[1]
return qutip.displace(n, alpha)
elif isinstance(expr, Squeeze):
eta = expr.operands[1]
return qutip.displace(n, eta)
elif isinstance(expr, LocalSigma):
j = expr.j
k = expr.k
if isinstance(j, str):
j = expr.space.basis_labels.index(j)
if isinstance(k, str):
k = expr.space.basis_labels.index(k)
ket = qutip.basis(n, j)
bra = qutip.basis(n, k).dag()
return ket * bra
else:
raise ValueError("Cannot convert '%s' of type %s"
% (str(expr), type(expr)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _time_dependent_to_qutip( op, full_space=None, time_symbol=symbols("t", real=True), convert_as='pyfunc'):
"""Convert a possiblty time-dependent operator into the nested-list structure required by QuTiP"""
|
if full_space is None:
full_space = op.space
if time_symbol in op.free_symbols:
op = op.expand()
if isinstance(op, OperatorPlus):
result = []
for o in op.operands:
if time_symbol not in o.free_symbols:
if len(result) == 0:
result.append(convert_to_qutip(o,
full_space=full_space))
else:
result[0] += convert_to_qutip(o, full_space=full_space)
for o in op.operands:
if time_symbol in o.free_symbols:
result.append(_time_dependent_to_qutip(o, full_space,
time_symbol, convert_as))
return result
elif (
isinstance(op, ScalarTimesOperator) and
isinstance(op.coeff, ScalarValue)):
if convert_as == 'pyfunc':
func_no_args = lambdify(time_symbol, op.coeff.val)
if {time_symbol, } == op.coeff.free_symbols:
def func(t, args):
# args are ignored for increased efficiency, since we
# know there are no free symbols except t
return func_no_args(t)
else:
def func(t, args):
return func_no_args(t).subs(args)
coeff = func
elif convert_as == 'str':
# a bit of a hack to replace imaginary unit
# TODO: we can probably use one of the sympy code generation
# routines, or lambdify with 'numexpr' to implement this in a
# more robust way
coeff = re.sub("I", "(1.0j)", str(op.coeff.val))
else:
raise ValueError(("Invalid value '%s' for `convert_as`, must "
"be one of 'str', 'pyfunc'") % convert_as)
return [convert_to_qutip(op.term, full_space), coeff]
else:
raise ValueError("op cannot be expressed in qutip. It must have "
"the structure op = sum_i f_i(t) * op_i")
else:
return convert_to_qutip(op, full_space=full_space)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ljust(text, width, fillchar=' '):
"""Left-justify text to a total of `width` The `width` is based on graphemes:: 'Â' 'Â ' """
|
len_text = grapheme_len(text)
return text + fillchar * (width - len_text)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rjust(text, width, fillchar=' '):
"""Right-justify text for a total of `width` graphemes The `width` is based on graphemes:: 'Â' ' Â' """
|
len_text = grapheme_len(text)
return fillchar * (width - len_text) + text
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def KroneckerDelta(i, j, simplify=True):
"""Kronecker delta symbol Return :class:`One` (`i` equals `j`)), :class:`Zero` (`i` and `j` are non-symbolic an unequal), or a :class:`ScalarValue` wrapping SymPy's :class:`~sympy.functions.special.tensor_functions.KroneckerDelta`. One Zero KroneckerDelta(i, j) By default, the Kronecker delta is returned in a simplified form, e.g:: KroneckerDelta(i, j) This may be suppressed by setting `simplify` to False:: KroneckerDelta(i/2 + 1/2, j/2 + 1/2) Raises: TypeError: if `i` or `j` is not an integer or sympy expression. There is no automatic sympification of `i` and `j`. """
|
from qnet.algebra.core.scalar_algebra import ScalarValue, One
if not isinstance(i, (int, sympy.Basic)):
raise TypeError(
"i is not an integer or sympy expression: %s" % type(i))
if not isinstance(j, (int, sympy.Basic)):
raise TypeError(
"j is not an integer or sympy expression: %s" % type(j))
if i == j:
return One
else:
delta = sympy.KroneckerDelta(i, j)
if simplify:
delta = _simplify_delta(delta)
return ScalarValue.create(delta)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, *operands, **kwargs):
"""Instantiate the product while applying simplification rules"""
|
converted_operands = []
for op in operands:
if not isinstance(op, Scalar):
op = ScalarValue.create(op)
converted_operands.append(op)
return super().create(*converted_operands, **kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conjugate(self):
"""Complex conjugate of of the product"""
|
return self.__class__.create(
*[arg.conjugate() for arg in reversed(self.args)])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, term, *ranges):
"""Instantiate the indexed sum while applying simplification rules"""
|
if not isinstance(term, Scalar):
term = ScalarValue.create(term)
return super().create(term, *ranges)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conjugate(self):
"""Complex conjugate of of the indexed sum"""
|
return self.__class__.create(self.term.conjugate(), *self.ranges)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_summands(cls, ops, kwargs):
"""Collect summands that occur multiple times into a single summand Also filters out zero-summands. Example: ((3 * A^(0), 2 * B^(0)), {}) ZeroOperator A^(0) """
|
from qnet.algebra.core.abstract_quantum_algebra import (
ScalarTimesQuantumExpression)
coeff_map = OrderedDict()
for op in ops:
if isinstance(op, ScalarTimesQuantumExpression):
coeff, term = op.coeff, op.term
else:
coeff, term = 1, op
if term in coeff_map:
coeff_map[term] += coeff
else:
coeff_map[term] = coeff
fops = []
for (term, coeff) in coeff_map.items():
op = coeff * term
if not op.is_zero:
fops.append(op)
if len(fops) == 0:
return cls._zero
elif len(fops) == 1:
return fops[0]
else:
return tuple(fops), kwargs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_binary_replacement(first, second, cls):
"""Helper function for match_replace_binary"""
|
expr = ProtoExpr([first, second], {})
if LOG:
logger = logging.getLogger('QNET.create')
for key, rule in cls._binary_rules.items():
pat, replacement = rule
match_dict = match_pattern(pat, expr)
if match_dict:
try:
replaced = replacement(**match_dict)
if LOG:
logger.debug(
"%sRule %s.%s: (%s, %s) -> %s", (" " * (LEVEL)),
cls.__name__, key, expr.args, expr.kwargs, replaced)
return replaced
except CannotSimplify:
if LOG_NO_MATCH:
logger.debug(
"%sRule %s.%s: no match: CannotSimplify",
(" " * (LEVEL)), cls.__name__, key)
continue
else:
if LOG_NO_MATCH:
logger.debug(
"%sRule %s.%s: no match: %s", (" " * (LEVEL)),
cls.__name__, key, match_dict.reason)
return None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_replace_binary(cls, ops: list) -> list: """Reduce list of `ops`"""
|
n = len(ops)
if n <= 1:
return ops
ops_left = ops[:n // 2]
ops_right = ops[n // 2:]
return _match_replace_binary_combine(
cls,
_match_replace_binary(cls, ops_left),
_match_replace_binary(cls, ops_right))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_replace_binary_combine(cls, a: list, b: list) -> list: """combine two fully reduced lists a, b"""
|
if len(a) == 0 or len(b) == 0:
return a + b
r = _get_binary_replacement(a[-1], b[0], cls)
if r is None:
return a + b
if r == cls._neutral_element:
return _match_replace_binary_combine(cls, a[:-1], b[1:])
if isinstance(r, cls):
r = list(r.args)
else:
r = [r, ]
return _match_replace_binary_combine(
cls,
_match_replace_binary_combine(cls, a[:-1], r),
b[1:])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empty_trivial(cls, ops, kwargs):
"""A ProductSpace of zero Hilbert spaces should yield the TrivialSpace"""
|
from qnet.algebra.core.hilbert_space_algebra import TrivialSpace
if len(ops) == 0:
return TrivialSpace
else:
return ops, kwargs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disjunct_hs_zero(cls, ops, kwargs):
"""Return ZeroOperator if all the operators in `ops` have a disjunct Hilbert space, or an unchanged `ops`, `kwargs` otherwise """
|
from qnet.algebra.core.hilbert_space_algebra import TrivialSpace
from qnet.algebra.core.operator_algebra import ZeroOperator
hilbert_spaces = []
for op in ops:
try:
hs = op.space
except AttributeError: # scalars
hs = TrivialSpace
for hs_prev in hilbert_spaces:
if not hs.isdisjoint(hs_prev):
return ops, kwargs
hilbert_spaces.append(hs)
return ZeroOperator
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commutator_order(cls, ops, kwargs):
"""Apply anti-commutative property of the commutator to apply a standard ordering of the commutator arguments """
|
from qnet.algebra.core.operator_algebra import Commutator
assert len(ops) == 2
if cls.order_key(ops[1]) < cls.order_key(ops[0]):
return -1 * Commutator.create(ops[1], ops[0])
else:
return ops, kwargs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accept_bras(cls, ops, kwargs):
"""Accept operands that are all bras, and turn that into to bra of the operation applied to all corresponding kets"""
|
from qnet.algebra.core.state_algebra import Bra
kets = []
for bra in ops:
if isinstance(bra, Bra):
kets.append(bra.ket)
else:
return ops, kwargs
return Bra.create(cls.create(*kets, **kwargs))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ranges_key(r, delta_indices):
"""Sorting key for ranges. When used with ``reverse=True``, this can be used to sort index ranges into the order we would prefer to eliminate them by evaluating KroneckerDeltas: First, eliminate primed indices, then indices names higher in the alphabet. """
|
idx = r.index_symbol
if idx in delta_indices:
return (r.index_symbol.primed, r.index_symbol.name)
else:
# ranges that are not in delta_indices should remain in the original
# order
return (0, ' ')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _factors_for_expand_delta(expr):
"""Yield factors from expr, mixing sympy and QNET Auxiliary routine for :func:`_expand_delta`. """
|
from qnet.algebra.core.scalar_algebra import ScalarValue
from qnet.algebra.core.abstract_quantum_algebra import (
ScalarTimesQuantumExpression)
if isinstance(expr, ScalarTimesQuantumExpression):
yield from _factors_for_expand_delta(expr.coeff)
yield expr.term
elif isinstance(expr, ScalarValue):
yield from _factors_for_expand_delta(expr.val)
elif isinstance(expr, sympy.Basic) and expr.is_Mul:
yield from expr.args
else:
yield expr
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_sympy_quantum_factor(expr):
"""Split a product into sympy and qnet factors This is a helper routine for applying some sympy transformation on an arbitrary product-like expression in QNET. The idea is this:: expr -> sympy_factor, quantum_factor sympy_factor -> sympy_function(sympy_factor) expr -> sympy_factor * quantum_factor """
|
from qnet.algebra.core.abstract_quantum_algebra import (
QuantumExpression, ScalarTimesQuantumExpression)
from qnet.algebra.core.scalar_algebra import ScalarValue, ScalarTimes, One
if isinstance(expr, ScalarTimesQuantumExpression):
sympy_factor, quantum_factor = _split_sympy_quantum_factor(expr.coeff)
quantum_factor *= expr.term
elif isinstance(expr, ScalarValue):
sympy_factor = expr.val
quantum_factor = expr._one
elif isinstance(expr, ScalarTimes):
sympy_factor = sympy.S(1)
quantum_factor = expr._one
for op in expr.operands:
op_sympy, op_quantum = _split_sympy_quantum_factor(op)
sympy_factor *= op_sympy
quantum_factor *= op_quantum
elif isinstance(expr, sympy.Basic):
sympy_factor = expr
quantum_factor = One
else:
sympy_factor = sympy.S(1)
quantum_factor = expr
assert isinstance(sympy_factor, sympy.Basic)
assert isinstance(quantum_factor, QuantumExpression)
return sympy_factor, quantum_factor
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_delta(expr, idx):
"""Extract a "simple" Kronecker delta containing `idx` from `expr`. Assuming `expr` can be written as the product of a Kronecker Delta and a `new_expr`, return a tuple of the sympy.KroneckerDelta instance and `new_expr`. Otherwise, return a tuple of None and the original `expr` (possibly converted to a :class:`.QuantumExpression`). On input, `expr` can be a :class:`QuantumExpression` or a :class:`sympy.Basic` object. On output, `new_expr` is guaranteed to be a :class:`QuantumExpression`. """
|
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression
from qnet.algebra.core.scalar_algebra import ScalarValue
sympy_factor, quantum_factor = _split_sympy_quantum_factor(expr)
delta, new_expr = _sympy_extract_delta(sympy_factor, idx)
if delta is None:
new_expr = expr
else:
new_expr = new_expr * quantum_factor
if isinstance(new_expr, ScalarValue._val_types):
new_expr = ScalarValue.create(new_expr)
assert isinstance(new_expr, QuantumExpression)
return delta, new_expr
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deltasummation(term, ranges, i_range):
"""Partially execute a summation for `term` with a Kronecker Delta for one of the summation indices. This implements the solution to the core sub-problem in :func:`indexed_sum_over_kronecker` Args: term (QuantumExpression):
term of the sum ranges (list):
list of all summation index ranges (class:`IndexRangeBase` instances) i_range (int):
list-index of element in `ranges` which should be eliminated Returns: ``(result, flag)`` where `result` is a list of ``(new_term, new_ranges)`` tuples and `flag` is an integer. There are three possible cases, indicated by the returned `flag`. Consider the following setup:: 1. If executing the sum produces a single non-zero term, result will be ``[(new_term, new_ranges)]`` where `new_ranges` contains the input `ranges` without the eliminated range specified by `i_range`. This should be the most common case for calls to:func:`_deltasummation`:: 2. If executing the sum for the index symbol specified via `index_range` does not reduce the sum, the result will be the list ``[(term, ranges)]`` with unchanged `term` and `ranges`:: This case also covers if there is no Kroncker delta in the term:: 3. If `term` does not contain a Kronecker delta as a factor, but in a sum that can be expanded, the result will be a list of expansion. In this case, `:func:`_deltasummation` should be called again for every tuple in the list, with the same `i_range`:: """
|
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression
idx = ranges[i_range].index_symbol
summands = _expand_delta(term, idx)
if len(summands) > 1:
return [(summand, ranges) for summand in summands], 3
else:
delta, expr = _extract_delta(summands[0], idx)
if not delta:
return [(term, ranges)], 2
solns = sympy.solve(delta.args[0] - delta.args[1], idx)
assert len(solns) > 0 # I can't think of an example that might cause this
# if len(solns) == 0:
# return [(term._zero, [])], 4
if len(solns) != 1:
return [(term, ranges)], 2
value = solns[0]
new_term = expr.substitute({idx: value})
if _RESOLVE_KRONECKER_WITH_PIECEWISE:
new_term *= ranges[i_range].piecewise_one(value)
assert isinstance(new_term, QuantumExpression)
return [(new_term, ranges[:i_range] + ranges[i_range+1:])], 1
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permutation_to_block_permutations(permutation):
"""If possible, decompose a permutation into a sequence of permutations each acting on individual ranges of the full range of indices. E.g. ``(1,2,0,3,5,4) --> (1,2,0) [+] (0,2,1)`` :type permutation: tuple :rtype: list of tuples :raise: ValueError """
|
if len(permutation) == 0 or not check_permutation(permutation):
raise BadPermutationError()
cycles = permutation_to_disjoint_cycles(permutation)
if len(cycles) == 1:
return (permutation,)
current_block_start = cycles[0][0]
current_block_end = max(cycles[0])
current_block_cycles = [cycles[0]]
res_permutations = []
for c in cycles[1:]:
if c[0] > current_block_end:
res_permutations.append(permutation_from_disjoint_cycles(current_block_cycles, current_block_start))
assert sum(map(len, current_block_cycles)) == current_block_end - current_block_start + 1
current_block_start = c[0]
current_block_end = max(c)
current_block_cycles = [c]
else:
current_block_cycles.append(c)
if max(c) > current_block_end:
current_block_end = max(c)
res_permutations.append(permutation_from_disjoint_cycles(current_block_cycles, current_block_start))
assert sum(map(len, current_block_cycles)) == current_block_end - current_block_start + 1
assert sum(map(len, res_permutations)) == len(permutation)
return res_permutations
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_perm_and_perms_within_blocks(permutation, block_structure):
"""Decompose a permutation into a block permutation and into permutations acting within each block. :param permutation: The overall permutation to be factored. :type permutation: tuple :param block_structure: The channel dimensions of the blocks :type block_structure: tuple :return: ``(block_permutation, permutations_within_blocks)`` Where ``block_permutations`` is an image tuple for a permutation of the block indices and ``permutations_within_blocks`` is a list of image tuples for the permutations of the channels within each block :rtype: tuple """
|
nblocks = len(block_structure)
offsets = [sum(block_structure[:k]) for k in range(nblocks)]
images = [permutation[offset: offset + length] for (offset, length) in zip(offsets, block_structure)]
images_mins = list(map(min, images))
key_block_perm_inv = lambda block_index: images_mins[block_index]
block_perm_inv = tuple(sorted(range(nblocks), key = key_block_perm_inv))
# print(images_mins)
# print(permutation, block_structure, "-->", block_perm, invert_permutation(block_perm))
block_perm = invert_permutation(block_perm_inv)
assert images_mins[block_perm_inv[0]] == min(images_mins)
assert images_mins[block_perm_inv[-1]] == max(images_mins)
# block_perm = tuple(invert_permutation(block_perm_inv))
perms_within_blocks = []
for (offset, length, image) in zip(offsets, block_structure, images):
block_key = lambda elt_index: image[elt_index]
within_inv = sorted(range(length), key = block_key)
within = invert_permutation(tuple(within_inv))
assert permutation[within_inv[0] + offset] == min(image)
assert permutation[within_inv[-1] + offset] == max(image)
perms_within_blocks.append(within)
return block_perm, perms_within_blocks
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_kets(*ops, same_space=False, disjunct_space=False):
"""Check that all operands are Kets from the same Hilbert space."""
|
if not all([(isinstance(o, State) and o.isket) for o in ops]):
raise TypeError("All operands must be Kets")
if same_space:
if not len({o.space for o in ops if o is not ZeroKet}) == 1:
raise UnequalSpaces(str(ops))
if disjunct_space:
spc = TrivialSpace
for o in ops:
if o.space & spc > TrivialSpace:
raise OverlappingSpaces(str(ops))
spc *= o.space
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def args(self):
"""Tuple containing `label_or_index` as its only element."""
|
if self.space.has_basis or isinstance(self.label, SymbolicLabelBase):
return (self.label, )
else:
return (self.index, )
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_fock_representation(self, index_symbol='n', max_terms=None):
"""Return the coherent state written out as an indexed sum over Fock basis states"""
|
phase_factor = sympy.exp(
sympy.Rational(-1, 2) * self.ampl * self.ampl.conjugate())
if not isinstance(index_symbol, IdxSym):
index_symbol = IdxSym(index_symbol)
n = index_symbol
if max_terms is None:
index_range = IndexOverFockSpace(n, hs=self._hs)
else:
index_range = IndexOverRange(n, 0, max_terms-1)
term = (
(self.ampl**n / sympy.sqrt(sympy.factorial(n))) *
BasisKet(FockIndex(n), hs=self._hs))
return phase_factor * KetIndexedSum(term, index_range)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_script(self, inputid):
""" Build CodeMirror HTML script tag which contains CodeMirror init. Arguments: inputid (string):
Input id. Returns: string: HTML for field CodeMirror instance. """
|
varname = "{}_codemirror".format(inputid)
html = self.get_codemirror_field_js()
opts = self.codemirror_config()
return html.format(varname=varname, inputid=inputid,
settings=json.dumps(opts, sort_keys=True))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _algebraic_rules_scalar():
"""Set the default algebraic rules for scalars"""
|
a = wc("a", head=SCALAR_VAL_TYPES)
b = wc("b", head=SCALAR_VAL_TYPES)
x = wc("x", head=SCALAR_TYPES)
y = wc("y", head=SCALAR_TYPES)
z = wc("z", head=SCALAR_TYPES)
indranges__ = wc("indranges__", head=IndexRangeBase)
ScalarTimes._binary_rules.update(check_rules_dict([
('R001', (
pattern_head(a, b),
lambda a, b: a * b)),
('R002', (
pattern_head(x, x),
lambda x: x**2)),
('R003', (
pattern_head(Zero, x),
lambda x: Zero)),
('R004', (
pattern_head(x, Zero),
lambda x: Zero)),
('R005', (
pattern_head(
pattern(ScalarPower, x, y),
pattern(ScalarPower, x, z)),
lambda x, y, z: x**(y+z))),
('R006', (
pattern_head(x, pattern(ScalarPower, x, -1)),
lambda x: One)),
]))
ScalarPower._rules.update(check_rules_dict([
('R001', (
pattern_head(a, b),
lambda a, b: a**b)),
('R002', (
pattern_head(x, 0),
lambda x: One)),
('R003', (
pattern_head(x, 1),
lambda x: x)),
('R004', (
pattern_head(pattern(ScalarPower, x, y), z),
lambda x, y, z: x**(y*z))),
]))
def pull_constfactor_from_sum(x, y, indranges):
bound_symbols = set([r.index_symbol for r in indranges])
if len(x.free_symbols.intersection(bound_symbols)) == 0:
return x * ScalarIndexedSum.create(y, *indranges)
else:
raise CannotSimplify()
ScalarIndexedSum._rules.update(check_rules_dict([
('R001', ( # sum over zero -> zero
pattern_head(Zero, indranges__),
lambda indranges: Zero)),
('R002', ( # pull constant prefactor out of sum
pattern_head(pattern(ScalarTimes, x, y), indranges__),
lambda x, y, indranges:
pull_constfactor_from_sum(x, y, indranges))),
]))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tensor_decompose_series(lhs, rhs):
"""Simplification method for lhs << rhs Decompose a series product of two reducible circuits with compatible block structures into a concatenation of individual series products between subblocks. This method raises CannotSimplify when rhs is a CPermutation in order not to conflict with other _rules. """
|
if isinstance(rhs, CPermutation):
raise CannotSimplify()
lhs_structure = lhs.block_structure
rhs_structure = rhs.block_structure
res_struct = _get_common_block_structure(lhs_structure, rhs_structure)
if len(res_struct) > 1:
blocks, oblocks = (
lhs.get_blocks(res_struct),
rhs.get_blocks(res_struct))
parallel_series = [SeriesProduct.create(lb, rb)
for (lb, rb) in zip(blocks, oblocks)]
return Concatenation.create(*parallel_series)
raise CannotSimplify()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _factor_permutation_for_blocks(cperm, rhs):
"""Simplification method for cperm << rhs. Decompose a series product of a channel permutation and a reducible circuit with appropriate block structure by decomposing the permutation into a permutation within each block of rhs and a block permutation and a residual part. This allows for achieving something close to a normal form for circuit expression. """
|
rbs = rhs.block_structure
if rhs == cid(rhs.cdim):
return cperm
if len(rbs) > 1:
residual_lhs, transformed_rhs, carried_through_lhs \
= cperm._factorize_for_rhs(rhs)
if residual_lhs == cperm:
raise CannotSimplify()
return SeriesProduct.create(residual_lhs, transformed_rhs,
carried_through_lhs)
raise CannotSimplify()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pull_out_perm_lhs(lhs, rest, out_port, in_port):
"""Pull out a permutation from the Feedback of a SeriesProduct with itself. Args: lhs (CPermutation):
The permutation circuit rest (tuple):
The other SeriesProduct operands out_port (int):
The feedback output port index in_port (int):
The feedback input port index Returns: Circuit: The simplified circuit """
|
out_inv, lhs_red = lhs._factor_lhs(out_port)
return lhs_red << Feedback.create(SeriesProduct.create(*rest),
out_port=out_inv, in_port=in_port)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pull_out_unaffected_blocks_lhs(lhs, rest, out_port, in_port):
"""In a self-Feedback of a series product, where the left-most operand is reducible, pull all non-trivial blocks outside of the feedback. Args: lhs (Circuit):
The reducible circuit rest (tuple):
The other SeriesProduct operands out_port (int):
The feedback output port index in_port (int):
The feedback input port index Returns: Circuit: The simplified circuit """
|
_, block_index = lhs.index_in_block(out_port)
bs = lhs.block_structure
nbefore, nblock, nafter = (sum(bs[:block_index]),
bs[block_index],
sum(bs[block_index + 1:]))
before, block, after = lhs.get_blocks((nbefore, nblock, nafter))
if before != cid(nbefore) or after != cid(nafter):
outer_lhs = before + cid(nblock - 1) + after
inner_lhs = cid(nbefore) + block + cid(nafter)
return outer_lhs << Feedback.create(
SeriesProduct.create(inner_lhs, *rest),
out_port=out_port, in_port=in_port)
elif block == cid(nblock):
outer_lhs = before + cid(nblock - 1) + after
return outer_lhs << Feedback.create(
SeriesProduct.create(*rest),
out_port=out_port, in_port=in_port)
raise CannotSimplify()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _series_feedback(series, out_port, in_port):
"""Invert a series self-feedback twice to get rid of unnecessary permutations."""
|
series_s = series.series_inverse().series_inverse()
if series_s == series:
raise CannotSimplify()
return series_s.feedback(out_port=out_port, in_port=in_port)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.