code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _factor_lhs(self, out_port): 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_port: (n - 1)}, n) << self << map_channels({(n - 1): out_inv}, n)) if isinstance(red_self_plus_cid1, CPermutation): #make sure we can factor assert red_self_plus_cid1.permutation[(n - 1)] == (n - 1) #form reduced permutation object red_self = CPermutation.create(red_self_plus_cid1.permutation[:-1]) return out_inv, red_self else: # 'red_self_plus_cid1' must be the identity for n channels. # Actually, this case can only occur # when self == m_{in_port -> in_im} return out_inv, circuit_identity(n - 1)
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_{out_inv -> (n-1)} (I) for the (n-1) channel CPermutation ``red_self``. Return out_inv, red_self. This is useful when 'self' is the LHS in a SeriesProduct Object that is within a Feedback loop as it allows to extract the feedback channel from the permutation and moving the remaining part of the permutation (``red_self``) outside of the feedback loop.
def cdim(self): if self._cdim is None: self._cdim = sum((circuit.cdim for circuit in self.operands)) return self._cdim
Circuit dimension (sum of dimensions of the operands)
def immutable_attribs(cls): 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(): val = getattr(self, name) positional = defaults[name] == attr.NOTHING if val != defaults[name]: args.append( srepr(val) if positional else "%s=%s" % (name, srepr(val))) return "{0}({1})".format(class_name, ", ".join(args)) cls.__repr__ = repr_ return cls
Class decorator like ``attr.s(frozen=True)`` with improved __repr__
def save(self, data, chart_type, options=None, filename='chart', w=800, h=420, overwrite=True): 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: f.write(html) else: if not os.path.exists(filename.replace(" ", "_") + '.html'): with open(filename.replace(" ", "_") + '.html', 'w') as f: f.write(html) else: raise IOError('File Already Exists!')
Save the rendered html to a file in the same directory as the notebook.
def _unicode_sub_super(string, mapping, max_len=None): 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 string: unicode_letters.append(mapping[letter]) return ''.join(unicode_letters)
Try to render a subscript or superscript string in unicode, fall back on ascii if this is not possible
def _translate_symbols(string): 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.append(s) return "".join(res)
Given a description of a Greek letter or other special character, return the appropriate unicode letter.
def render(self, data, div_id="chart", head=""): 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(" ", "_"), data=json.dumps( data, indent=4).replace("'", "\\'").replace('"', "'"))
Render the data in HTML template.
def plot_and_save(self, data, w=800, h=420, filename='chart', overwrite=True): self.save(data, filename, overwrite) return IFrame(filename + '.html', w, h)
Save the rendered html to a file and returns an IFrame to display the plot in the notebook.
def plot(self, data, w=800, h=420): return HTML( self.iframe.format( source=self.render( data=data, div_id="chart", head=self.head), w=w, h=h))
Output an iframe containing the plot in the notebook without saving.
def _get_from_cache(self, expr): 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
Obtain cached result, prepend with the keyname if necessary, and indent for the current level
def _write_to_cache(self, expr, res): res = dedent(res) super()._write_to_cache(expr, res)
Store the cached result without indentation, and without the keyname
def emptyPrinter(self, expr): 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): args = expr.args keys = expr.minimal_kwargs.keys() lines.append(indent_str + expr.__class__.__name__ + "(") for arg in args: lines.append(self.doprint(arg) + ",") for key in keys: arg = expr.kwargs[key] lines.append( (" " * self._print_level) + key + '=' + self.doprint(arg).lstrip() + ",") if len(args) > 0 or len(keys) > 0: lines[-1] = lines[-1][:-1] # drop trailing comma for last arg lines[-1] += ")" elif isinstance(expr, (tuple, list)): delims = ("(", ")") if isinstance(expr, tuple) else ("[", "]") if len(expr) == 1: delims = (delims[0], "," + delims[1]) lines.append( indent_str + delims[0] + ", ".join([render_head_repr(v) for v in expr]) + delims[1]) else: lines.append(indent_str + SympyReprPrinter().doprint(expr)) return "\n".join(lines)
Fallback printer
def _translate_symbols(string): 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) else: if re.match(r'^[a-zA-Z]{4,}$', s): res.append(r'\text{' + s + '}') else: res.append(s) return "".join(res)
Given a description of a Greek letter or other special character, return the appropriate latex.
def _render_str(self, string): 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=True)
Returned a texified version of the string
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False): 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{'): name = name[6:-1] if self._is_single_letter(name): if superop: name_fmt = self._settings['tex_sop_macro'] else: name_fmt = self._settings['tex_op_macro'] else: if superop: name_fmt = self._settings['tex_textsop_macro'] else: name_fmt = self._settings['tex_textop_macro'] res = name_fmt.format(name=name) res = render_latex_sub_super( res, [total_subscript], [total_superscript], translate_symbols=True) res += args_str return res
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 (bool): Whether the operator should be daggered args (list): A list of expressions that will be rendered with :meth:`doprint`, joined with commas, enclosed in parenthesis superop (bool): Whether the operator is a super-operator
def is_symbol(string): return ( is_int(string) or is_float(string) or is_constant(string) or is_unary(string) or is_binary(string) or (string == '(') or (string == ')') )
Return true if the string is a mathematical symbol.
def find_word_groups(string, words): 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 result
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".
def replace_word_tokens(string, language): 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 string: string = string.replace(operator, operators[operator]) # Replace number words with numeric values numbers = words['numbers'] for number in list(numbers.keys()): if number in string: string = string.replace(number, str(numbers[number])) # Replace scaling multipliers with numeric values scales = words['scales'] end_index_characters = mathwords.BINARY_OPERATORS end_index_characters.add('(') word_matches = find_word_groups(string, list(scales.keys())) for match in word_matches: string = string.replace(match, '(' + match + ')') for scale in list(scales.keys()): for _ in range(0, string.count(scale)): start_index = string.find(scale) - 1 end_index = len(string) while is_int(string[start_index - 1]) and start_index > 0: start_index -= 1 end_index = string.find(' ', start_index) + 1 end_index = string.find(' ', end_index) + 1 add = ' + ' if string[end_index] in end_index_characters: add = '' string = string[:start_index] + '(' + string[start_index:] string = string.replace( scale, '* ' + str(scales[scale]) + ')' + add, 1 ) string = string.replace(') (', ') + (') return string
Given a string and an ISO 639-2 language code, return the string with the words replaced with an operational equivalent.
def to_postfix(tokens): 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)) elif token in mathwords.CONSTANTS: postfix.append(mathwords.CONSTANTS[token]) elif is_unary(token): opstack.append(token) elif token == '(': opstack.append(token) elif token == ')': top_token = opstack.pop() while top_token != '(': postfix.append(top_token) top_token = opstack.pop() else: while (opstack != []) and ( precedence[opstack[-1]] >= precedence[token] ): postfix.append(opstack.pop()) opstack.append(token) while opstack != []: postfix.append(opstack.pop()) return postfix
Convert a list of evaluatable tokens to postfix format.
def evaluate_postfix(tokens): 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 = stack.pop() a = stack.pop() if token == '+': total = a + b elif token == '-': total = a - b elif token == '*': total = a * b elif token == '^': total = a ** b elif token == '/': if Decimal(str(b)) == 0: total = 'undefined' else: total = Decimal(str(a)) / Decimal(str(b)) else: raise PostfixTokenEvaluationException( 'Unknown token {}'.format(token) ) if total is not None: stack.append(total) # If the stack is empty the tokens could not be evaluated if not stack: raise PostfixTokenEvaluationException( 'The postfix expression resulted in an empty stack' ) return stack.pop()
Given a list of evaluatable tokens in postfix format, calculate a solution.
def tokenize(string, language=None, escape='___'): # 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('(', ' ( ') string = string.replace(')', ' ) ') if language: words = mathwords.words_for_language(language) for phrase in words: escaped_phrase = phrase.replace(' ', escape) string = string.replace(phrase, escaped_phrase) tokens = string.split() for index, token in enumerate(tokens): tokens[index] = token.replace(escape, ' ') return tokens
Given a string, return a list of math symbol tokens
def parse(string, language=None): if language: string = replace_word_tokens(string, language) tokens = tokenize(string) postfix = to_postfix(tokens) return evaluate_postfix(postfix)
Return a solution to the equation in the input string.
def extract_expression(dirty_string, language): 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, language): break else: end_index -= 1 return ' '.join(tokens[start_index:end_index])
Give a string such as: "What is 4 + 4?" Return the string "4 + 4"
def expr_order_key(expr): 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__, ) + tuple(map(expr_order_key, expr.args)) + tuple(map(expr_order_key, key_vals))) except AttributeError: return str(expr)
A default order key for arbitrary expressions
def ensure_local_space(hs, cls=LocalSpace): 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, LocalSpace): raise TypeError("hs must be an instance of LocalSpace") return hs
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 (or label) to convert/check cls (type): The class to which an int/str label for a Hilbert space should be converted. Must be a subclass of :class:`LocalSpace`. Raises: TypeError: If `hs` is not a :class:`.LocalSpace`, :class:`str`, or :class:`int`. Returns: LocalSpace: original or converted `hs` Examples: >>> srepr(ensure_local_space(0)) "LocalSpace('0')" >>> srepr(ensure_local_space('tls')) "LocalSpace('tls')" >>> srepr(ensure_local_space(0, cls=LocalSpace)) "LocalSpace('0')" >>> srepr(ensure_local_space(LocalSpace(0))) "LocalSpace('0')" >>> srepr(ensure_local_space(LocalSpace(0))) "LocalSpace('0')" >>> srepr(ensure_local_space(LocalSpace(0) * LocalSpace(1))) Traceback (most recent call last): ... TypeError: hs must be an instance of LocalSpace
def _series_expand_combine_prod(c1, c2, order): 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: summands.append(c1[k] * c2[n - k]) sum = summands[0] for summand in summands[1:]: if summand != 0: sum += summand res.append(sum) return tuple(res)
Given the result of the ``c1._series_expand(...)`` and ``c2._series_expand(...)``, construct the result of ``(c1*c2)._series_expand(...)``
def diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True): 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 us free # caching deriv = QuantumDerivative.create(self, derivs={sym: n}, vals=None) if not deriv.is_zero and expand_simplify: deriv = deriv.expand().simplify_scalar() return deriv else: # the "issubset" of free symbols is a sufficient, but not a # necessary condition; if `sym` is non-atomic, determining whether # `self` depends on `sym` is not completely trivial (you'd have to # substitute with a Dummy) return self.__class__._zero
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.
def series_expand( self, param: Symbol, about, order: int) -> tuple: 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: v = self._one assert isinstance(v, self._base_cls) res.append(v) return tuple(res)
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(N+1) Args: param: Expansion parameter $x$ about (Scalar): Point $x_0$ about which to expand order: Maximum order $N$ of expansion (>= 0) Returns: tuple of length ``order + 1``, where the entries are the expansion coefficients, $(c_0, \dots, c_N)$. Note: The expansion coefficients are "type-stable", in that they share a common base class with the original expression. In particular, this applies to "zero" coefficients:: >>> expr = KetSymbol("Psi", hs=0) >>> t = sympy.symbols("t") >>> assert expr.series_expand(t, 0, 1) == (expr, ZeroKet)
def factor_for_space(self, spc): 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 (o.space & spc) > TrivialSpace] ops_not_on_spc = [ o for o in self.operands if (o.space & spc) is TrivialSpace] return ( self.__class__._times_cls.create(*ops_on_spc), self.__class__._times_cls.create(*ops_not_on_spc))
Return a tuple of two products, where the first product contains the given Hilbert space, and the second product is disjunct from it.
def create(cls, op, *, derivs, vals=None): # 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) or vals is None): vals = cls._dict_to_ordered_tuple(dict(vals)) return super().create(op, derivs=derivs, vals=vals)
Instantiate the derivative by repeatedly calling the :meth:`~QuantumExpression._diff` method of `op` and evaluating the result at the given `vals`.
def evaluate_at(self, vals): new_vals = self._vals.copy() new_vals.update(vals) return self.__class__(self.operand, derivs=self._derivs, vals=new_vals)
Evaluate the derivative at a specific point
def free_symbols(self): 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 symbols may not be atomic, so we have to replace them # with dummies self._free_symbols = { sym for sym in self.operand.substitute(dummy_map).free_symbols if not isinstance(sym, sympy.Dummy)} for val in self._vals.values(): self._free_symbols.update(val.free_symbols) return self._free_symbols
Set of free SymPy symbols contained within the expression.
def bound_symbols(self): 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
Set of Sympy symbols that are eliminated by evaluation.
def generate_clickable_map(self): # type: () -> unicode if self.clickable: return '\n'.join([self.content[0]] + self.clickable + [self.content[-1]]) else: return ''
Generate clickable map tags if clickable item exists. If not exists, this only returns empty string.
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`. ''' assert isinstance(ls, SpinSpace) n = ls.dimension s = sympify(n - 1) / 2 assert n == int(2 * s + 1) if isinstance(m, str): return ls.basis.index(m) - s elif isinstance(m, int): if shift: assert 0 <= m < n return m - s else: return sympify(mf 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`. ''' assert isinstance(ls, SpinSpace) n = ls.dimension s = sympify(n - 1) / 2 assert n == int(2 * s + 1) if isinstance(m, str): return ls.basis.index(m) - s elif isinstance(m, int): if shift: assert 0 <= m < n return m - s else: return sympify(m)
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`.
def try_import(objname): # 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 modname, attrname = matched.groups() if modname is None: return None try: __import__(modname) return getattr(sys.modules.get(modname), attrname, None) except (ImportError, ValueError): # ValueError,py27 -> ImportError,py3 return None
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.
def import_classes(name, currmodule): # 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: raise InheritanceException( 'Could not import class or module %r specified for ' 'inheritance diagram' % name) if inspect.isclass(target): # If imported object is a class, just return it return [target] elif inspect.ismodule(target): # If imported object is a module, return classes defined on it classes = [] for cls in target.__dict__.values(): if inspect.isclass(cls) and cls_is_in_module(cls, mod=target): classes.append(cls) return classes raise InheritanceException('%r specified for inheritance diagram is ' 'not a class or module' % name)
Import a class using its fully-qualified *name*.
def html_visit_inheritance_diagram(self, node): # 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() current_filename = self.builder.current_docname + self.builder.out_suffix urls = {} for child in node: if child.get('refuri') is not None: if graphviz_output_format == 'SVG': urls[child['reftitle']] = os.path.join("..", child.get('refuri')) else: urls[child['reftitle']] = child.get('refuri') elif child.get('refid') is not None: if graphviz_output_format == 'SVG': urls[child['reftitle']] = os.path.join('..', current_filename + '#' + child.get('refid')) else: urls[child['reftitle']] = '#' + child.get('refid') dotcode = graph.generate_dot(name, urls, env=self.builder.env) render_dot_html( self, node, dotcode, {}, 'inheritance', 'inheritance', alt='Inheritance diagram of ' + node['content'], link_to_svg='<i class="fa fa-external-link" aria-hidden="true"></i>'' SVG') raise nodes.SkipNode
Output the graph for HTML. This will insert a PNG with clickable image map.
def latex_visit_inheritance_diagram(self, node): # 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_latex(self, node, dotcode, {}, 'inheritance') raise nodes.SkipNode
Output the graph for LaTeX. This will insert a PDF.
def texinfo_visit_inheritance_diagram(self, node): # 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_texinfo(self, node, dotcode, {}, 'inheritance') raise nodes.SkipNode
Output the graph for Texinfo. This will insert a PNG.
def _import_classes(self, class_names, currmodule): # type: (unicode, str) -> List[Any] classes = [] # type: List[Any] for name in class_names: classes.extend(import_classes(name, currmodule)) return classes
Import a list of classes.
def _class_info(self, classes, show_builtins, private_bases, parts, aliases, top_classes): # 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_builtins and cls in py_builtins: return if not private_bases and cls.__name__.startswith('_'): return nodename = self.class_name(cls, parts, aliases) fullname = self.class_name(cls, 0, aliases) # Use first line of docstring as tooltip, if available tooltip = None try: if cls.__doc__: enc = ModuleAnalyzer.for_module(cls.__module__).encoding doc = cls.__doc__.strip().split("\n")[0] if not isinstance(doc, text_type): doc = force_decode(doc, enc) if doc: tooltip = '"%s"' % doc.replace('"', '\\"') except Exception: # might raise AttributeError for strange classes pass baselist = [] # type: List[unicode] all_classes[cls] = (nodename, fullname, baselist, tooltip) if fullname in top_classes: return for base in cls.__bases__: if not show_builtins and base in py_builtins: continue if not private_bases and base.__name__.startswith('_'): continue baselist.append(self.class_name(base, parts, aliases)) if base not in all_classes: recurse(base) for cls in classes: recurse(cls) return list(all_classes.values())
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 separated by comma.
def class_name(self, cls, parts=0, aliases=None): # 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 = fullname else: name_parts = fullname.split('.') result = '.'.join(name_parts[-parts:]) if aliases is not None and result in aliases: return aliases[result] return result
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.
def codemirror_settings_update(configs, parameters, on=None, names=None): # 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(parameters) return output
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 apply on selected configurations. Keyword Arguments: on (list): List of configuration names to select for update. If empty, all given configurations will be updated. names (list): List of configuration names to keep. If not empty, only those configurations will be in returned dict. Else every configs from original dict will be present. Returns: dict: Dict of configurations with updated parameters.
def lhs(self): lhs = self._lhs i = 0 while lhs is None: i -= 1 lhs = self._prev_lhs[i] return lhs
The left-hand-side of the equation
def set_tag(self, tag): return Eq( self._lhs, self._rhs, tag=tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
Return a copy of the equation with a new `tag`
def apply(self, func, *args, cont=False, tag=None, **kwargs): 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)
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 history of its previous state (resulting in multiple lines of equations when printed, as in the main example above). The resulting equation with have the given `tag`.
def apply_mtd(self, mtd, *args, cont=False, tag=None, **kwargs): 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)
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`.
def substitute(self, var_map, cont=False, tag=None): return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)
Substitute sub-expressions both on the lhs and rhs Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}``
def verify(self, func=None, *args, **kwargs): res = ( self.lhs.expand().simplify_scalar() - self.rhs.expand().simplify_scalar()) if func is not None: return func(res, *args, **kwargs) else: return res
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 verification by checking the :attr:`is_zero` attribute of the returned expression.
def copy(self): return Eq( self._lhs, self._rhs, tag=self._tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
Return a copy of the equation
def free_symbols(self): 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
Set of free SymPy symbols contained within the equation.
def bound_symbols(self): 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
Set of bound SymPy symbols contained within the equation.
def basis_state(i, n): v = sympy.zeros(n, 1) v[i] = 1 return v
``n x 1`` `sympy.Matrix` representing the `i`'th eigenstate of an `n`-dimensional Hilbert space (`i` >= 0)
def SympyCreate(n): 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
Creation operator for a Hilbert space of dimension `n`, as an instance of `sympy.Matrix`
def formfield_for_dbfield(self, db_field, **kwargs): 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.user = kwargs['request'].user return field
Allow formfield_overrides to contain field names too.
def product(*generators, repeat=1): 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
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 (something that :func:`iter` can repeatably turn into an iterator, or a generator function (but not the generator iterator that is returned by that generator function) Args: generators: list of restartable iterators or generator functions repeat: number of times `generators` should be repeated Adapted from https://stackoverflow.com/q/12093364/
def incr_primed(self, incr=1): return self.__class__( self.name, primed=self._primed + incr, **self._assumptions.generator)
Return a copy of the index with an incremented :attr:`primed`
def no_instance_caching(): # 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
Temporarily disable instance caching in :meth:`~.Expression.create` Within the managed context, :meth:`~.Expression.create` will not use any caching, for any class.
def temporary_instance_cache(*classes): 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]
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 be used within the managed context, and vice versa
def _split_identifier(self, identifier): try: name, subscript = identifier.split("_", 1) except (TypeError, ValueError, AttributeError): name = identifier subscript = '' return self._render_str(name), self._render_str(subscript)
Split the given identifier at the first underscore into (rendered) name and subscript. Both `name` and `subscript` are rendered as strings
def _split_op( self, identifier, hs_label=None, dagger=False, args=None): 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, '']): if self._settings['show_hs_label'] == 'subscript': if len(total_subscript) == 0: total_subscript = '(' + hs_label + ')' else: total_subscript += ',(' + hs_label + ')' else: total_superscript += '(' + hs_label + ')' if dagger: total_superscript += self._dagger_sym args_str = '' if (args is not None) and (len(args) > 0): args_str = (self._parenth_left + ",".join([self.doprint(arg) for arg in args]) + self._parenth_right) return name, total_subscript, total_superscript, args_str
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 the `identifier` without any subscript hs_label (str): The rendered label for the Hilbert space of the operator, or None. Returned unchanged. dagger (bool): Flag to indicate whether the operator is daggered. If True, :attr:`dagger_sym` will be included in the `superscript` (or `subscript`, depending on the settings) args (list or None): List of arguments (expressions). Each element will be rendered with :meth:`doprint`. The total list of args will then be joined with commas, enclosed with :attr:`_parenth_left` and :attr:`parenth_right`, and returnd as the `arguments` string
def _render_hs_label(self, hs): 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])
Return the label of the given Hilbert space as a string
def _braket_fmt(self, expr_type): mapping = { 'bra': { True: '<{label}|^({space})', 'subscript': '<{label}|_({space})', False: '<{label}|'}, 'ket': { True: '|{label}>^({space})', 'subscript': '|{label}>_({space})', False: '|{label}>'}, 'ketbra': { True: '|{label_i}><{label_j}|^({space})', 'subscript': '|{label_i}><{label_j}|_({space})', False: '|{label_i}><{label_j}|'}, 'braket': { True: '<{label_i}|{label_j}>^({space})', 'subscript': '<{label_i}|{label_j}>_({space})', False: '<{label_i}|{label_j}>'}, } hs_setting = bool(self._settings['show_hs_label']) if self._settings['show_hs_label'] == 'subscript': hs_setting = 'subscript' return mapping[expr_type][hs_setting]
Return a format string for printing an `expr_type` ket/bra/ketbra/braket
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False): 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) > 0: res += "_" + total_subscript if len(total_superscript) > 0: res += "^" + total_superscript if len(args_str) > 0: res += args_str return res
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 dagger (bool): Whether the operator should be daggered args (list): A list of expressions that will be rendered with :meth:`doprint`, joined with commas, enclosed in parenthesis superop (bool): Whether the operator is a super-operator
def parenthesize(self, expr, level, *args, strict=False, **kwargs): 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: return self.doprint(expr, *args, **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
def _curve(x1, y1, x2, y2, hunit = HUNIT, vunit = VUNIT): ax1, ax2, axm = x1 * hunit, x2 * hunit, (x1 + x2) * hunit / 2 ay1, ay2 = y1 * vunit, y2 * vunit return pyx.path.curve(ax1, ay1, axm, ay1, axm, ay2, ax2, ay2)
Return a PyX curved path from (x1, y1) to (x2, y2), such that the slope at either end is zero.
def nested_tuple(container): if isinstance(container, OrderedDict): return tuple(map(nested_tuple, container.items())) if isinstance(container, Mapping): return tuple(sorted_if_possible(map(nested_tuple, container.items()))) if not isinstance(container, (str, bytes)): if isinstance(container, Sequence): return tuple(map(nested_tuple, container)) if ( isinstance(container, Container) and isinstance(container, Iterable) and isinstance(container, Sized) ): return tuple(sorted_if_possible(map(nested_tuple, container))) return container
Recursively transform a container structure to a nested tuple. The function understands container types inheriting from the selected abstract base classes in `collections.abc`, and performs the following replacements: `Mapping` `tuple` of key-value pair `tuple`s. The order is preserved in the case of an `OrderedDict`, otherwise the key-value pairs are sorted if orderable and otherwise kept in the order of iteration. `Sequence` `tuple` containing the same elements in unchanged order. `Container and Iterable and Sized` (equivalent to `Collection` in python >= 3.6) `tuple` containing the same elements in sorted order if orderable and otherwise kept in the order of iteration. The function recurses into these container types to perform the same replacement, and leaves objects of other types untouched. The returned container is hashable if and only if all the values contained in the original data structure are hashable. Parameters ---------- container Data structure to transform into a nested tuple. Returns ------- tuple Nested tuple containing the same data as `container`.
def precedence(item): try: mro = item.__class__.__mro__ except AttributeError: return PRECEDENCE["Atom"] for i in mro: n = i.__name__ if n in PRECEDENCE_FUNCTIONS: return PRECEDENCE_FUNCTIONS[n](item) elif n in PRECEDENCE_VALUES: return PRECEDENCE_VALUES[n] return PRECEDENCE["Atom"]
Returns the precedence of a given object.
def render(self, data, chart_type, chart_package='corechart', options=None, div_id="chart", head=""): 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(" ", "_"), data=json.dumps( data, indent=4).replace("'", "\\'").replace('"', "'"), chart_type=chart_type, chart_package=chart_package, options=json.dumps( options, indent=4).replace("'", "\\'").replace('"', "'"))
Render the data in HTML template.
def plot(self, data, chart_type, chart_package='corechart', options=None, w=800, h=420): return HTML( self.iframe.format( source=self.render( data=data, options=options, chart_type=chart_type, chart_package=chart_package, head=self.head), w=w, h=h))
Output an iframe containing the plot in the notebook without saving.
def published(self, for_user=None): if appsettings.FLUENT_BLOGS_FILTER_SITE_ID: qs = self.parent_site(settings.SITE_ID) else: qs = self if for_user is not None and for_user.is_staff: return qs return qs \ .filter(status=self.model.PUBLISHED) \ .filter( Q(publication_date__isnull=True) | Q(publication_date__lte=now()) ).filter( Q(publication_end_date__isnull=True) | Q(publication_end_date__gte=now()) )
Return only published entries for the current site.
def authors(self, *usernames): if len(usernames) == 1: return self.filter(**{"author__{}".format(User.USERNAME_FIELD): usernames[0]}) else: return self.filter(**{"author__{}__in".format(User.USERNAME_FIELD): usernames})
Return the entries written by the given usernames When multiple tags are provided, they operate as "OR" query.
def categories(self, *category_slugs): categories_field = getattr(self.model, 'categories', None) if categories_field is None: raise AttributeError("The {0} does not include CategoriesEntryMixin".format(self.model.__name__)) if issubclass(categories_field.rel.model, TranslatableModel): # Needs a different field, assume slug is translated (e.g django-categories-i18n) filters = { 'categories__translations__slug__in': category_slugs, } # TODO: should the current language also be used as filter somehow? languages = self._get_active_rel_languages() if languages: if len(languages) == 1: filters['categories__translations__language_code'] = languages[0] else: filters['categories__translations__language_code__in'] = languages return self.filter(**filters).distinct() else: return self.filter(categories__slug=category_slugs)
Return the entries with the given category slugs. When multiple tags are provided, they operate as "OR" query.
def tagged(self, *tag_slugs): if getattr(self.model, 'tags', None) is None: raise AttributeError("The {0} does not include TagsEntryMixin".format(self.model.__name__)) if len(tag_slugs) == 1: return self.filter(tags__slug=tag_slugs[0]) else: return self.filter(tags__slug__in=tag_slugs).distinct()
Return the items which are tagged with a specific tag. When multiple tags are provided, they operate as "OR" query.
def format(self, **kwargs): name = self.name.format(**kwargs) subs = [] if self.sub is not None: subs = [self.sub.format(**kwargs)] supers = [] if self.sup is not None: supers = [self.sup.format(**kwargs)] return render_unicode_sub_super( name, subs, supers, sub_first=True, translate_symbols=True, unicode_sub_super=self.unicode_sub_super)
Format and combine the name, subscript, and superscript
def _render_str(self, string): 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_unicode_sub_super( name, subs, supers, sub_first=True, translate_symbols=True, unicode_sub_super=self._settings['unicode_sub_super'])
Returned a unicodified version of the string
def _braket_fmt(self, expr_type): if self._settings['unicode_sub_super']: sub_sup_fmt = SubSupFmt else: sub_sup_fmt = SubSupFmtNoUni mapping = { 'bra': { True: sub_sup_fmt('⟨{label}|', sup='({space})'), 'subscript': sub_sup_fmt('⟨{label}|', sub='({space})'), False: sub_sup_fmt('⟨{label}|')}, 'ket': { True: sub_sup_fmt('|{label}⟩', sup='({space})'), 'subscript': sub_sup_fmt('|{label}⟩', sub='({space})'), False: sub_sup_fmt('|{label}⟩')}, 'ketbra': { True: sub_sup_fmt('|{label_i}⟩⟨{label_j}|', sup='({space})'), 'subscript': sub_sup_fmt( '|{label_i}⟩⟨{label_j}|', sub='({space})'), False: sub_sup_fmt('|{label_i}⟩⟨{label_j}|')}, 'braket': { True: sub_sup_fmt('⟨{label_i}|{label_j}⟩', sup='({space})'), 'subscript': sub_sup_fmt( '⟨{label_i}|{label_j}⟩', sub='({space})'), False: sub_sup_fmt('⟨{label_i}|{label_j}⟩')}, } hs_setting = bool(self._settings['show_hs_label']) if self._settings['show_hs_label'] == 'subscript': hs_setting = 'subscript' return mapping[expr_type][hs_setting]
Return a format string for printing an `expr_type` ket/bra/ketbra/braket
def _render_op( self, identifier, hs=None, dagger=False, args=None, superop=False): 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 self._settings['unicode_op_hats'] and len(name) == 1: if superop: res = name else: res = modifier_dict['hat'](name) else: res = name res = render_unicode_sub_super( res, [total_subscript], [total_superscript], sub_first=True, translate_symbols=True, unicode_sub_super=self._settings['unicode_sub_super']) res += args_str return res
Render an operator Args: identifier (str or SymbolicLabelBase): The identifier (name/symbol) of the operator. May include a subscript, denoted by '_'. hs (HilbertSpace): The Hilbert space in which the operator is defined dagger (bool): Whether the operator should be daggered args (list): A list of expressions that will be rendered with :meth:`doprint`, joined with commas, enclosed in parenthesis superop (bool): Whether the operator is a super-operator
def PauliX(local_space, states=None): r local_space, states = _get_pauli_args(local_space, states) g, e = states return ( LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))
r"""Pauli-type X-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} on an arbitrary two-level system. Args: local_space (str or int or .LocalSpace): Associated Hilbert space. If :class:`str` or :class:`int`, a :class:`LocalSpace` with a matching label will be created. states (None or tuple[int or str]): The labels for the basis states for the two levels on which the operator acts. If None, the two lowest levels are used. Returns: Operator: Local X-operator as a linear combination of :class:`LocalSigma`
def PauliY(local_space, states=None): r local_space, states = _get_pauli_args(local_space, states) g, e = states return I * (-LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))
r""" Pauli-type Y-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix} on an arbitrary two-level system. See :func:`PauliX`
def PauliZ(local_space, states=None): r local_space, states = _get_pauli_args(local_space, states) g, e = states return ( LocalProjector(g, hs=local_space) - LocalProjector(e, hs=local_space))
r"""Pauli-type Z-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} on an arbitrary two-level system. See :func:`PauliX`
def render_head_repr( expr: Any, sub_render=None, key_sub_render=None) -> str: head_repr_fmt = r'{head}({args}{kwargs})' if sub_render is None: sub_render = render_head_repr if key_sub_render is None: key_sub_render = sub_render if isinstance(expr.__class__, Singleton): # We exploit that Singletons override __expr__ to directly return # their name return repr(expr) if isinstance(expr, Expression): args = expr.args keys = expr.minimal_kwargs.keys() kwargs = '' if len(keys) > 0: kwargs = ", ".join([ "%s=%s" % (key, key_sub_render(expr.kwargs[key])) for key in keys]) if len(args) > 0: kwargs = ", " + kwargs return head_repr_fmt.format( head=expr.__class__.__name__, args=", ".join([sub_render(arg) for arg in args]), kwargs=kwargs) elif isinstance(expr, (tuple, list)): delims = ("(", ")") if isinstance(expr, tuple) else ("[", "]") if len(expr) == 1: delims = (delims[0], "," + delims[1]) return ( delims[0] + ", ".join([ render_head_repr( v, sub_render=sub_render, key_sub_render=key_sub_render) for v in expr]) + delims[1]) else: return sympy_srepr(expr)
Render a textual representation of `expr` using Positional and keyword arguments are recursively rendered using `sub_render`, which defaults to `render_head_repr` by default. If desired, a different renderer may be used for keyword arguments by giving `key_sub_renderer` Raises: AttributeError: if `expr` is not an instance of :class:`Expression`, or more specifically, if `expr` does not have `args` and `kwargs` (respectively `minimal_kwargs`) properties
def derationalize_denom(expr): r_pos = -1 p_pos = -1 numerator = S.Zero denom_sq = S.One post_factors = [] if isinstance(expr, Mul): for pos, factor in enumerate(expr.args): if isinstance(factor, Rational) and r_pos < 0: r_pos = pos numerator, denom_sq = factor.p, factor.q elif isinstance(factor, Pow) and r_pos >= 0: if factor == sqrt(denom_sq): p_pos = pos else: post_factors.append(factor) else: post_factors.append(factor) if r_pos >= 0 and p_pos >= 0: return numerator, denom_sq, Mul(*post_factors) else: raise ValueError("Cannot derationalize") else: raise ValueError("expr is not a Mul instance")
Try to de-rationalize the denominator of the given expression. The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from ``sqrt(2)/2``. Specifically, this matches `expr` against the following pattern:: Mul(..., Rational(n, d), Pow(d, Rational(1, 2)), ...) and returns a tuple ``(numerator, denom_sq, post_factor)``, where ``numerator`` and ``denom_sq`` are ``n`` and ``d`` in the above pattern (of type `int`), respectively, and ``post_factor`` is the product of the remaining factors (``...`` in `expr`). The result will fulfill the following identity:: (numerator / sqrt(denom_sq)) * post_factor == expr If `expr` does not follow the appropriate pattern, a :exc:`ValueError` is raised.
def entries(self): # Since there is currently no filtering in place, return all entries. EntryModel = get_entry_model() qs = get_entry_model().objects.order_by('-publication_date') # Only limit to current language when this makes sense. if issubclass(EntryModel, TranslatableModel): admin_form_language = self.get_current_language() # page object is in current language tab. qs = qs.active_translations(admin_form_language).language(admin_form_language) return qs
Return the entries that are published under this node.
def get_entry_url(self, entry): # It could be possible this page is fetched as fallback, while the 'entry' does have a translation. # - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the language of retrieval # as current object language. The page is not assigned a fallback language instead. # - With i18n_patterns() that would make strange URLs, such as '/en/blog/2016/05/dutch-entry-title/' # Hence, respect the entry language as starting point to make the language consistent. with switch_language(self, entry.get_current_language()): return self.get_absolute_url() + entry.get_relative_url()
Return the URL of a blog entry, relative to this page.
def create_placeholder(self, slot="blog_contents", role='m', title=None): return Placeholder.objects.create_for_object(self, slot, role=role, title=title)
Create a placeholder on this blog entry. To fill the content items, use :func:`ContentItemModel.objects.create_for_placeholder() <fluent_contents.models.managers.ContentItemManager.create_for_placeholder>`. :rtype: :class:`~fluent_contents.models.Placeholder`
def similar_objects(self, num=None, **filters): # TODO: filter appsettings.FLUENT_BLOGS_FILTER_SITE_ID: # filters.setdefault('parent_site', self.parent_site_id) # FIXME: Using super() doesn't work, calling directly. return TagsMixin.similar_objects(self, num=num, **filters)
Find similar objects using related tags.
def save_as_png(self, filename, width=300, height=250, render_time=1): self.driver.set_window_size(width, height) self.driver.get('file://{path}/{filename}'.format( path=os.getcwd(), filename=filename + ".html")) time.sleep(render_time) self.driver.save_screenshot(filename + ".png")
Open saved html file in an virtual browser and save a screen shot to PNG format.
def get_version(filename): with open(filename) as in_fh: for line in in_fh: if line.startswith('__version__'): return line.split('=')[1].strip()[1:-1] raise ValueError("Cannot extract version from %s" % filename)
Extract the package version
def blogurl(parser, token): if HAS_APP_URLS: from fluent_pages.templatetags.appurl_tags import appurl return appurl(parser, token) else: from django.template.defaulttags import url return url(parser, token)
Compatibility tag 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. For the former, URL resolving works via the normal '{% url "viewname" arg1 arg2 %}' syntax. For the latter, the URL resolving works via '{% appurl "viewname" arg1 arg2 %}' syntax.
def format_year(year): if isinstance(year, (date, datetime)): # Django 1.5 and up, 'year' is a date object, consistent with month+day views. return unicode(year.year) else: # Django 1.4 just passes the kwarg as string. return unicode(year)
Format the year value of the ``YearArchiveView``, which can be a integer or date object. This tag is no longer needed, but exists for template compatibility. It was a compatibility tag for Django 1.4.
def free_symbols(self): return set([ sym for sym in self.term.free_symbols if sym not in self.bound_symbols])
Set of all free symbols
def terms(self): from qnet.algebra.core.scalar_algebra import ScalarValue for mapping in yield_from_ranges(self.ranges): term = self.term.substitute(mapping) if isinstance(term, ScalarValue._val_types): term = ScalarValue.create(term) assert isinstance(term, Expression) yield term
Iterator over the terms of the sum Yield from the (possibly) infinite list of terms of the indexed sum, if the sum was written out explicitly. Each yielded term in an instance of :class:`.Expression`
def doit( self, classes=None, recursive=True, indices=None, max_terms=None, **kwargs): return super().doit( classes, recursive, indices=indices, max_terms=max_terms, **kwargs)
Write out the indexed sum explicitly If `classes` is None or :class:`IndexedSum` is in `classes`, (partially) write out the indexed sum in to an explicit sum of terms. If `recursive` is True, write out each of the new sum's summands by calling its :meth:`doit` method. Args: classes (None or list): see :meth:`.Expression.doit` recursive (bool): see :meth:`.Expression.doit` indices (list): List of :class:`IdxSym` indices for which the sum should be expanded. If `indices` is a subset of the indices over which the sum runs, it will be partially expanded. If not given, expand the sum completely max_terms (int): Number of terms after which to truncate the sum. This is particularly useful for infinite sums. If not given, expand all terms of the sum. Cannot be combined with `indices` kwargs: keyword arguments for recursive calls to :meth:`doit`. See :meth:`.Expression.doit`
def make_disjunct_indices(self, *others): new = self other_index_symbols = set() for other in others: try: if isinstance(other, IdxSym): other_index_symbols.add(other) elif isinstance(other, IndexRangeBase): other_index_symbols.add(other.index_symbol) elif hasattr(other, 'ranges'): other_index_symbols.update( [r.index_symbol for r in other.ranges]) else: other_index_symbols.update( [r.index_symbol for r in other]) except AttributeError: raise ValueError( "Each element of other must be an an instance of IdxSym, " "IndexRangeBase, an object with a `ranges` attribute " "with a list of IndexRangeBase instances, or a list of" "IndexRangeBase objects.") for r in self.ranges: index_symbol = r.index_symbol modified = False while index_symbol in other_index_symbols: modified = True index_symbol = index_symbol.incr_primed() if modified: new = new._substitute( {r.index_symbol: index_symbol}, safe=True) return new
Return a copy with modified indices to ensure disjunct indices with `others`. Each element in `others` may be an index symbol (:class:`.IdxSym`), a index-range object (:class:`.IndexRangeBase`) or list of index-range objects, or an indexed operation (something with a ``ranges`` attribute) Each index symbol is primed until it does not match any index symbol in `others`.
def codemirror_field_js_assets(*args): manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.js_html())
Tag to render CodeMirror Javascript assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_js_assets form.myfield1 form.myfield2 %}
def codemirror_field_css_assets(*args): manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.css_html())
Tag to render CodeMirror CSS assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_css_assets form.myfield1 form.myfield2 %}
def codemirror_field_js_bundle(field): manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.js_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFieldBundleError(msg.format(field.config_name)) return bundle_name
Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_js_bundle }} Arguments: field (django.forms.fields.Field): A form field that contains a widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Raises: CodeMirrorFieldBundleError: If Codemirror configuration form field does not have a bundle name. Returns: string: Bundle name to load with webassets.
def codemirror_field_css_bundle(field): manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.css_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFieldBundleError(msg.format(field.config_name)) return bundle_name
Filter to get CodeMirror CSS bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_css_bundle }} Arguments: field (djangocodemirror.fields.CodeMirrorField): A form field. Raises: CodeMirrorFieldBundleError: Raised if Codemirror configuration from field does not have a bundle name. Returns: string: Bundle name to load with webassets.