code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def codemirror_parameters(field):
manifesto = CodemirrorAssetTagRender()
names = manifesto.register_from_fields(field)
config = manifesto.get_codemirror_parameters(names[0])
return mark_safe(json.dumps(config)) | 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 django... |
def codemirror_instance(config_name, varname, element_id, assets=True):
output = io.StringIO()
manifesto = CodemirrorAssetTagRender()
manifesto.register(config_name)
if assets:
output.write(manifesto.css_html())
output.write(manifesto.js_html())
html = manifesto.codemirror_ht... | 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... |
def resolve_widget(self, 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:
... | 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 giv... |
def register_from_fields(self, *args):
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 | 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. |
def render_asset_html(self, path, tag_template):
url = os.path.join(settings.STATIC_URL, path)
return tag_template.format(url=url) | 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. |
def css_html(self):
output = io.StringIO()
for item in self.css():
output.write(
self.render_asset_html(item, settings.CODEMIRROR_CSS_ASSET_TAG)
)
content = output.getvalue()
output.close()
return content | Render HTML tags for Javascript assets.
Returns:
string: HTML for CSS assets from every registered config. |
def js_html(self):
output = io.StringIO()
for item in self.js():
output.write(
self.render_asset_html(item, settings.CODEMIRROR_JS_ASSET_TAG)
)
content = output.getvalue()
output.close()
return content | Render HTML tags for Javascript assets.
Returns:
string: HTML for Javascript assets from every registered config. |
def codemirror_html(self, config_name, varname, element_id):
parameters = json.dumps(self.get_codemirror_parameters(config_name),
sort_keys=True)
return settings.CODEMIRROR_FIELD_INIT_JS.format(
varname=varname,
inputid=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
... |
def get_language_settings(language_code, site_id=None):
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
for lang_dict in FLUENT_BLOGS_LANGUAGES.get(site_id, ()):
if lang_dict['code'] == language_code:
return lang_dict
return FLUENT_BLOGS_LANGUAGES['default... | Return the language settings for the current site |
def run_apidoc(_):
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'),
]) | Generage API documentation |
def _shorten_render(renderer, max_len):
def short_renderer(expr):
res = renderer(expr)
if len(res) > max_len:
return '...'
else:
return res
return short_renderer | Return a modified that returns the representation of expr, or '...' if
that representation is longer than `max_len` |
def init_algebra(*, default_hs_cls='LocalSpace'):
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, LocalSpac... | 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` |
def register(self, name):
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_co... | 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``.
... |
def register_many(self, *args):
params = []
for name in args:
params.append(self.register(name))
return params | Register many configuration names.
Arguments:
*args: Config names as strings.
Returns:
list: List of registered configs. |
def resolve_mode(self, name):
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) | 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 pa... |
def resolve_theme(self, name):
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) | 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 f... |
def get_configs(self, name=None):
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 | 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 conf... |
def get_config(self, name):
if name not in self.registry:
msg = "Given config name '{}' is not registered."
raise NotRegisteredError(msg.format(name))
return copy.deepcopy(self.registry[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. |
def get_codemirror_parameters(self, name):
config = self.get_config(name)
return {k: config[k] for k in config if k not in self._internal_only} | 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. |
def js(self, name=None):
filepaths = copy.copy(settings.CODEMIRROR_BASE_JS)
configs = self.get_configs(name)
names = sorted(configs)
# Addons first
for name in names:
opts = configs[name]
for item in opts.get('addons', []):
if it... | Returns all needed Javascript filepaths for given config name (if
given) or every registred config instead (if no name is given).
Keyword Arguments:
name (string): Specific config name to use instead of all.
Returns:
list: List of Javascript file paths. |
def js_bundle_names(self, name=None):
configs = self.get_configs(name)
names = []
for k, v in configs.items():
if v.get('js_bundle_name'):
names.append(v['js_bundle_name'])
return sorted(names) | Returns all needed Javascript Bundle names for given config name (if
given) or every registred config instead (if no name is given).
Keyword Arguments:
name (string): Specific config name to use instead of all.
Returns:
list: List of webasset bundle names. |
def css(self, name=None):
filepaths = copy.copy(settings.CODEMIRROR_BASE_CSS)
configs = self.get_configs(name)
names = sorted(configs)
# Process themes
for name in names:
opts = configs[name]
for item in opts.get('themes', []):
r... | Returns all needed CSS filepaths for given config name (if
given) or every registred config instead (if no name is given).
Keyword Arguments:
name (string): Specific config name to use instead of all.
Returns:
list: List of CSS file paths. |
def commutator(A, B=None):
if B:
return A * B - B * A
return SPre(A) - SPost(A) | 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 comm... |
def anti_commutator(A, B=None):
if B:
return A * B + B * A
return SPre(A) + SPost(A) | If ``B != None``, return the anti-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 anti-commutator
:math:`\{A, B\} = A B + B A`.
Args:
A: The first operator to form all anti-commutat... |
def liouvillian(H, Ls=None):
r
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) | 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... |
def vstackm(matrices):
arr = np_vstack(tuple(m.matrix for m in matrices))
# print(tuple(m.matrix.dtype for m in matrices))
# print(arr.dtype)
return Matrix(arr) | Generalizes `numpy.vstack` to :class:`Matrix` objects. |
def block_matrix(A, B, C, D):
r
return vstackm((hstackm((A, B)), hstackm((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)``
Retu... |
def permutation_matrix(permutation):
r
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) | 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)}
... |
def block_structure(self):
n, m = self.shape
if n != m:
raise AttributeError("block_structure only defined for square "
"matrices")
for k in range(1, n):
if ((self.matrix[:k, k:] == 0).all() and
(self.matrix[k:... | For square matrices this gives the block (-diagonal) structure of
the matrix as a tuple of integers that sum up to the full dimension.
:rtype: tuple |
def is_zero(self):
for o in self.matrix.ravel():
try:
if not o.is_zero:
return False
except AttributeError:
if not o == 0:
return False
return True | Are all elements of the matrix zero? |
def conjugate(self):
try:
return Matrix(np_conjugate(self.matrix))
except AttributeError:
raise NoConjugateMatrix(
"Matrix %s contains entries that have no defined "
"conjugate" % str(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... |
def real(self):
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:... | 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.con... |
def imag(self):
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)
... | 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::
... |
def element_wise(self, func, *args, **kwargs):
s = self.shape
emat = [func(o, *args, **kwargs) for o in self.matrix.ravel()]
return Matrix(np_array(emat).reshape(s)) | 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... |
def series_expand(self, param: Symbol, about, order: int):
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)) | 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 e... |
def expand(self):
return self.element_wise(
lambda o: o.expand() if isinstance(o, QuantumExpression) else o) | Expand each matrix element distributively.
Returns:
Matrix: Expanded matrix. |
def space(self):
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) | Combined Hilbert space of all matrix elements. |
def simplify_scalar(self, func=sympy.simplify):
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
... | Simplify all scalar expressions appearing in the Matrix. |
def get_initial(self):
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', ... | Try to find a demo source for given mode if any, if finded use it to
fill the demo textarea. |
def _get_order_by(order, orderby, order_by_fields):
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... | Return the order by syntax for a model.
Checks whether use ascending or descending order, and maps the fieldnames. |
def query_tags(order=None, orderby=None, limit=None):
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.
ent... | Query the tags, with usage count included.
This interface is mainly used by the ``get_tags`` template tag. |
def get_category_for_slug(slug, language_code=None):
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) | Find the category for a given slug |
def get_date_range(year=None, month=None, day=None):
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:
... | Return a start..end range to query for a specific month, day or year. |
def singleton_object(cls):
assert isinstance(cls, Singleton), \
cls.__name__ + " must use Singleton metaclass"
def self_instantiate(self):
return self
cls.__call__ = self_instantiate
if hasattr(cls, '_hash_val'):
cls.__hash__ = lambda self: hash(cls._hash_val)
cls.... | Class decorator that transforms (and replaces) a class definition (which
must have a Singleton metaclass) with the actual singleton object. Ensures
that the resulting object can still be "instantiated" (i.e., called),
returning the same object. Also ensures the object can be pickled, is
hashable, and ha... |
def pattern(head, *args, mode=1, wc_name=None, conditions=None, **kwargs) \
-> Pattern:
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) | 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 |
def pattern_head(*args, conditions=None, wc_name=None, **kwargs) -> Pattern:
# This routine is indented for the _rules and _binary_rules class
# attributes of algebraic objects, which the match_replace and
# match_replace_binary match against a ProtoExpr
if len(args) == 0:
args = None
i... | Constructor for a :class:`Pattern` matching a :class:`ProtoExpr`
The patterns associated with :attr:`_rules` and :attr:`_binary_rules`
of an :class:`Expression` subclass, or those passed to
:meth:`Expression.add_rule`, must be instantiated through this
routine. The function does not allow to set a wild... |
def wc(name_mode="_", head=None, args=None, kwargs=None, *, conditions=None) \
-> Pattern:
rx = re.compile(r"^([A-Za-z]?[A-Za-z0-9]*)(_{0,3})$")
m = rx.match(name_mode)
if not m:
raise ValueError("Invalid name_mode: %s" % name_mode)
wc_name, mode_underscores = m.groups()
if wc_n... | Constructor for a wildcard-:class:`Pattern`
Helper function to create a Pattern object with an emphasis on wildcard
patterns, if we don't care about the arguments of the matched expressions
(otherwise, use :func:`pattern`)
Args:
name_mode (str): Combined `wc_name` and `mode` for :class:`Patter... |
def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict:
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
... | 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 |
def update(self, *others):
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:
... | Update dict with entries from `other`
If `other` has an attribute ``success=False`` and ``reason``, those
attributes are copied as well |
def extended_arg_patterns(self):
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:
... | Iterator over patterns for positional arguments to be matched
This yields the elements of :attr:`args`, extended by their `mode`
value |
def _check_last_arg_pattern(self, current_arg_pattern, last_arg_pattern):
try:
if last_arg_pattern.mode == self.single:
raise ValueError("insufficient number of arguments")
elif last_arg_pattern.mode == self.zero_or_more:
if last_arg_pattern.wc_na... | Given a "current" arg pattern (that was used to match the last
actual argument of an expression), and another ("last") argument
pattern, raise a ValueError, unless the "last" argument pattern is a
"zero or more" wildcard. In that case, return a dict that maps the
wildcard name to an empt... |
def findall(self, expr):
result = []
try:
for arg in expr.args:
result.extend(self.findall(arg))
for arg in expr.kwargs.values():
result.extend(self.findall(arg))
except AttributeError:
pass
if self.match(expr):... | list of all matching (sub-)expressions in `expr`
See also:
:meth:`finditer` yields the matches (:class:`MatchDict` instances)
for the matched expressions. |
def finditer(self, expr):
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... | 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`. |
def wc_names(self):
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 i... | Set of all wildcard names occurring in the pattern |
def instantiate(self, cls=None):
if cls is None:
cls = self.cls
if cls is None:
raise TypeError("cls must a class")
return cls.create(*self.args, **self.kwargs) | Return an instantiated Expression as
``cls.create(*self.args, **self.kwargs)``
Args:
cls (class): The class of the instantiated expression. If not
given, ``self.cls`` will be used. |
def from_expr(cls, expr):
return cls(expr.args, expr.kwargs, cls=expr.__class__) | Instantiate proto-expression from the given Expression |
def get_entry_model():
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 ca... | 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. |
def get_category_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... | Return the category model to use.
This function reads the :ref:`FLUENT_BLOGS_CATEGORY_MODEL` setting to find the model. |
def blog_reverse(viewname, args=None, kwargs=None, current_app='fluent_blogs', **page_kwargs):
return mixed_reverse(viewname, args=args, kwargs=kwargs, current_app=current_app, **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*. |
def expand_commutators_leibniz(expr, expand_expr=True):
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, ... | 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. |
def configure_printing(**kwargs):
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) | Context manager for temporarily changing the printing system.
This takes the same parameters as :func:`init_printing`
Example:
>>> A = OperatorSymbol('A', hs=1); B = OperatorSymbol('B', hs=1)
>>> with configure_printing(show_hs_label=False):
... print(ascii(A + B))
A + B
... |
def ascii(expr, cache=None, **settings):
try:
if cache is None and len(settings) == 0:
return ascii.printer.doprint(expr)
else:
printer = ascii._printer_cls(cache, settings)
return printer.doprint(expr)
except AttributeError:
# init_printing was n... | Return an ASCII representation of the given object / expression
Args:
expr: Expression to print
cache (dict or None): dictionary to use for caching
show_hs_label (bool or str): Whether to a label for the Hilbert space
of `expr`. By default (``show_hs_label=True``), the label is ... |
def srepr(expr, indented=False, cache=None):
if indented:
printer = IndentedSReprPrinter(cache=cache)
else:
printer = QnetSReprPrinter(cache=cache)
return printer.doprint(expr) | Render the given expression into a string that can be evaluated in an
appropriate context to re-instantiate an identical expression. If
`indented` is False (default), the resulting string is a single line.
Otherwise, the result is a multiline string, and each positional and
keyword argument of each `Exp... |
def lastmod(self, category):
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(categories=category).only('modification_date')
return lastitems[0].modification_date | Return the last modification of the entry. |
def lastmod(self, author):
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date')
return lastitems[0].modification_date | Return the last modification of the entry. |
def lastmod(self, tag):
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(tags=tag).only('modification_date')
return lastitems[0].modification_date | Return the last modification of the entry. |
def ljust(text, width, fillchar=' '):
len_text = grapheme_len(text)
return text + fillchar * (width - len_text) | Left-justify text to a total of `width`
The `width` is based on graphemes::
>>> s = 'Â'
>>> s.ljust(2)
'Â'
>>> ljust(s, 2)
'Â ' |
def rjust(text, width, fillchar=' '):
len_text = grapheme_len(text)
return fillchar * (width - len_text) + text | Right-justify text for a total of `width` graphemes
The `width` is based on graphemes::
>>> s = 'Â'
>>> s.rjust(2)
'Â'
>>> rjust(s, 2)
' Â' |
def KroneckerDelta(i, j, simplify=True):
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 TypeErro... | 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`.
>>> i, j = IdxSym('i'), IdxSym('j')
>>> KroneckerDelta(i, i)
... |
def sqrt(scalar):
if isinstance(scalar, ScalarValue):
scalar = scalar.val
if scalar == 1:
return One
elif scalar == 0:
return Zero
elif isinstance(scalar, (float, complex, complex128, float64)):
return ScalarValue.create(numpy.sqrt(scalar))
elif isinstance(scalar... | Square root of a :class:`Scalar` or scalar value
This always returns a :class:`Scalar`, and uses a symbolic square root if
possible (i.e., for non-floats)::
>>> sqrt(2)
sqrt(2)
>>> sqrt(2.0)
1.414213...
For a :class:`ScalarExpression` argument, it returns a
:class:`Sc... |
def create(cls, val):
if val in cls._invalid:
raise ValueError("Invalid value %r" % val)
if val == 0:
return Zero
elif val == 1:
return One
elif isinstance(val, Scalar):
return val
else:
# We instantiate ScalarV... | Instatiate the :class:`ScalarValue` while recognizing :class:`Zero`
and :class:`One`.
:class:`Scalar` instances as `val` (including
:class:`ScalarExpression` instances) are left unchanged. This makes
:meth:`ScalarValue.create` a safe method for converting unknown objects
to :cla... |
def real(self):
if hasattr(self.val, 'real'):
return self.val.real
else:
# SymPy
return self.val.as_real_imag()[0] | Real part |
def imag(self):
if hasattr(self.val, 'imag'):
return self.val.imag
else:
# SymPy
return self.val.as_real_imag()[1] | Imaginary part |
def create(cls, *operands, **kwargs):
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) | Instantiate the product while applying simplification rules |
def conjugate(self):
return self.__class__.create(
*[arg.conjugate() for arg in reversed(self.args)]) | Complex conjugate of of the product |
def create(cls, term, *ranges):
if not isinstance(term, Scalar):
term = ScalarValue.create(term)
return super().create(term, *ranges) | Instantiate the indexed sum while applying simplification rules |
def conjugate(self):
return self.__class__.create(self.term.conjugate(), *self.ranges) | Complex conjugate of of the indexed sum |
def real(self):
return self.__class__.create(self.term.real, *self.ranges) | Real part |
def imag(self):
return self.__class__.create(self.term.imag, *self.ranges) | Imaginary part |
def assoc(cls, ops, kwargs):
expanded = [(o,) if not isinstance(o, cls) else o.operands for o in ops]
return sum(expanded, ()), kwargs | Associatively expand out nested arguments of the flat class.
E.g.::
>>> class Plus(Operation):
... simplifications = [assoc, ]
>>> Plus.create(1,Plus(2,3))
Plus(1, 2, 3) |
def assoc_indexed(cls, ops, kwargs):
r
from qnet.algebra.core.abstract_quantum_algebra import (
ScalarTimesQuantumExpression)
term, *ranges = ops
if isinstance(term, cls):
coeff = 1
elif isinstance(term, ScalarTimesQuantumExpression):
coeff = term.coeff
term = term.t... | r"""Flatten nested indexed structures while pulling out possible prefactors
For example, for an :class:`.IndexedSum`:
.. math::
\sum_j \left( a \sum_i \dots \right) = a \sum_{j, i} \dots |
def idem(cls, ops, kwargs):
return sorted(set(ops), key=cls.order_key), kwargs | Remove duplicate arguments and order them via the cls's order_key key
object/function.
E.g.::
>>> class Set(Operation):
... order_key = lambda val: val
... simplifications = [idem, ]
>>> Set.create(1,2,3,1,3)
Set(1, 2, 3) |
def orderby(cls, ops, kwargs):
return sorted(ops, key=cls.order_key), kwargs | Re-order arguments via the class's ``order_key`` key object/function.
Use this for commutative operations:
E.g.::
>>> class Times(Operation):
... order_key = lambda val: val
... simplifications = [orderby, ]
>>> Times.create(2,1)
Times(1, 2) |
def filter_neutral(cls, ops, kwargs):
c_n = cls._neutral_element
if len(ops) == 0:
return c_n
fops = [op for op in ops if c_n != op] # op != c_n does NOT work
if len(fops) > 1:
return fops, kwargs
elif len(fops) == 1:
# the remaining operand is the single non-trivial on... | Remove occurrences of a neutral element from the argument/operand list,
if that list has at least two elements. To use this, one must also specify
a neutral element, which can be anything that allows for an equality check
with each argument. E.g.::
>>> class X(Operation):
... _neutral... |
def collect_summands(cls, ops, kwargs):
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:
... | Collect summands that occur multiple times into a single summand
Also filters out zero-summands.
Example:
>>> A, B, C = (OperatorSymbol(s, hs=0) for s in ('A', 'B', 'C'))
>>> collect_summands(
... OperatorPlus, (A, B, C, ZeroOperator, 2 * A, B, -C) , {})
((3 * A^(0), 2 * B^... |
def _get_binary_replacement(first, second, cls):
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:
t... | Helper function for match_replace_binary |
def match_replace_binary(cls, ops, kwargs):
assert assoc in cls.simplifications, (
cls.__name__ + " must be associative to use match_replace_binary")
assert hasattr(cls, '_neutral_element'), (
cls.__name__ + " must define a neutral element to use "
"match_replace_bina... | Similar to func:`match_replace`, but for arbitrary length operations,
such that each two pairs of subsequent operands are matched pairwise.
>>> A = wc("A")
>>> class FilterDupes(Operation):
... _binary_rules = {
... 'filter_dupes': (pattern_head(A,A), lambda A: A)}
... |
def _match_replace_binary(cls, ops: list) -> list:
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)) | Reduce list of `ops` |
def _match_replace_binary_combine(cls, a: list, b: list) -> list:
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:])
i... | combine two fully reduced lists a, b |
def check_cdims(cls, ops, kwargs):
if not len({o.cdim for o in ops}) == 1:
raise ValueError("Not all operands have the same cdim:" + str(ops))
return ops, kwargs | Check that all operands (`ops`) have equal channel dimension. |
def filter_cid(cls, ops, kwargs):
from qnet.algebra.core.circuit_algebra import CircuitZero, circuit_identity
if len(ops) == 0:
return CircuitZero
fops = [op for op in ops if op != circuit_identity(op.cdim)]
if len(fops) > 1:
return fops, kwargs
elif len(fops) == 1:
# th... | Remove occurrences of the :func:`.circuit_identity` ``cid(n)`` for any
``n``. Cf. :func:`filter_neutral` |
def convert_to_spaces(cls, ops, kwargs):
from qnet.algebra.core.hilbert_space_algebra import (
HilbertSpace, LocalSpace)
cops = [o if isinstance(o, HilbertSpace) else LocalSpace(o) for o in ops]
return cops, kwargs | For all operands that are merely of type str or int, substitute
LocalSpace objects with corresponding labels:
For a string, just itself, for an int, a string version of that int. |
def empty_trivial(cls, ops, kwargs):
from qnet.algebra.core.hilbert_space_algebra import TrivialSpace
if len(ops) == 0:
return TrivialSpace
else:
return ops, kwargs | A ProductSpace of zero Hilbert spaces should yield the TrivialSpace |
def delegate_to_method(mtd):
def _delegate_to_method(cls, ops, kwargs):
assert len(ops) == 1
op, = ops
if hasattr(op, mtd):
return getattr(op, mtd)()
else:
return ops, kwargs
return _delegate_to_method | Create a simplification rule that delegates the instantiation to the
method `mtd` of the operand (if defined) |
def scalars_to_op(cls, ops, kwargs):
r'''Convert any scalar $\alpha$ in `ops` into an operator $\alpha
\identity$'''
from qnet.algebra.core.scalar_algebra import is_scalar
op_ops = []
for op in ops:
if is_scalar(op):
op_ops.append(op * cls._one)
else:
op_ops.a... | r'''Convert any scalar $\alpha$ in `ops` into an operator $\alpha
\identity$ |
def convert_to_scalars(cls, ops, kwargs):
from qnet.algebra.core.scalar_algebra import Scalar, ScalarValue
scalar_ops = []
for op in ops:
if not isinstance(op, Scalar):
scalar_ops.append(ScalarValue(op))
else:
scalar_ops.append(op)
return scalar_ops, kwargs | Convert any entry in `ops` that is not a :class:`.Scalar` instance into
a :class:`.ScalarValue` instance |
def disjunct_hs_zero(cls, ops, kwargs):
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 = T... | Return ZeroOperator if all the operators in `ops` have a disjunct
Hilbert space, or an unchanged `ops`, `kwargs` otherwise |
def commutator_order(cls, ops, kwargs):
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 | Apply anti-commutative property of the commutator to apply a standard
ordering of the commutator arguments |
def accept_bras(cls, ops, kwargs):
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)) | Accept operands that are all bras, and turn that into to bra of the
operation applied to all corresponding kets |
def basis_ket_zero_outside_hs(cls, ops, kwargs):
from qnet.algebra.core.state_algebra import ZeroKet
ind, = ops
hs = kwargs['hs']
if isinstance(ind, int):
if ind < 0 or (hs._dimension is not None and ind >= hs._dimension):
return ZeroKet
return ops, kwargs | For ``BasisKet.create(ind, hs)`` with an integer label `ind`, return a
:class:`ZeroKet` if `ind` is outside of the range of the underlying Hilbert
space |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.