code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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): B = BC.operands[0] C = OperatorTimes.create(*B...
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.
2.836923
2.897215
0.97919
# 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('re...
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( st...
3.645183
3.52773
1.033294
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)
def configure_printing(**kwargs)
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 ...
5.247552
6.391603
0.821007
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 as...
def ascii(expr, cache=None, **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 ...
4.332711
4.68327
0.925146
try: if cache is None and len(settings) == 0: return unicode.printer.doprint(expr) else: printer = unicode._printer_cls(cache, settings) return printer.doprint(expr) except AttributeError: # init_printing was not called. Setting up defaults ...
def unicode(expr, cache=None, **settings)
Return a unicode 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...
4.511656
4.710011
0.957887
if indented: printer = IndentedSReprPrinter(cache=cache) else: printer = QnetSReprPrinter(cache=cache) return printer.doprint(expr)
def srepr(expr, indented=False, cache=None)
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...
4.381668
5.783762
0.757581
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(categories=category).only('modification_date') return lastitems[0].modification_date
def lastmod(self, category)
Return the last modification of the entry.
7.531737
6.446829
1.168286
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date') return lastitems[0].modification_date
def lastmod(self, author)
Return the last modification of the entry.
7.32383
5.91316
1.238564
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(tags=tag).only('modification_date') return lastitems[0].modification_date
def lastmod(self, tag)
Return the last modification of the entry.
8.173064
6.659652
1.227251
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 Tri...
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 ma...
3.35955
3.274353
1.026019
if full_space: if not full_space >= slh.space: raise AlgebraError("full_space="+str(full_space)+" needs to " "at least include slh.space = "+str(slh.space)) else: full_space = slh.space if full_space == TrivialSpace: raise AlgebraError(...
def SLH_to_qutip(slh, full_space=None, time_symbol=None, convert_as='pyfunc')
Generate and return QuTiP representation matrices for the Hamiltonian and the collapse operators. Any inhomogeneities in the Lindblad operators (resulting from coherent drives) will be moved into the Hamiltonian, cf. :func:`~qnet.algebra.circuit_algebra.move_drive_to_H`. Args: slh (SLH): The SL...
2.6529
2.320005
1.143489
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_qu...
def _convert_local_operator_to_qutip(expr, full_space, mapping)
Convert a LocalOperator instance to qutip
2.502208
2.491852
1.004156
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: ...
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
3.18953
3.185786
1.001175
len_text = grapheme_len(text) return text + fillchar * (width - len_text)
def ljust(text, width, fillchar=' ')
Left-justify text to a total of `width` The `width` is based on graphemes:: >>> s = 'Â' >>> s.ljust(2) 'Â' >>> ljust(s, 2) 'Â '
6.472518
7.763659
0.833694
len_text = grapheme_len(text) return fillchar * (width - len_text) + text
def rjust(text, width, fillchar=' ')
Right-justify text for a total of `width` graphemes The `width` is based on graphemes:: >>> s = 'Â' >>> s.rjust(2) 'Â' >>> rjust(s, 2) ' Â'
7.054959
8.323477
0.847598
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 sy...
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`. >>> i, j = IdxSym('i'), IdxSym('j') >>> KroneckerDelta(i, i) ...
2.805808
2.512375
1.116795
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.Basi...
def sqrt(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...
2.731466
2.92439
0.934029
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...
def create(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 :cla...
5.947596
5.034506
1.181366
if hasattr(self.val, 'real'): return self.val.real else: # SymPy return self.val.as_real_imag()[0]
def real(self)
Real part
4.178649
3.783453
1.104454
if hasattr(self.val, 'imag'): return self.val.imag else: # SymPy return self.val.as_real_imag()[1]
def imag(self)
Imaginary part
3.924348
3.742983
1.048455
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)
def create(cls, *operands, **kwargs)
Instantiate the product while applying simplification rules
3.177437
3.241733
0.980166
return self.__class__.create( *[arg.conjugate() for arg in reversed(self.args)])
def conjugate(self)
Complex conjugate of of the product
7.760278
7.39297
1.049683
if not isinstance(term, Scalar): term = ScalarValue.create(term) return super().create(term, *ranges)
def create(cls, term, *ranges)
Instantiate the indexed sum while applying simplification rules
5.491016
5.088489
1.079106
return self.__class__.create(self.term.conjugate(), *self.ranges)
def conjugate(self)
Complex conjugate of of the indexed sum
11.758207
11.30917
1.039706
return self.__class__.create(self.term.real, *self.ranges)
def real(self)
Real part
23.028727
22.721384
1.013527
return self.__class__.create(self.term.imag, *self.ranges)
def imag(self)
Imaginary part
21.444473
19.999754
1.072237
expanded = [(o,) if not isinstance(o, cls) else o.operands for o in ops] return sum(expanded, ()), kwargs
def assoc(cls, ops, 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)
8.041827
15.504649
0.518672
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, c...
def assoc_indexed(cls, ops, kwargs)
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
4.067536
4.393457
0.925817
return sorted(set(ops), key=cls.order_key), kwargs
def idem(cls, ops, 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)
13.66003
12.231361
1.116804
return sorted(ops, key=cls.order_key), kwargs
def orderby(cls, ops, 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)
11.417656
14.779959
0.772509
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: ...
def filter_neutral(cls, ops, kwargs)
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...
5.197961
5.221112
0.995566
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 c...
def collect_summands(cls, ops, 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^...
2.747694
2.981238
0.921662
# This routine is required because there is no # "ScalarTimesQuantumExpression" for scalars: we have to extract # coefficiencts from ScalarTimes instead from qnet.algebra.core.scalar_algebra import ( Zero, One, Scalar, ScalarTimes, ScalarValue) a_0 = Zero coeff_map = OrderedDict() ...
def collect_scalar_summands(cls, ops, kwargs)
Collect :class:`ValueScalar` and :class:`ScalarExpression` summands Example: >>> srepr(collect_scalar_summands(Scalar, (1, 2, 3), {})) 'ScalarValue(6)' >>> collect_scalar_summands(Scalar, (1, 1, -1), {}) One >>> collect_scalar_summands(Scalar, (1, -1), {}) Zero ...
3.673625
3.88739
0.945011
expr = ProtoExpr(ops, kwargs) if LOG: logger = logging.getLogger('QNET.create') for key, rule in cls._rules.items(): pat, replacement = rule match_dict = match_pattern(pat, expr) if match_dict: try: replaced = replacement(**match_dict) ...
def match_replace(cls, ops, kwargs)
Match and replace a full operand specification to a function that provides a replacement for the whole expression or raises a :exc:`.CannotSimplify` exception. E.g. First define an operation:: >>> class Invert(Operation): ... _rules = OrderedDict() ... simplifications =...
3.807444
3.93592
0.967358
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(**matc...
def _get_binary_replacement(first, second, cls)
Helper function for match_replace_binary
3.89535
3.838149
1.014904
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, l...
def match_replace_binary(cls, ops, 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)} ...
4.240644
3.412813
1.242565
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))
def _match_replace_binary(cls, ops: list) -> list
Reduce list of `ops`
2.408514
2.123305
1.134323
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...
def _match_replace_binary_combine(cls, a: list, b: list) -> list
combine two fully reduced lists a, b
2.78314
2.582209
1.077814
if not len({o.cdim for o in ops}) == 1: raise ValueError("Not all operands have the same cdim:" + str(ops)) return ops, kwargs
def check_cdims(cls, ops, kwargs)
Check that all operands (`ops`) have equal channel dimension.
4.578539
3.475917
1.317218
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 ...
def filter_cid(cls, ops, kwargs)
Remove occurrences of the :func:`.circuit_identity` ``cid(n)`` for any ``n``. Cf. :func:`filter_neutral`
5.990984
5.141874
1.165136
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
def convert_to_spaces(cls, ops, 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.
5.198272
5.362255
0.969419
from qnet.algebra.core.hilbert_space_algebra import TrivialSpace if len(ops) == 0: return TrivialSpace else: return ops, kwargs
def empty_trivial(cls, ops, kwargs)
A ProductSpace of zero Hilbert spaces should yield the TrivialSpace
5.626578
4.707066
1.195347
from qnet.algebra.core.hilbert_space_algebra import ( HilbertSpace, LocalSpace) def args_to_local_space(cls, args, kwargs): if isinstance(args[arg_index], LocalSpace): new_args = args else: if isinstance(args[arg_index], (int, str)): ...
def implied_local_space(*, arg_index=None, keys=None)
Return a simplification that converts the positional argument `arg_index` from (str, int) to a subclass of :class:`.LocalSpace`, as well as any keyword argument with one of the given keys. The exact type of the resulting Hilbert space is determined by the `default_hs_cls` argument of :func:`init_algebr...
1.972343
1.889121
1.044053
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
def delegate_to_method(mtd)
Create a simplification rule that delegates the instantiation to the method `mtd` of the operand (if defined)
4.466189
3.636548
1.22814
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
def scalars_to_op(cls, ops, kwargs)
r'''Convert any scalar $\alpha$ in `ops` into an operator $\alpha \identity$
5.38867
2.86824
1.878737
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
def convert_to_scalars(cls, ops, kwargs)
Convert any entry in `ops` that is not a :class:`.Scalar` instance into a :class:`.ScalarValue` instance
3.035817
2.677869
1.133669
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 hilbe...
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
3.497663
3.079105
1.135935
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
def commutator_order(cls, ops, kwargs)
Apply anti-commutative property of the commutator to apply a standard ordering of the commutator arguments
4.101937
4.255817
0.963843
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))
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
4.358139
4.072817
1.070055
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
def basis_ket_zero_outside_hs(cls, 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
6.433617
5.532409
1.162896
r'''Execute an indexed sum over a term that does not depend on the summation indices .. math:: \sum_{j=1}^{N} a = N a >>> a = symbols('a') >>> i, j = (IdxSym(s) for s in ('i', 'j')) >>> unicode(Sum(i, 1, 2)(a)) '2 a' >>> unicode(Sum(j, 1, 2)(Sum(i, 1, 2)(a * i))) '∑_{i=1}...
def indexed_sum_over_const(cls, ops, kwargs)
r'''Execute an indexed sum over a term that does not depend on the summation indices .. math:: \sum_{j=1}^{N} a = N a >>> a = symbols('a') >>> i, j = (IdxSym(s) for s in ('i', 'j')) >>> unicode(Sum(i, 1, 2)(a)) '2 a' >>> unicode(Sum(j, 1, 2)(Sum(i, 1, 2)(a * i))) '∑_{i=1}^{2}...
4.187544
1.866574
2.243439
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, ' ')
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.
7.811273
6.722778
1.161912
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression term, *ranges = ops assert isinstance(term, QuantumExpression) deltas = set(Pattern(head=sympy.KroneckerDelta).findall(term)) if len(deltas) == 0: return ops, kwargs # nothing to do else: # the term contains ...
def indexed_sum_over_kronecker(cls, ops, kwargs)
Execute sums over KroneckerDelta prefactors
4.247852
4.139015
1.026296
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...
def _factors_for_expand_delta(expr)
Yield factors from expr, mixing sympy and QNET Auxiliary routine for :func:`_expand_delta`.
3.198238
3.093981
1.033697
found_first_delta = False summands = None for factor in _factors_for_expand_delta(expr): need_to_expand = False if not found_first_delta and isinstance(factor, sympy.Basic): if factor.is_Add and _has_simple_delta(factor, idx): need_to_expand = True if...
def _expand_delta(expr, idx)
Expand the first :class:`sympy.Add` containing a simple :class:`sympy.KroneckerDelta`. Auxiliary routine for :func:`_deltasummation`. Adapted from SymPy. The input `expr` may be a :class:`.QuantumExpression` or a `:class:`sympy.Basic` instance. Returns a list of summands. The elements of the list ...
2.67799
2.583727
1.036484
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_fac...
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 * quant...
2.277854
2.238382
1.017634
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 ...
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 :c...
3.681506
3.17254
1.160429
assert len(ops) == 1 op = ops[0] derivs = kwargs['derivs'] vals = kwargs['vals'] # both `derivs` and `vals` are guaranteed to be tuples, via the conversion # that's happening in `QuantumDerivative.create` for (sym, n) in derivs: if sym.free_symbols.issubset(op.free_symbols): ...
def derivative_via_diff(cls, ops, kwargs)
Implementation of the :meth:`QuantumDerivative.create` interface via the use of :meth:`QuantumExpression._diff`. Thus, by having :meth:`.QuantumExpression.diff` delegate to :meth:`.QuantumDerivative.create`, instead of :meth:`.QuantumExpression._diff` directly, we get automatic caching of derivativ...
5.519215
5.31305
1.038804
if language_code not in LANGUAGE_CODES: message = '{} is not an available language code'.format(language_code) raise InvalidLanguageCodeException(message) return MATH_WORDS[language_code]
def word_groups_for_language(language_code)
Return the math word groups for a language code. The language_code should be an ISO 639-2 language code. https://www.loc.gov/standards/iso639-2/php/code_list.php
4.784022
3.882245
1.232282
word_groups = word_groups_for_language(language_code) words = [] for group in word_groups: words.extend(word_groups[group].keys()) return words
def words_for_language(language_code)
Return the math words for a language code. The language_code should be an ISO 639-2 language code. https://www.loc.gov/standards/iso639-2/php/code_list.php
3.118829
2.894807
1.077388
return tuple([permutation.index(p) for p in range(len(permutation))])
def invert_permutation(permutation)
Compute the image tuple of the inverse permutation. :param permutation: A valid (cf. :py:func:check_permutation) permutation. :return: The inverse permutation tuple :rtype: tuple
3.703683
8.187044
0.452383
if not check_permutation(permutation): raise BadPermutationError('Malformed permutation %r' % permutation) p_index = 0 current_cycle = [0] # keep track of all remaining/unvisited indices permutation_nums = list(range(1,len(permutation))) cycles = [] while True: # find...
def permutation_to_disjoint_cycles(permutation)
Any permutation sigma can be represented as a product of cycles. A cycle (c_1, .. c_n) is a closed sequence of indices such that sigma(c_1) == c_2, sigma(c_2) == sigma^2(c_1)== c_3, ..., sigma(c_(n-1)) == c_n, sigma(c_n) == c_1 Any single length-n cycle admits n equivalent representations in corresp...
4.20132
4.125226
1.018446
perm_length = sum(map(len, cycles)) res_perm = list(range(perm_length)) for c in cycles: p1 = c[0] - offset for p2 in c[1:]: p2 = p2 - offset res_perm[p1] = p2 p1 = p2 res_perm[p1] = c[0] - offset #close cycle assert sorted(res_perm) == li...
def permutation_from_disjoint_cycles(cycles, offset=0)
Reconstruct a permutation image tuple from a list of disjoint cycles :param cycles: sequence of disjoint cycles :type cycles: list or tuple :param offset: Offset to subtract from the resulting permutation image points :type offset: int :return: permutation image tuple :rtype: tuple
2.744438
2.771659
0.990179
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_c...
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)`` :param permutation: A valid permutation image tuple ``s = (s_0,...s_n)`` with ``n > 0`` :type permutation: tuple ...
1.931958
2.050406
0.942232
offset = 0 new_perm = [] for p in permutations: new_perm[offset: offset +len(p)] = [p_i + offset for p_i in p] offset += len(p) return tuple(new_perm)
def permutation_from_block_permutations(permutations)
Reverse operation to :py:func:`permutation_to_block_permutations` Compute the concatenation of permutations ``(1,2,0) [+] (0,2,1) --> (1,2,0,3,5,4)`` :param permutations: A list of permutation tuples ``[t = (t_0,...,t_n1), u = (u_0,...,u_n2),..., z = (z_0,...,z_nm)]`` ...
3.283341
3.447315
0.952434
if len(sequence) != len(permutation): raise ValueError((sequence, permutation)) if not check_permutation(permutation): raise BadPermutationError(str(permutation)) if type(sequence) in (list, tuple, str): constructor = type(sequence) else: constructor = list retu...
def permute(sequence, permutation)
Apply a permutation sigma({j}) to an arbitrary sequence. :param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same. :param permutation: permutation image tuple :type permutation: tuple :return: The permuted sequence ``[l_sigma(1), ...
3.682681
3.288682
1.119804
fblockp = [] bp_inv = invert_permutation(block_permutation) for k, block_length in enumerate(block_structure): p_k = block_permutation[k] offset = sum([block_structure[bp_inv[j]] for j in range(p_k)]) fblockp += range(offset, offset + block_length) assert sorted(fblockp) ==...
def full_block_perm(block_permutation, block_structure)
Extend a permutation of blocks to a permutation for the internal signals of all blocks. E.g., say we have two blocks of sizes ('block structure') ``(2, 3)``, then a block permutation that switches the blocks would be given by the image tuple ``(1,0)``. However, to get a permutation of all 2+3 = 5 channels t...
3.540646
4.127721
0.857773
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_i...
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_permu...
2.885905
2.955157
0.976566
# TODO: django-fluent-pages needs a public API to get the current page. current_page = getattr(self.request, '_current_fluent_page', None) return blog_reverse(viewname, args=args, kwargs=kwargs, current_page=current_page)
def reverse(self, viewname, args=None, kwargs=None)
Reverse a blog page, taking different configuration options into account. For example, the blog can be mounted using *django-fluent-pages* on multiple nodes.
4.853726
4.250078
1.142032
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 i...
def _check_kets(*ops, same_space=False, disjunct_space=False)
Check that all operands are Kets from the same Hilbert space.
3.942536
3.700242
1.06548
if self.space.has_basis or isinstance(self.label, SymbolicLabelBase): return (self.label, ) else: return (self.index, )
def args(self)
Tuple containing `label_or_index` as its only element.
11.283078
6.300939
1.790698
if isinstance(self.label, SymbolicLabelBase): next_label = self.space.next_basis_label_or_index( self.label, n) return BasisKet(next_label, hs=self.space) else: try: next_index = self.space.next_basis_label_or_index( ...
def next(self, n=1)
Move up by `n` steps in the Hilbert space:: >>> hs = LocalSpace('tls', basis=('g', 'e')) >>> ascii(BasisKet('g', hs=hs).next()) '|e>^(tls)' >>> ascii(BasisKet(0, hs=hs).next()) '|e>^(tls)' We can also go multiple steps: >>> hs = LocalS...
4.001361
3.20058
1.250199
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=sel...
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
3.917279
3.894045
1.005967
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))
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.
4.590331
5.400643
0.84996
if not hasattr(self, "editor_manifest"): self.editor_manifest = self.init_manifest(self.config_name) config = self.editor_manifest.get_config(self.config_name) if config.get('embed_config'): self.embed_config = True context = self.get_context(name, valu...
def render(self, name, value, attrs=None, renderer=None)
Returns this Widget rendered as HTML, as a Unicode string.
3.731083
3.719832
1.003025
if not hasattr(self, "editor_manifest"): self.editor_manifest = self.init_manifest(self.config_name) return forms.Media( css={"all": self.editor_manifest.css()}, js=self.editor_manifest.js() )
def media(self)
Adds necessary files (Js/CSS) to the widget's medias. Returns: django.forms.Media: Media object with all assets from registered config.
5.350863
4.400424
1.215988
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', ...
def _algebraic_rules_scalar()
Set the default algebraic rules for scalars
2.656783
2.668807
0.995495
# for convenience the arguments may also be Circuit objects if isinstance(lhs_bs, Circuit): lhs_bs = lhs_bs.block_structure if isinstance(rhs_bs, Circuit): rhs_bs = rhs_bs.block_structure if sum(lhs_bs) != sum(rhs_bs): raise IncompatibleBlockStructures( 'Blocks...
def _get_common_block_structure(lhs_bs, rhs_bs)
For two block structures ``aa = (a1, a2, ..., an)``, ``bb = (b1, b2, ..., bm)`` generate the maximal common block structure so that every block from aa and bb is contained in exactly one block of the resulting structure. This is useful for determining how to apply the distributive law when feeding two ...
2.720993
2.518426
1.080434
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_stru...
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.
4.422533
3.148813
1.404508
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(...
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 somethin...
8.969759
8.031619
1.116806
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)
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: ...
18.384863
13.163498
1.396655
_, 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)) ...
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...
3.899449
3.464635
1.125501
in_im, rhs_red = rhs._factor_rhs(in_port) return (Feedback.create( SeriesProduct.create(*rest), out_port=out_port, in_port=in_im) << rhs_red)
def _pull_out_perm_rhs(rest, rhs, out_port, in_port)
Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-feedback.
15.392593
14.11511
1.090505
_, block_index = rhs.index_in_block(in_port) rest = tuple(rest) bs = rhs.block_structure (nbefore, nblock, nafter) = (sum(bs[:block_index]), bs[block_index], sum(bs[block_index + 1:])) before, block, after = rhs.get_blocks((nbefo...
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port)
Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a series product self-feedback.
3.771652
3.607807
1.045414
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)
def _series_feedback(series, out_port, in_port)
Invert a series self-feedback twice to get rid of unnecessary permutations.
5.353517
5.136045
1.042342
from qnet.algebra.core.scalar_algebra import Scalar scalar_args = False if hasattr(cls, '_scalar_args'): scalar_args = cls._scalar_args for arg_name in getattr(cls, arg_names): def get_arg(self, name): val = getattr(self, "_%s" % name) if scalar_args: ...
def properties_for_args(cls, arg_names='_arg_names')
For a class with an attribute `arg_names` containing a list of names, add a property for every name in that list. It is assumed that there is an instance attribute ``self._<arg_name>``, which is returned by the `arg_name` property. The decorator also adds a class attribute :attr:`_has_properties_for_a...
2.855203
2.802279
1.018886
try: return get_category_for_slug(slug) except ObjectDoesNotExist as e: raise Http404(str(e))
def get_category(self, slug)
Get the category object
3.717493
3.810009
0.975718
date_kwargs = {} error_msg = _("The slug is not unique") # The /year/month/slug/ URL determines when a slug can be unique. pubdate = cleaned_data['publication_date'] or now() if '{year}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE: date_kwargs['year'] = pub...
def validate_unique_slug(self, cleaned_data)
Test whether the slug is unique within a given time period.
3.154888
2.999087
1.05195
try: if isinstance(expr, SympyBasic): sympy_var_map = { k: v for (k, v) in var_map.items() if isinstance(k, SympyBasic)} return expr.subs(sympy_var_map) else: return expr.substitute(var_map) except AttributeError: i...
def substitute(expr, var_map)
Substitute symbols or (sub-)expressions with the given replacements and re-evalute the result Args: expr: The expression in which to perform the substitution var_map (dict): The substitution dictionary.
2.461606
2.553416
0.964044
try: # `rules` is an OrderedDict key => (pattern, replacement) items = rules.items() except AttributeError: # `rules` is a list of (pattern, replacement) tuples items = enumerate(rules) for key, (pat, replacement) in items: matched = pat.match(expr) if ma...
def _apply_rules_no_recurse(expr, rules)
Non-recursively match expr again all rules
4.042478
4.002607
1.009961
if LOG: logger = logging.getLogger('QNET.create') stack = [] path = [] if isinstance(expr, Expression): stack.append(ProtoExpr.from_expr(expr)) path.append(0) if LOG: logger.debug( "Starting at level 1: placing expr on stack: %s", expr) ...
def _apply_rules(expr, rules)
Recursively re-instantiate the expression, while applying all of the given `rules` to all encountered (sub-) expressions Args: expr: Any Expression or scalar object rules (list, ~collections.OrderedDict): A list of rules dictionary mapping names to rules, where each rule is a tuple...
2.958484
2.968987
0.996462
global LEVEL if LOG: logger = logging.getLogger('QNET.create') logger.debug( "%s%s.create(*args, **kwargs); args = %s, kwargs = %s", (" " * LEVEL), cls.__name__, args, kwargs) LEVEL += 1 key = cls._get_instance_key(arg...
def create(cls, *args, **kwargs)
Instantiate while applying automatic simplifications Instead of directly instantiating `cls`, it is recommended to use :meth:`create`, which applies simplifications to the args and keyword arguments according to the :attr:`simplifications` class attribute, and returns an appropriate obj...
2.785196
2.750722
1.012533
from qnet.algebra.core.algebraic_properties import ( match_replace, match_replace_binary) if match_replace in cls.simplifications: return '_rules' elif match_replace_binary in cls.simplifications: return '_binary_rules' else: raise...
def _rules_attr(cls)
Return the name of the attribute with rules for :meth:`create`
5.140901
4.6505
1.105451
from qnet.utils.check_rules import check_rules_dict if attr is None: attr = cls._rules_attr() if name in getattr(cls, attr): raise ValueError( "Duplicate key '%s': rule already exists" % name) getattr(cls, attr).update(check_rules_dict( ...
def add_rule(cls, name, pattern, replacement, attr=None)
Add an algebraic rule for :meth:`create` to the class Args: name (str): Name of the rule. This is used for debug logging to allow an analysis of which rules where applied when creating an expression. The `name` can be arbitrary, but it must be unique. ...
5.009599
5.775577
0.867376
from qnet.printing import srepr try: if attr is None: attr = cls._rules_attr() rules = getattr(cls, attr) except TypeError: rules = {} for (name, rule) in rules.items(): if len(names) > 0 and name not in names: ...
def show_rules(cls, *names, attr=None)
Print algebraic rules used by :class:`create` Print a summary of the algebraic rules with the given names, or all rules if not names a given. Args: names (str): Names of rules to show attr (None or str): Name of the class attribute from which to get the ...
3.489973
3.75981
0.928231
if attr is None: attr = cls._rules_attr() if len(names) == 0: getattr(cls, attr) # raise AttributeError if wrong attr setattr(cls, attr, OrderedDict()) else: for name in names: del getattr(cls, attr)[name]
def del_rules(cls, *names, attr=None)
Delete algebraic rules used by :meth:`create` Remove the rules with the given `names`, or all rules if no names are given Args: names (str): Names of rules to delete attr (None or str): Name of the class attribute from which to delete the rules. Cf. :met...
3.636321
3.947541
0.921161
try: if attr is None: attr = cls._rules_attr() return getattr(cls, attr).keys() except TypeError: return ()
def rules(cls, attr=None)
Iterable of rule names used by :meth:`create` Args: attr (None or str): Name of the class attribute to which to get the names. If None, one of ``'_rules'``, ``'_binary_rules'`` is automatically chosen
5.286692
6.202303
0.852376
# Subclasses must override this property if and only if they define # keyword-only arguments in their __init__ method if hasattr(self, '_has_kwargs') and self._has_kwargs: raise NotImplementedError( "Class %s does not provide a kwargs property" ...
def kwargs(self)
The dictionary of keyword-only arguments for the instantiation of the Expression
5.255027
4.856947
1.081961
if self in var_map: return var_map[self] return self._substitute(var_map)
def substitute(self, var_map)
Substitute sub-expressions Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}``
3.710555
5.688723
0.652265
if self in var_map: if not safe or (type(var_map[self]) == type(self)): return var_map[self] if isinstance(self.__class__, Singleton): return self new_args = [substitute(arg, var_map) for arg in self.args] new_kwargs = {key: substitute(val...
def _substitute(self, var_map, safe=False)
Implementation of :meth:`substitute`. For internal use, the `safe` keyword argument allows to perform a substitution on the `args` and `kwargs` of the expression only, guaranteeing that the type of the expression does not change, at the cost of possibly not returning a maximally simplif...
2.263948
2.392003
0.946466