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 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.
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_html(config_name, varname, element_id) output.write(html) content = output.getvalue() output.close() return mark_safe(content)
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.
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: widget = field.widget return widget
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.
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, settings=parameters, )
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.
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, LocalSpace): QuantumExpression._default_hs_cls = default_hs_cls else: raise TypeError("default_hs_cls must be a subclass of 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`
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_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
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.
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 path.
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 file path.
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 configuration name to return. Raises: NotRegisteredError: If given config name does not exist in registry. Returns: dict: Configurations.
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 item not in filepaths: filepaths.append(item) # Process modes for name in names: opts = configs[name] for item in opts['modes']: resolved = self.resolve_mode(item) if resolved not in filepaths: filepaths.append(resolved) return filepaths
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', []): resolved = self.resolve_theme(item) if resolved not in filepaths: filepaths.append(resolved) # Then process extra CSS files for name in names: opts = configs[name] for item in opts.get('extra_css', []): if item not in filepaths: filepaths.append(item) return filepaths
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 commutator of. B: The second operator to form the commutator of, or None. Returns: SuperOperator: The linear superoperator :math:`[A,\cdot]`
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-commutators of. B: The second operator to form the anti-commutator of, or None. Returns: SuperOperator: The linear superoperator :math:`[A,\cdot]`
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 (Operator): The associated Hamilton operator Ls (sequence or Matrix): A sequence of Lindblad operators. Returns: SuperOperator: The Liouvillian super-operator.
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)`` Returns: Matrix: The combined block matrix ``[[A, B], [C, D]]``.
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)} 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!)
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:, :k] == 0).all()): return (k,) + self[k:, k:].block_structure return n,
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 this is mathematically different from a complex conjugate. Raises: NoConjugateMatrix: if any entries have no `conjugate` method
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: 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)
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 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) 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)
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 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 be passed to `func` kwargs: Additional keyword arguments to be passed to `func` Returns: Matrix: Matrix with results of `func`, applied element-wise.
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 entries are the expansion coefficients.
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 return self.element_wise(element_simplify)
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', encoding='utf-8') as fp: initial['foo'] = fp.read() return initial
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(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
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. 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
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: # 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)
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.__eq__ = lambda self, other: other == cls._hash_val else: cls.__hash__ = lambda self: hash(cls) cls.__eq__ = lambda self, other: other is self cls.__repr__ = lambda self: cls.__name__ cls.__reduce__ = lambda self: cls.__name__ obj = cls() obj.__name__ = cls.__name__ obj.__qualname__ = cls.__qualname__ return obj
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 has the correct string representation (the name of the singleton) If the class defines a `_hash_val` class attribute, the hash of the singleton will be the hash of that value, and the singleton will compare equal to that value. Otherwise, the singleton will have a unique hash and compare equal only to itself.
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 if len(kwargs) == 0: kwargs = None if wc_name is not None: raise ValueError("pattern_head cannot be used to set a wildcard " "(`wc_name` must not be given") pat = Pattern(head=ProtoExpr, args=args, kwargs=kwargs, wc_name=None, conditions=conditions) return pat
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 wildcard name (`wc_name` must not be given / be None)
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_name == '': wc_name = None mode = len(mode_underscores) or Pattern.single return Pattern(head, args, kwargs, mode=mode, wc_name=wc_name, conditions=conditions)
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:`Pattern` constructor argument. See below for syntax head (type, or None): See :class:`Pattern` args (list or None): See :class:`Pattern` kwargs (dict or None): See :class:`Pattern` conditions (list or None): See :class:`Pattern` The `name_mode` argument uses trailing underscored to indicate the `mode`: * ``A`` -> ``Pattern(wc_name="A", mode=Pattern.single, ...)`` * ``A_`` -> ``Pattern(wc_name="A", mode=Pattern.single, ...)`` * ``B__`` -> ``Pattern(wc_name="B", mode=Pattern.one_or_more, ...)`` * ``B___`` -> ``Pattern(wc_name="C", mode=Pattern.zero_or_more, ...)``
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 else: res = MatchDict() res.success = False res.reason = "Expressions '%s' and '%s' are not the same" % ( repr(expr_or_pattern), repr(expr)) return res
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: pass
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: yield arg
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_name is not None: if last_arg_pattern != current_arg_pattern: # we have to record an empty match return {last_arg_pattern.wc_name: []} elif last_arg_pattern.mode == self.one_or_more: if last_arg_pattern != current_arg_pattern: raise ValueError("insufficient number of arguments") except AttributeError: raise ValueError("insufficient number of arguments") return {}
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 empty list
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): result.append(expr) return result
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 m = self.match(expr) if m: yield m
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 is not None: for val in self.kwargs.values(): if isinstance(val, Pattern): res.update(val.wc_names) return res
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 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
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}".format( appsettings.FLUENT_BLOGS_CATEGORY_MODEL, str(e) ))
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, 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
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 >>> print(ascii(A + B)) A^(1) + B^(1)
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 not called. Setting up defaults ascii._printer_cls = QnetAsciiPrinter ascii.printer = ascii._printer_cls() return ascii(expr, cache, **settings)
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 shown as a superscript. It can be shown as a subscript with ``show_hs_label='subscript'`` or suppressed entirely (``show_hs_label=False``) sig_as_ketbra (bool): Whether to render instances of :class:`.LocalSigma` as a ket-bra (default), or as an operator symbol Examples: >>> A = OperatorSymbol('A', hs=1); B = OperatorSymbol('B', hs=1) >>> ascii(A + B) 'A^(1) + B^(1)' >>> ascii(A + B, cache={A: 'A', B: 'B'}) 'A + B' >>> ascii(A + B, show_hs_label='subscript') 'A_(1) + B_(1)' >>> ascii(A + B, show_hs_label=False) 'A + B' >>> ascii(LocalSigma(0, 1, hs=1)) '|0><1|^(1)' >>> ascii(LocalSigma(0, 1, hs=1), sig_as_ketbra=False) 'sigma_0,1^(1)' Note that the accepted parameters and their default values may be changed through :func:`init_printing` or :func:`configure_printing`
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 `Expression` is on a separate line, recursively indented to produce a tree-like output. The `cache` may be used to generate more readable expressions. Example: >>> hs = LocalSpace('1') >>> A = OperatorSymbol('A', hs=hs); B = OperatorSymbol('B', hs=hs) >>> expr = A + B >>> srepr(expr) "OperatorPlus(OperatorSymbol('A', hs=LocalSpace('1')), OperatorSymbol('B', hs=LocalSpace('1')))" >>> eval(srepr(expr)) == expr True >>> srepr(expr, cache={hs:'hs'}) "OperatorPlus(OperatorSymbol('A', hs=hs), OperatorSymbol('B', hs=hs))" >>> eval(srepr(expr, cache={hs:'hs'})) == expr True >>> print(srepr(expr, indented=True)) OperatorPlus( OperatorSymbol( 'A', hs=LocalSpace( '1')), OperatorSymbol( 'B', hs=LocalSpace( '1'))) >>> eval(srepr(expr, indented=True)) == expr True See also: :func:`~qnet.printing.tree.print_tree`, respectively :func:`qnet.printing.tree.tree`, produces an output similar to the indented :func:`srepr`, for interactive use. Their result cannot be evaluated and the exact output depends on :func:`init_printing`. :func:`~qnet.printing.dot.dotprint` provides a way to graphically explore the tree structure of an expression.
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 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)
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) One >>> KroneckerDelta(1, 2) Zero >>> KroneckerDelta(i, j) KroneckerDelta(i, j) By default, the Kronecker delta is returned in a simplified form, e.g:: >>> KroneckerDelta((i+1)/2, (j+1)/2) KroneckerDelta(i, j) This may be suppressed by setting `simplify` to False:: >>> KroneckerDelta((i+1)/2, (j+1)/2, simplify=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`.
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, (int, sympy.Basic, int64)): return ScalarValue.create(sympy.sqrt(scalar)) elif isinstance(scalar, Scalar): return scalar**(sympy.sympify(1) / 2) else: raise TypeError("Unknown type of scalar: %r" % type(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:`ScalarPower` instance:: >>> braket = KetSymbol('Psi', hs=0).dag() * KetSymbol('Phi', hs=0) >>> nrm = sqrt(braket * braket.dag()) >>> print(srepr(nrm, indented=True)) ScalarPower( ScalarTimes( BraKet( KetSymbol( 'Phi', hs=LocalSpace( '0')), KetSymbol( 'Psi', hs=LocalSpace( '0'))), BraKet( KetSymbol( 'Psi', hs=LocalSpace( '0')), KetSymbol( 'Phi', hs=LocalSpace( '0')))), ScalarValue( Rational(1, 2)))
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 ScalarValue directly to avoid the overhead of # super().create(). Thus, there is no caching for scalars (which is # probably a good thing) return cls(val)
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 :class:`Scalar`.
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.term if not isinstance(term, cls): return ops, kwargs else: return ops, kwargs term = term.make_disjunct_indices(*ranges) combined_ranges = tuple(ranges) + term.ranges if coeff == 1: return cls.create(term.term, *combined_ranges) else: bound_symbols = set([r.index_symbol for r in combined_ranges]) if len(coeff.free_symbols.intersection(bound_symbols)) == 0: return coeff * cls.create(term.term, *combined_ranges) else: return cls.create(coeff * term.term, *combined_ranges)
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 one return fops[0] else: # the original list of operands consists only of neutral elements return ops[0]
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_element = 1 ... simplifications = [filter_neutral, ] >>> X.create(2,1,3,1) X(2, 3)
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: 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
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^(0)), {}) >>> collect_summands(OperatorPlus, (A, -A), {}) ZeroOperator >>> collect_summands(OperatorPlus, (B, A, -B), {}) A^(0)
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: 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
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_binary") fops = _match_replace_binary(cls, list(ops)) if len(fops) == 1: return fops[0] elif len(fops) == 0: return cls._neutral_element else: return fops, kwargs
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)} ... simplifications = [match_replace_binary, assoc] ... _neutral_element = 0 >>> FilterDupes.create(1,2,3,4) # No duplicates FilterDupes(1, 2, 3, 4) >>> FilterDupes.create(1,2,2,3,4) # Some duplicates FilterDupes(1, 2, 3, 4) Note that this only works for *subsequent* duplicate entries: >>> FilterDupes.create(1,2,3,2,4) # No *subsequent* duplicates FilterDupes(1, 2, 3, 2, 4) Any operation that uses binary reduction must be associative and define a neutral element. The binary rules must be compatible with associativity, i.e. there is no specific order in which the rules are applied to pairs of operands.
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:]) 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:])
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: # the remaining operand is the single non-trivial one return fops[0] else: # the original list of operands consists only of neutral elements return ops[0]
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.append(op) return op_ops, kwargf 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.append(op) return op_ops, kwargs
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 = TrivialSpace for hs_prev in hilbert_spaces: if not hs.isdisjoint(hs_prev): return ops, kwargs hilbert_spaces.append(hs) return ZeroOperator
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