code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if out_port is None: out_port = circuit.cdim - 1 if in_port is None: in_port = circuit.cdim - 1 return Feedback.create(circuit, out_port=out_port, in_port=in_port)
def FB(circuit, *, out_port=None, in_port=None)
Wrapper for :class:`.Feedback`, defaulting to last channel Args: circuit (Circuit): The circuit that undergoes self-feedback out_port (int): The output port index, default = None --> last port in_port (int): The input port index, default = None --> last port Returns: Circuit: T...
2.531888
2.699841
0.937792
n = cdim perm = tuple(list(range(k)) + [n - 1] + list(range(k, n - 1))) return CPermutation.create(perm)
def extract_channel(k, cdim)
Create a :class:`CPermutation` that extracts channel `k` Return a permutation circuit that maps the k-th (zero-based) input to the last output, while preserving the relative order of all other channels. Args: k (int): Extracted channel index cdim (int): The circuit dimension (number of...
6.048306
5.641794
1.072054
n = cdim free_values = list(range(n)) for v in mapping.values(): if v >= n: raise ValueError('the mapping cannot take on values larger than ' 'cdim - 1') free_values.remove(v) for k in mapping: if k >= n: raise ValueError...
def map_channels(mapping, cdim)
Create a :class:`CPermuation` based on a dict of channel mappings For a given mapping in form of a dictionary, generate the channel permutating circuit that achieves the specified mapping while leaving the relative order of all non-specified channels intact. Args: mapping (dict): Input-output ...
3.561644
3.283298
1.084777
circuit_n = circuit.cdim combined_circuit = circuit + circuit_identity(n) permutation = (list(range(k)) + list(range(circuit_n, circuit_n + n)) + list(range(k, circuit_n))) return (CPermutation.create(invert_permutation(permutation)) << combined_circuit << CPermutatio...
def pad_with_identity(circuit, k, n)
Pad a circuit by adding a `n`-channel identity circuit at index `k` That is, a circuit of channel dimension $N$ is extended to one of channel dimension $N+n$, where the channels $k$, $k+1$, ...$k+n-1$, just pass through the system unaffected. E.g. let ``A``, ``B`` be two single channel systems:: ...
5.818155
6.556914
0.887331
r'''Move coherent drives from the Lindblad operators to the Hamiltonian. For the given SLH model, move inhomogeneities in the Lindblad operators (resulting from the presence of a coherent drive, see :class:`CoherentDriveCC`) to the Hamiltonian. This exploits the invariance of the Lindblad master e...
def move_drive_to_H(slh, which=None, expand_simplify=True)
r'''Move coherent drives from the Lindblad operators to the Hamiltonian. For the given SLH model, move inhomogeneities in the Lindblad operators (resulting from the presence of a coherent drive, see :class:`CoherentDriveCC`) to the Hamiltonian. This exploits the invariance of the Lindblad master equat...
5.576647
1.543877
3.612105
if k is None: k = symbols('k', positive=True) Ld = slh.L.dag() LdL = (Ld * slh.L)[0, 0] K = (-LdL / 2 + I * slh.H).expand().simplify_scalar() N = slh.S.dag() B, A, Y = K.series_expand(k, 0, 2) G, F = Ld.series_expand(k, 0, 1) return Y, A, B, F, G, N
def prepare_adiabatic_limit(slh, k=None)
Prepare the adiabatic elimination on an SLH object Args: slh: The SLH object to take the limit for k: The scaling parameter $k \rightarrow \infty$. The default is a positive symbol 'k' Returns: tuple: The objects ``Y, A, B, F, G, N`` necessary to compute the limitin...
5.49087
4.469148
1.228617
Y, A, B, F, G, N = YABFGN Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar() Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar() Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar() dN = identity_matrix(N.shape[0]) + F.H * Ytilde * F Nlim = (P0 * N ...
def eval_adiabatic_limit(YABFGN, Ytilde, P0)
Compute the limiting SLH model for the adiabatic approximation Args: YABFGN: The tuple (Y, A, B, F, G, N) as returned by prepare_adiabatic_limit. Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0. P0: The projector onto the null-space of Y. Returns: SLH: L...
5.862384
5.131249
1.142487
ops = prepare_adiabatic_limit(slh, k) Y = ops[0] if isinstance(Y.space, LocalSpace): try: b = Y.space.basis_labels if len(b) > fock_trunc: b = b[:fock_trunc] except BasisNotSetError: b = range(fock_trunc) projectors = set(Local...
def try_adiabatic_elimination(slh, k=None, fock_trunc=6, sub_P0=True)
Attempt to automatically do adiabatic elimination on an SLH object This will project the `Y` operator onto a truncated basis with dimension specified by `fock_trunc`. `sub_P0` controls whether an attempt is made to replace the kernel projector P0 by an :class:`.IdentityOperator`.
6.408277
5.975224
1.072475
if channel_index < 0 or channel_index >= self.cdim: raise ValueError() struct = self.block_structure if len(struct) == 1: return channel_index, 0 i = 1 while sum(struct[:i]) <= channel_index and i < self.cdim: i += 1 block_in...
def index_in_block(self, channel_index: int) -> int
Return the index a channel has within the subblock it belongs to I.e., only for reducible circuits, this gives a result different from the argument itself. Args: channel_index (int): The index of the external channel Raises: ValueError: for an invalid `channel_...
3.412858
3.241186
1.052966
if block_structure is None: block_structure = self.block_structure try: return self._get_blocks(block_structure) except IncompatibleBlockStructures as e: raise e
def get_blocks(self, block_structure=None)
For a reducible circuit, get a sequence of subblocks that when concatenated again yield the original circuit. The block structure given has to be compatible with the circuits actual block structure, i.e. it can only be more coarse-grained. Args: block_structure (tuple): The...
3.368159
3.79861
0.886682
if out_port is None: out_port = self.cdim - 1 if in_port is None: in_port = self.cdim - 1 return self._feedback(out_port=out_port, in_port=in_port)
def feedback(self, *, out_port=None, in_port=None)
Return a circuit with self-feedback from the output port (zero-based) ``out_port`` to the input port ``in_port``. Args: out_port (int or None): The output port from which the feedback connection leaves (zero-based, default ``None`` corresponds to the *last* p...
2.297525
2.35644
0.974998
# noinspection PyPackageRequirements from IPython.display import Image, display fname = self.render() display(Image(filename=fname))
def show(self)
Show the circuit expression in an IPython notebook.
8.265428
5.88754
1.403885
import qnet.visualization.circuit_pyx as circuit_visualization from tempfile import gettempdir from time import time, sleep if not fname: tmp_dir = gettempdir() fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time))) if circuit_visualiza...
def render(self, fname='')
Render the circuit expression and store the result in a file Args: fname (str): Path to an image file to store the result in. Returns: str: The path to the image file
5.307623
5.207257
1.019274
args_spaces = (self.S.space, self.L.space, self.H.space) return ProductSpace.create(*args_spaces)
def space(self)
Total Hilbert space
8.784507
6.963489
1.261509
return set.union( self.S.free_symbols, self.L.free_symbols, self.H.free_symbols)
def free_symbols(self)
Set of all symbols occcuring in S, L, or H
5.993594
3.236455
1.851901
new_S = self.S * other.S new_L = self.S * other.L + self.L def ImAdjoint(m): return (m.H - m) * (I / 2) delta = ImAdjoint(self.L.adjoint() * self.S * other.L) if isinstance(delta, Matrix): new_H = self.H + other.H + delta[0, 0] else: ...
def series_with_slh(self, other)
Series product with another :class:`SLH` object Args: other (SLH): An upstream SLH circuit. Returns: SLH: The combined system.
4.393399
4.388672
1.001077
selfS = self.S otherS = other.S new_S = block_matrix( selfS, zerosm((selfS.shape[0], otherS.shape[1]), dtype=int), zerosm((otherS.shape[0], selfS.shape[1]), dtype=int), otherS) new_L = vstackm((self.L, other.L)) new_H = self.H + other.H ...
def concatenate_slh(self, other)
Concatenation with another :class:`SLH` object
3.201828
3.00316
1.066153
return SLH(self.S.expand(), self.L.expand(), self.H.expand())
def expand(self)
Expand out all operator expressions within S, L and H Return a new :class:`SLH` object with these expanded expressions.
8.305547
3.472347
2.391911
return SLH( self.S.simplify_scalar(func=func), self.L.simplify_scalar(func=func), self.H.simplify_scalar(func=func))
def simplify_scalar(self, func=sympy.simplify)
Simplify all scalar expressions within S, L and H Return a new :class:`SLH` object with the simplified expressions. See also: :meth:`.QuantumExpression.simplify_scalar`
3.608235
2.382567
1.514432
L, H = self.L, self.H if rho is None: rho = OperatorSymbol('rho', hs=self.space) return (-I * (H * rho - rho * H) + sum(Lk * rho * adjoint(Lk) - (adjoint(Lk) * Lk * rho + rho * adjoint(Lk) * Lk) / 2 for Lk in L.matrix.r...
def symbolic_master_equation(self, rho=None)
Compute the symbolic Liouvillian acting on a state rho If no rho is given, an OperatorSymbol is created in its place. This correspnds to the RHS of the master equation in which an average is taken over the external noise degrees of freedom. Args: rho (Operator): A s...
5.993237
5.989739
1.000584
L, H = self.L, self.H if X is None: X = OperatorSymbol('X', hs=(L.space | H.space)) summands = [I * (H * X - X * H), ] for Lk in L.matrix.ravel(): summands.append(adjoint(Lk) * X * Lk) summands.append(-(adjoint(Lk) * Lk * X + X * adjoint(Lk)...
def symbolic_heisenberg_eom( self, X=None, noises=None, expand_simplify=True)
Compute the symbolic Heisenberg equations of motion of a system operator X. If no X is given, an OperatorSymbol is created in its place. If no noises are given, this correspnds to the ensemble-averaged Heisenberg equation of motion. Args: X (Operator): A system operator ...
4.237197
4.271003
0.992085
if not self._block_perms: self._block_perms = permutation_to_block_permutations( self.permutation) return self._block_perms
def block_perms(self)
If the circuit is reducible into permutations within subranges of the full range of channels, this yields a tuple with the internal permutations for each such block. :type: tuple
4.405171
4.913836
0.896483
combined_permutation = tuple([self.permutation[p] for p in other.permutation]) return CPermutation.create(combined_permutation)
def series_with_permutation(self, other)
Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: The composite permutation circuit (could also be the identity circuit for n channels)
10.212564
7.709621
1.324652
block_structure = rhs.block_structure block_perm, perms_within_blocks \ = block_perm_and_perms_within_blocks(self.permutation, block_structure) fblockp = full_block_perm(block_perm, block_structure) if not sorted(fbl...
def _factorize_for_rhs(self, rhs)
Factorize a channel permutation circuit according the block structure of the upstream circuit. This allows to move as much of the permutation as possible *around* a reducible circuit upstream. It basically decomposes ``permutation << rhs --> permutation' << rhs' << residual'`` ...
5.267124
4.35267
1.21009
n = self.cdim if not (0 <= in_port < n): raise Exception in_im = self.permutation[in_port] # (I) is equivalent to # m_{in_im -> (n-1)} << self << m_{(n-1) -> in_port} # == (red_self + cid(1)) (I') red_self_plus_cid1 = (map...
def _factor_rhs(self, in_port)
With:: n := self.cdim in_im := self.permutation[in_port] m_{k->l} := map_signals_circuit({k:l}, n) solve the equation (I) containing ``self``:: self << m_{(n-1) -> in_port} == m_{(n-1) -> in_im} << (red_self + cid(1)) ...
7.598378
4.006077
1.896713
n = self.cdim assert (0 <= out_port < n) out_inv = self.permutation.index(out_port) # (I) is equivalent to # m_{out_port -> (n-1)} << self << m_{(n-1) # -> out_inv} == (red_self + cid(1)) (I') red_self_plus_cid1 = (map_channels({out...
def _factor_lhs(self, out_port)
With:: n := self.cdim out_inv := invert_permutation(self.permutation)[out_port] m_{k->l} := map_signals_circuit({k:l}, n) solve the equation (I) containing ``self``:: m_{out_port -> (n-1)} << self == (red_self + cid(1)) << m_{ou...
8.416423
4.614962
1.823725
if self._cdim is None: self._cdim = sum((circuit.cdim for circuit in self.operands)) return self._cdim
def cdim(self)
Circuit dimension (sum of dimensions of the operands)
5.637262
2.802738
2.011341
cls = attr.s(cls, frozen=True) defaults = OrderedDict([(a.name, a.default) for a in cls.__attrs_attrs__]) def repr_(self): from qnet.printing import srepr real_cls = self.__class__ class_name = real_cls.__name__ args = [] for name in defaults.keys(): ...
def immutable_attribs(cls)
Class decorator like ``attr.s(frozen=True)`` with improved __repr__
3.093862
2.993851
1.033406
html = self.render( data=data, chart_type=chart_type, options=options, div_id=filename, head=self.head, w=w, h=h) if overwrite: with open(filename.replace(" ", "_") + '.html', 'w') as f: ...
def save(self, data, chart_type, options=None, filename='chart', w=800, h=420, overwrite=True)
Save the rendered html to a file in the same directory as the notebook.
1.989578
1.977456
1.00613
if subs is None: subs = [] if supers is None: supers = [] if translate_symbols: supers = [_translate_symbols(sup) for sup in supers] subs = [_translate_symbols(sub) for sub in subs] name = _translate_symbols(name) res = name try: if unicode_sub_su...
def render_unicode_sub_super( name, subs=None, supers=None, sub_first=True, translate_symbols=True, unicode_sub_super=True, sep=',', subscript_max_len=1)
Assemble a string from the primary name and the given sub- and superscripts:: >>> render_unicode_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2]) 'α_μ,ν^2' >>> render_unicode_sub_super( ... name='alpha', subs=['1', '2'], supers=['(1)'], sep='') 'α₁₂⁽¹⁾' >>> render_unicode_sub_su...
1.660719
1.728778
0.960632
string = str(string) if string.startswith('(') and string.endswith(')'): len_string = len(string) - 2 else: len_string = len(string) if max_len is not None: if len_string > max_len: raise KeyError("max_len exceeded") unicode_letters = [] for letter in str...
def _unicode_sub_super(string, mapping, max_len=None)
Try to render a subscript or superscript string in unicode, fall back on ascii if this is not possible
2.413205
2.360288
1.02242
res = [] string = str(string) for s in re.split(r'(\W+)', string, flags=re.UNICODE): tex_str = _GREEK_DICTIONARY.get(s) if tex_str: res.append(tex_str) elif s.lower() in _GREEK_DICTIONARY: res.append(_GREEK_DICTIONARY[s]) else: res.app...
def _translate_symbols(string)
Given a description of a Greek letter or other special character, return the appropriate unicode letter.
2.664049
2.57895
1.032998
if not self.is_valid_name(div_id): raise ValueError( "Name {} is invalid. Only letters, numbers, '_', and '-' are permitted ".format( div_id)) return Template(head + self.template).render( div_id=div_id.replace(" ", "_"), ...
def render(self, data, div_id="chart", head="")
Render the data in HTML template.
3.967771
3.551677
1.117154
self.save(data, filename, overwrite) return IFrame(filename + '.html', w, h)
def plot_and_save(self, data, w=800, h=420, filename='chart', overwrite=True)
Save the rendered html to a file and returns an IFrame to display the plot in the notebook.
5.998719
4.64381
1.291767
return HTML( self.iframe.format( source=self.render( data=data, div_id="chart", head=self.head), w=w, h=h))
def plot(self, data, w=800, h=420)
Output an iframe containing the plot in the notebook without saving.
8.991482
7.577421
1.186615
is_cached, res = super()._get_from_cache(expr) if is_cached: indent_str = " " * self._print_level return True, indent(res, indent_str) else: return False, None
def _get_from_cache(self, expr)
Obtain cached result, prepend with the keyname if necessary, and indent for the current level
5.214302
4.284401
1.217043
res = dedent(res) super()._write_to_cache(expr, res)
def _write_to_cache(self, expr, res)
Store the cached result without indentation, and without the keyname
5.915988
5.366547
1.102383
indent_str = " " * (self._print_level - 1) lines = [] if isinstance(expr.__class__, Singleton): # We exploit that Singletons override __expr__ to directly return # their name return indent_str + repr(expr) if isinstance(expr, Expression): ...
def emptyPrinter(self, expr)
Fallback printer
3.192667
3.18147
1.003519
res = [] for s in re.split(r'([,.:\s=]+)', string): tex_str = _TEX_GREEK_DICTIONARY.get(s) if tex_str: res.append(tex_str) elif s.lower() in greek_letters_set: res.append("\\" + s.lower()) elif s in other_symbols: res.append("\\" + s) ...
def _translate_symbols(string)
Given a description of a Greek letter or other special character, return the appropriate latex.
3.02209
2.93059
1.031222
r'''Assemble a string from the primary name and the given sub- and superscripts:: >>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2]) '\\alpha_{\\mu,\\nu}^{2}' >>> render_latex_sub_super( ... name='alpha', subs=['1', '2'], supers=['(1)'], sep='') ...
def render_latex_sub_super( name, subs=None, supers=None, translate_symbols=True, sep=',')
r'''Assemble a string from the primary name and the given sub- and superscripts:: >>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2]) '\\alpha_{\\mu,\\nu}^{2}' >>> render_latex_sub_super( ... name='alpha', subs=['1', '2'], supers=['(1)'], sep='') '\\...
2.902362
1.380366
2.102603
if isinstance(string, StrLabel): string = string._render(string.expr) string = str(string) if len(string) == 0: return '' name, supers, subs = split_super_sub(string) return render_latex_sub_super( name, subs, supers, translate_symbols...
def _render_str(self, string)
Returned a texified version of the string
7.5587
7.080191
1.067584
mapping = { True: { # use braket package 'bra': { True: r'\Bra{{{label}}}^{{({space})}}', 'subscript': r'\Bra{{{label}}}_{{({space})}}', False: r'\Bra{{{label}}}'}, 'ket': { Tru...
def _braket_fmt(self, expr_type)
Return a format string for printing an `expr_type` ket/bra/ketbra/braket
1.804261
1.760072
1.025106
hs_label = None if hs is not None and self._settings['show_hs_label']: hs_label = self._render_hs_label(hs) name, total_subscript, total_superscript, args_str \ = self._split_op(identifier, hs_label, dagger, args) if name.startswith(r'\text{'): ...
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False)
Render an operator Args: identifier (str): The identifier (name/symbol) of the operator. May include a subscript, denoted by '_'. hs (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbert space in which the operator is defined dagger (...
3.610418
3.860311
0.935266
return ( is_int(string) or is_float(string) or is_constant(string) or is_unary(string) or is_binary(string) or (string == '(') or (string == ')') )
def is_symbol(string)
Return true if the string is a mathematical symbol.
3.150059
3.18422
0.989272
scale_pattern = '|'.join(words) # For example: # (?:(?:\d+)\s+(?:hundred|thousand)*\s*)+(?:\d+|hundred|thousand)+ regex = re.compile( r'(?:(?:\d+)\s+(?:' + scale_pattern + r')*\s*)+(?:\d+|' + scale_pattern + r')+' ) result = regex.findall(string) return r...
def find_word_groups(string, words)
Find matches for words in the format "3 thousand 6 hundred 2". The words parameter should be the list of words to check for such as "hundred".
4.448619
3.984004
1.11662
words = mathwords.word_groups_for_language(language) # Replace operator words with numeric operators operators = words['binary_operators'].copy() if 'unary_operators' in words: operators.update(words['unary_operators']) for operator in list(operators.keys()): if operator in st...
def replace_word_tokens(string, language)
Given a string and an ISO 639-2 language code, return the string with the words replaced with an operational equivalent.
3.107618
3.071858
1.011641
precedence = { '/': 4, '*': 4, '+': 3, '-': 3, '^': 2, '(': 1 } postfix = [] opstack = [] for token in tokens: if is_int(token): postfix.append(int(token)) elif is_float(token): postfix.append(float(token)...
def to_postfix(tokens)
Convert a list of evaluatable tokens to postfix format.
1.66355
1.662027
1.000916
stack = [] for token in tokens: total = None if is_int(token) or is_float(token) or is_constant(token): stack.append(token) elif is_unary(token): a = stack.pop() total = mathwords.UNARY_FUNCTIONS[token](a) elif len(stack): b ...
def evaluate_postfix(tokens)
Given a list of evaluatable tokens in postfix format, calculate a solution.
2.437595
2.516906
0.968488
# Set all words to lowercase string = string.lower() # Ignore punctuation if len(string) and not string[-1].isalnum(): character = string[-1] string = string[:-1] + ' ' + character # Parenthesis must have space around them to be tokenized properly string = string.replace('...
def tokenize(string, language=None, escape='___')
Given a string, return a list of math symbol tokens
3.375193
3.318978
1.016937
if language: string = replace_word_tokens(string, language) tokens = tokenize(string) postfix = to_postfix(tokens) return evaluate_postfix(postfix)
def parse(string, language=None)
Return a solution to the equation in the input string.
5.372028
4.768919
1.126467
tokens = tokenize(dirty_string, language) start_index = 0 end_index = len(tokens) for part in tokens: if is_symbol(part) or is_word(part, language): break else: start_index += 1 for part in reversed(tokens): if is_symbol(part) or is_word(part, ...
def extract_expression(dirty_string, language)
Give a string such as: "What is 4 + 4?" Return the string "4 + 4"
2.08614
2.130993
0.978952
if hasattr(expr, '_order_key'): return expr._order_key try: if isinstance(expr.kwargs, OrderedDict): key_vals = expr.kwargs.values() else: key_vals = [expr.kwargs[key] for key in sorted(expr.kwargs)] return KeyTuple((expr.__class__.__name__, ) + ...
def expr_order_key(expr)
A default order key for arbitrary expressions
2.97914
2.981603
0.999174
if isinstance(hs, (str, int)): try: hs = cls(hs) except TypeError as exc_info: raise TypeError( "Cannot convert %s '%s' into a %s instance: %s" % (hs.__class__.__name__, hs, cls.__name__, str(exc_info))) if not isinstance(hs, LocalSpac...
def ensure_local_space(hs, cls=LocalSpace)
Ensure that the given `hs` is an instance of :class:`LocalSpace`. If `hs` an instance of :class:`str` or :class:`int`, it will be converted to a `cls` (if possible). If it already is an instace of `cls`, `hs` will be returned unchanged. Args: hs (HilbertSpace or str or int): The Hilbert space ...
2.905286
2.769339
1.04909
from qnet.algebra.core.scalar_algebra import Zero res = [] c1 = list(c1) c2 = list(c2) for n in range(order + 1): summands = [] for k in range(n + 1): if c1[k].is_zero or c2[n-k].is_zero: summands.append(Zero) else: summand...
def _series_expand_combine_prod(c1, c2, order)
Given the result of the ``c1._series_expand(...)`` and ``c2._series_expand(...)``, construct the result of ``(c1*c2)._series_expand(...)``
2.408242
2.589378
0.930046
if not isinstance(sym, sympy.Basic): raise TypeError("%s needs to be a Sympy symbol" % sym) if sym.free_symbols.issubset(self.free_symbols): # QuantumDerivative.create delegates internally to _diff (the # explicit non-trivial derivative). Using `create` gives...
def diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True)
Differentiate by scalar parameter `sym`. Args: sym: What to differentiate by. n: How often to differentiate expand_simplify: Whether to simplify the result. Returns: The n-th derivative.
9.250304
9.184155
1.007203
r expansion = self._series_expand(param, about, order) # _series_expand is generally not "type-stable", so we continue to # ensure the type-stability res = [] for v in expansion: if v == 0 or v.is_zero: v = self._zero elif v == 1: ...
def series_expand( self, param: Symbol, about, order: int) -> tuple
r"""Expand the expression as a truncated power series in a scalar parameter. When expanding an expr for a parameter $x$ about the point $x_0$ up to order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill .. math:: \text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(...
5.478108
5.465734
1.002264
if spc == TrivialSpace: ops_on_spc = [ o for o in self.operands if o.space is TrivialSpace] ops_not_on_spc = [ o for o in self.operands if o.space > TrivialSpace] else: ops_on_spc = [ o for o in self.operands if...
def factor_for_space(self, spc)
Return a tuple of two products, where the first product contains the given Hilbert space, and the second product is disjunct from it.
2.623131
2.539768
1.032823
# To ensure stable ordering in Expression._get_instance_key, we explicitly # convert `derivs` and `vals` to a tuple structure with a custom sorting key. if not isinstance(derivs, tuple): derivs = cls._dict_to_ordered_tuple(dict(derivs)) if not (isinstance(vals, tuple...
def create(cls, op, *, derivs, vals=None)
Instantiate the derivative by repeatedly calling the :meth:`~QuantumExpression._diff` method of `op` and evaluating the result at the given `vals`.
4.195246
4.229332
0.991941
new_vals = self._vals.copy() new_vals.update(vals) return self.__class__(self.operand, derivs=self._derivs, vals=new_vals)
def evaluate_at(self, vals)
Evaluate the derivative at a specific point
4.864332
4.793276
1.014824
if self._free_symbols is None: if len(self._vals) == 0: self._free_symbols = self.operand.free_symbols else: dummy_map = {} for sym in self._vals.keys(): dummy_map[sym] = sympy.Dummy() # bound sy...
def free_symbols(self)
Set of free SymPy symbols contained within the expression.
3.315786
3.248093
1.020841
if self._bound_symbols is None: res = set() self._bound_symbols = res.union( *[sym.free_symbols for sym in self._vals.keys()]) return self._bound_symbols
def bound_symbols(self)
Set of Sympy symbols that are eliminated by evaluation.
4.471599
3.707091
1.206229
# type: (nodes.NodeVisitor, unicode, Dict, unicode, unicode) -> Tuple[unicode, unicode] graphviz_dot = options.get('graphviz_dot', self.builder.config.graphviz_dot) hashkey = (code + str(options) + str(graphviz_dot) + str(self.builder.config.graphviz_dot_args)).encode('utf-8') fname...
def render_dot(self, code, options, format, prefix='graphviz')
Render graphviz code into a PNG or PDF output file.
2.504354
2.532753
0.988788
# type: () -> unicode if self.clickable: return '\n'.join([self.content[0]] + self.clickable + [self.content[-1]]) else: return ''
def generate_clickable_map(self)
Generate clickable map tags if clickable item exists. If not exists, this only returns empty string.
5.433347
5.104885
1.064343
try: spin_numer, spin_denom = hs.spin.as_numer_denom() except AttributeError: raise TypeError( "hs=%s for SpinBasisKet must be a SpinSpace instance" % hs) assert spin_denom in (1, 2) if spin_denom == 1: # integer spin if len(numer_denom) != 1: raise ...
def SpinBasisKet(*numer_denom, hs)
Constructor for a :class:`BasisKet` for a :class:`SpinSpace` For a half-integer spin system:: >>> hs = SpinSpace('s', spin=(3, 2)) >>> assert SpinBasisKet(1, 2, hs=hs) == BasisKet("+1/2", hs=hs) For an integer spin system:: >>> hs = SpinSpace('s', spin=1) >>> assert SpinBasis...
2.10029
1.972574
1.064746
r'''Eigenvalue of the $\Op{J}_{+}$ (:class:`Jplus`) operator .. math:: \Op{J}_{+} \ket{s, m} = \sqrt{s (s+1) - m (m+1)} \ket{s, m} where the multiplicity $s$ is implied by the size of the Hilbert space `ls`: there are $2s+1$ eigenstates with $m = -s, -s+1, \dots, s$. Args: ls (Lo...
def Jpjmcoeff(ls, m, shift=False) -> sympy.Expr
r'''Eigenvalue of the $\Op{J}_{+}$ (:class:`Jplus`) operator .. math:: \Op{J}_{+} \ket{s, m} = \sqrt{s (s+1) - m (m+1)} \ket{s, m} where the multiplicity $s$ is implied by the size of the Hilbert space `ls`: there are $2s+1$ eigenstates with $m = -s, -s+1, \dots, s$. Args: ls (LocalS...
5.249584
1.649249
3.183015
r'''Eigenvalue of the $\Op{J}_z$ (:class:`Jz`) operator .. math:: \Op{J}_{z} \ket{s, m} = m \ket{s, m} See also :func:`Jpjmcoeff`. ''' assert isinstance(ls, SpinSpace) n = ls.dimension s = sympify(n - 1) / 2 assert n == int(2 * s + 1) if isinstance(m, str): return ...
def Jzjmcoeff(ls, m, shift) -> sympy.Expr
r'''Eigenvalue of the $\Op{J}_z$ (:class:`Jz`) operator .. math:: \Op{J}_{z} \ket{s, m} = m \ket{s, m} See also :func:`Jpjmcoeff`.
6.349794
3.061344
2.074185
if isinstance(label_or_index, int): new_index = label_or_index + n if new_index < 0: raise IndexError("index %d < 0" % new_index) if new_index >= self.dimension: raise IndexError( "index %d out of range for basis %s...
def next_basis_label_or_index(self, label_or_index, n=1)
Given the label or index of a basis state, return the label the next basis state. More generally, if `n` is given, return the `n`'th next basis state label/index; `n` may also be negative to obtain previous basis state labels. Returns a :class:`str` label if `label_or_index` is a ...
1.943779
1.816288
1.070193
# type: (unicode) -> Any try: __import__(objname) return sys.modules.get(objname) # type: ignore except (ImportError, ValueError): # ValueError,py27 -> ImportError,py3 matched = module_sig_re.match(objname) # type: ignore if not matched: return None ...
def try_import(objname)
Import a object or module using *name* and *currentmodule*. *name* should be a relative name from *currentmodule* or a fully-qualified name. Returns imported object or module. If failed, returns None value.
3.12994
3.57937
0.874439
# type: (unicode, unicode) -> Any target = None # import class or module using currmodule if currmodule: target = try_import(currmodule + '.' + name) # import class or module without currmodule if target is None: target = try_import(name) if target is None: ra...
def import_classes(name, currmodule)
Import a class using its fully-qualified *name*.
3.381396
3.518067
0.961152
# type: (nodes.NodeVisitor, inheritance_diagram) -> None graph = node['graph'] graph_hash = get_graph_hash(node) name = 'inheritance%s' % graph_hash # Create a mapping from fully-qualified class names to URLs. graphviz_output_format = self.builder.env.config.graphviz_output_format.upper()...
def html_visit_inheritance_diagram(self, node)
Output the graph for HTML. This will insert a PNG with clickable image map.
3.569963
3.497527
1.020711
# type: (nodes.NodeVisitor, inheritance_diagram) -> None graph = node['graph'] graph_hash = get_graph_hash(node) name = 'inheritance%s' % graph_hash dotcode = graph.generate_dot(name, env=self.builder.env, graph_attrs={'size': '"6.0,6.0"'}) render_dot_late...
def latex_visit_inheritance_diagram(self, node)
Output the graph for LaTeX. This will insert a PDF.
6.73476
6.790349
0.991814
# type: (nodes.NodeVisitor, inheritance_diagram) -> None graph = node['graph'] graph_hash = get_graph_hash(node) name = 'inheritance%s' % graph_hash dotcode = graph.generate_dot(name, env=self.builder.env, graph_attrs={'size': '"6.0,6.0"'}) render_dot_texi...
def texinfo_visit_inheritance_diagram(self, node)
Output the graph for Texinfo. This will insert a PNG.
6.611531
6.906431
0.957301
# type: (unicode, str) -> List[Any] classes = [] # type: List[Any] for name in class_names: classes.extend(import_classes(name, currmodule)) return classes
def _import_classes(self, class_names, currmodule)
Import a list of classes.
3.586941
3.712392
0.966208
# type: (List[Any], bool, bool, int, Optional[Dict[unicode, unicode]], List[Any]) -> List[Tuple[unicode, unicode, List[unicode], unicode]] # NOQA all_classes = {} py_builtins = vars(builtins).values() def recurse(cls): # type: (Any) -> None if not show_...
def _class_info(self, classes, show_builtins, private_bases, parts, aliases, top_classes)
Return name and bases for all classes that are ancestors of *classes*. *parts* gives the number of dotted name parts that is removed from the displayed node names. *top_classes* gives the name(s) of the top most ancestor class to traverse to. Multiple names can be specified sep...
2.972797
3.198053
0.929565
# type: (Any, int, Optional[Dict[unicode, unicode]]) -> unicode module = cls.__module__ if module in ('__builtin__', 'builtins'): fullname = cls.__name__ else: fullname = '%s.%s' % (module, cls.__name__) if parts == 0: result = fullnam...
def class_name(self, cls, parts=0, aliases=None)
Given a class object, return a fully-qualified name. This works for things I've tested in matplotlib so far, but may not be completely general.
2.207543
2.450645
0.900801
# type: (unicode, Dict, BuildEnvironment, Dict, Dict, Dict) -> unicode g_attrs = self.default_graph_attrs.copy() n_attrs = self.default_node_attrs.copy() e_attrs = self.default_edge_attrs.copy() c_attrs = self.default_cluster_attrs.copy() g_attrs.update(graph_att...
def generate_dot(self, name, urls={}, env=None, graph_attrs={}, node_attrs={}, edge_attrs={})
Generate a graphviz dot graph from the classes that were passed in to __init__. *name* is the name of the graph. *urls* is a dictionary mapping class names to HTTP URLs. *graph_attrs*, *node_attrs*, *edge_attrs* are dictionaries containing key/value pairs to pass on as graphvi...
2.051701
2.149439
0.954528
# Deep copy of given config output = copy.deepcopy(configs) # Optionnaly filtering config from given names if names: output = {k: output[k] for k in names} # Select every config if selectors is empty if not on: on = output.keys() for k in on: output[k].update(...
def codemirror_settings_update(configs, parameters, on=None, names=None)
Return a new dictionnary of configs updated with given parameters. You may use ``on`` and ``names`` arguments to select config or filter out some configs from returned dict. Arguments: configs (dict): Dictionnary of configurations to update. parameters (dict): Dictionnary of parameters to ...
6.106079
5.241966
1.164845
lhs = self._lhs i = 0 while lhs is None: i -= 1 lhs = self._prev_lhs[i] return lhs
def lhs(self)
The left-hand-side of the equation
5.614345
5.359827
1.047486
return Eq( self._lhs, self._rhs, tag=tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
def set_tag(self, tag)
Return a copy of the equation with a new `tag`
4.433693
3.465084
1.279534
new_lhs = func(self.lhs, *args, **kwargs) if new_lhs == self.lhs and cont: new_lhs = None new_rhs = func(self.rhs, *args, **kwargs) new_tag = tag return self._update(new_lhs, new_rhs, new_tag, cont)
def apply(self, func, *args, cont=False, tag=None, **kwargs)
Apply `func` to both sides of the equation Returns a new equation where the left-hand-side and right-hand side are replaced by the application of `func`:: lhs=func(lhs, *args, **kwargs) rhs=func(rhs, *args, **kwargs) If ``cont=True``, the resulting equation will keep a...
2.76944
3.046233
0.909136
new_lhs = getattr(self.lhs, mtd)(*args, **kwargs) if new_lhs == self.lhs and cont: new_lhs = None new_rhs = getattr(self.rhs, mtd)(*args, **kwargs) new_tag = tag return self._update(new_lhs, new_rhs, new_tag, cont)
def apply_mtd(self, mtd, *args, cont=False, tag=None, **kwargs)
Call the method `mtd` on both sides of the equation That is, the left-hand-side and right-hand-side are replaced by:: lhs=lhs.<mtd>(*args, **kwargs) rhs=rhs.<mtd>(*args, **kwargs) The `cont` and `tag` parameters are as in :meth:`apply`.
2.690891
2.764791
0.973271
return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)
def substitute(self, var_map, cont=False, tag=None)
Substitute sub-expressions both on the lhs and rhs Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}``
3.749182
5.179705
0.723821
res = ( self.lhs.expand().simplify_scalar() - self.rhs.expand().simplify_scalar()) if func is not None: return func(res, *args, **kwargs) else: return res
def verify(self, func=None, *args, **kwargs)
Subtract the rhs from the lhs of the equation Before the substraction, each side is expanded and any scalars are simplified. If given, `func` with the positional arguments `args` and keyword-arguments `kwargs` is applied to the result before returning it. You may complete the v...
5.090003
3.700797
1.37538
return Eq( self._lhs, self._rhs, tag=self._tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
def copy(self)
Return a copy of the equation
4.367466
3.603441
1.212027
try: lhs_syms = self.lhs.free_symbols except AttributeError: lhs_syms = set() try: rhs_syms = self.rhs.free_symbols except AttributeError: rhs_syms = set() return lhs_syms | rhs_syms
def free_symbols(self)
Set of free SymPy symbols contained within the equation.
1.99521
1.830719
1.089851
try: lhs_syms = self.lhs.bound_symbols except AttributeError: lhs_syms = set() try: rhs_syms = self.rhs.bound_symbols except AttributeError: rhs_syms = set() return lhs_syms | rhs_syms
def bound_symbols(self)
Set of bound SymPy symbols contained within the equation.
2.111393
1.998408
1.056537
v = sympy.zeros(n, 1) v[i] = 1 return v
def basis_state(i, n)
``n x 1`` `sympy.Matrix` representing the `i`'th eigenstate of an `n`-dimensional Hilbert space (`i` >= 0)
3.730799
3.644772
1.023603
a = sympy.zeros(n) for i in range(1, n): a += sympy.sqrt(i) * basis_state(i, n) * basis_state(i-1, n).H return a
def SympyCreate(n)
Creation operator for a Hilbert space of dimension `n`, as an instance of `sympy.Matrix`
4.007821
3.955427
1.013246
overrides = self.formfield_overrides.get(db_field.name) if overrides: kwargs.update(overrides) field = super(AbstractEntryBaseAdmin, self).formfield_for_dbfield(db_field, **kwargs) # Pass user to the form. if db_field.name == 'author': field.use...
def formfield_for_dbfield(self, db_field, **kwargs)
Allow formfield_overrides to contain field names too.
3.22565
2.890968
1.115768
if len(generators) == 0: yield () else: generators = generators * repeat it = generators[0] for item in it() if callable(it) else iter(it): for items in product(*generators[1:]): yield (item, ) + items
def product(*generators, repeat=1)
Cartesian product akin to :func:`itertools.product`, but accepting generator functions Unlike :func:`itertools.product` this function does not convert the input iterables into tuples. Thus, it can handle large or infinite inputs. As a drawback, however, it only works with "restartable" iterables (somet...
3.476307
3.897058
0.892034
return self.__class__( self.name, primed=self._primed + incr, **self._assumptions.generator)
def incr_primed(self, incr=1)
Return a copy of the index with an incremented :attr:`primed`
11.431264
9.243196
1.236722
# this assumes that no sub-class of Expression shadows # Expression.instance_caching orig_flag = Expression.instance_caching Expression.instance_caching = False try: yield finally: Expression.instance_caching = orig_flag
def no_instance_caching()
Temporarily disable instance caching in :meth:`~.Expression.create` Within the managed context, :meth:`~.Expression.create` will not use any caching, for any class.
6.060928
5.93628
1.020998
orig_instances = [] for cls in classes: orig_instances.append(cls._instances) cls._instances = {} try: yield finally: for i, cls in enumerate(classes): cls._instances = orig_instances[i]
def temporary_instance_cache(*classes)
Use a temporary cache for instances in :meth:`~.Expression.create` The instance cache used by :meth:`~.Expression.create` for any of the given `classes` will be cleared upon entering the managed context, and restored on leaving it. That is, no cached instances from outside of the managed context will ...
2.247152
2.552327
0.880432
orig_instances = [] orig_rules = [] orig_binary_rules = [] orig_simplifications = [] for cls in classes: orig_instances.append(cls._instances) cls._instances = {} orig_simplifications.append(cls.simplifications) cls.simplifications = cls.simplifications.copy() ...
def temporary_rules(*classes, clear=False)
Allow temporary modification of rules for :meth:`~.Expression.create` For every one of the given `classes`, protect the rules (processed by :func:`.match_replace` or :func:`.match_replace_binary`) associated with that class from modification beyond the managed context. Implies :func:`temporary_instance...
1.669829
1.666014
1.00229
try: name, subscript = identifier.split("_", 1) except (TypeError, ValueError, AttributeError): name = identifier subscript = '' return self._render_str(name), self._render_str(subscript)
def _split_identifier(self, identifier)
Split the given identifier at the first underscore into (rendered) name and subscript. Both `name` and `subscript` are rendered as strings
4.263758
3.023441
1.410234
if self._isinstance(identifier, 'SymbolicLabelBase'): identifier = QnetAsciiDefaultPrinter()._print_SCALAR_TYPES( identifier.expr) name, total_subscript = self._split_identifier(identifier) total_superscript = '' if (hs_label not in [None, '']): ...
def _split_op( self, identifier, hs_label=None, dagger=False, args=None)
Return `name`, total `subscript`, total `superscript` and `arguments` str. All of the returned strings are fully rendered. Args: identifier (str or SymbolicLabelBase): A (non-rendered/ascii) identifier that may include a subscript. The output `name` will be t...
4.265041
3.124073
1.365218
if isinstance(hs.__class__, Singleton): return self._render_str(hs.label) else: return self._tensor_sym.join( [self._render_str(ls.label) for ls in hs.local_factors])
def _render_hs_label(self, hs)
Return the label of the given Hilbert space as a string
7.859247
6.861914
1.145343
mapping = { 'bra': { True: '<{label}|^({space})', 'subscript': '<{label}|_({space})', False: '<{label}|'}, 'ket': { True: '|{label}>^({space})', 'subscript': '|{label}>_({space})', F...
def _braket_fmt(self, expr_type)
Return a format string for printing an `expr_type` ket/bra/ketbra/braket
2.595335
2.382052
1.089538
hs_label = None if hs is not None and self._settings['show_hs_label']: hs_label = self._render_hs_label(hs) name, total_subscript, total_superscript, args_str \ = self._split_op(identifier, hs_label, dagger, args) res = name if len(total_subscript...
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False)
Render an operator Args: identifier (str or SymbolicLabelBase): The identifier (name/symbol) of the operator. May include a subscript, denoted by '_'. hs (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbert space in which the operator is defined...
3.032388
3.331287
0.910275
needs_parenths = ( (precedence(expr) < level) or (strict and precedence(expr) == level)) if needs_parenths: return ( self._parenth_left + self.doprint(expr, *args, **kwargs) + self._parenth_right) else: retu...
def parenthesize(self, expr, level, *args, strict=False, **kwargs)
Render `expr` and wrap the result in parentheses if the precedence of `expr` is below the given `level` (or at the given `level` if `strict` is True. Extra `args` and `kwargs` are passed to the internal `doit` renderer
3.295387
2.659014
1.239327