Python sympy.Basic() Examples
The following are 30
code examples of sympy.Basic().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sympy
, or try the search function
.
Example #1
Source File: flatten_expressions.py From Cirq with Apache License 2.0 | 6 votes |
def transform_params(self, params: resolver.ParamResolverOrSimilarType ) -> resolver.ParamDictType: """Returns a `ParamResolver` to use with a circuit flattened earlier with `cirq.flatten`. If `params` maps symbol `a` to 3.0 and this `ExpressionMap` maps `a/2+1` to `'<a/2 + 1>'` then this method returns a resolver that maps symbol `'<a/2 + 1>'` to 2.5. See `cirq.flatten` for an example. Args: params: The params to transform. """ param_dict = { sym: protocols.resolve_parameters(formula, params) for formula, sym in self.items() if isinstance(sym, sympy.Basic) } return param_dict
Example #2
Source File: wrapped.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def assert_eigengate_implements_consistent_protocols( eigen_gate_type: Type[cirq.EigenGate], *, exponents: Sequence[Union[sympy.Basic, float]] = ( 0, 1, -1, 0.25, -0.5, 0.1, sympy.Symbol('s')), global_shifts: Sequence[float] = (0, -0.5, 0.1), qubit_count: Optional[int] = None, ignoring_global_phase: bool=False, setup_code: str = _setup_code, global_vals: Optional[Dict[str, Any]] = None, local_vals: Optional[Dict[str, Any]] = None) -> None: """Checks that an EigenGate subclass is internally consistent and has a good __repr__.""" cirq.testing.assert_eigengate_implements_consistent_protocols( eigen_gate_type, exponents=exponents, global_shifts=global_shifts, qubit_count=qubit_count, ignoring_global_phase=ignoring_global_phase, setup_code=setup_code, global_vals=global_vals, local_vals=local_vals)
Example #3
Source File: parameters.py From strawberryfields with Apache License 2.0 | 6 votes |
def par_regref_deps(p): """RegRef dependencies of an Operation parameter. Returns the RegRefs that the parameter depends on through the :class:`MeasuredParameter` atoms it contains. Args: p (Any): Operation parameter Returns: set[RegRef]: RegRefs the parameter depends on """ ret = set() if is_object_array(p): # p is an object array, possibly containing symbols for k in p: ret.update(par_regref_deps(k)) elif isinstance(p, sympy.Basic): # p is a Sympy expression, possibly containing measured parameters for k in p.atoms(MeasuredParameter): ret.add(k.regref) return ret
Example #4
Source File: resolve_parameters.py From Cirq with Apache License 2.0 | 6 votes |
def is_parameterized(val: Any) -> bool: """Returns whether the object is parameterized with any Symbols. A value is parameterized when it has an `_is_parameterized_` method and that method returns a truthy value, or if the value is an instance of sympy.Basic. Returns: True if the gate has any unresolved Symbols and False otherwise. If no implementation of the magic method above exists or if that method returns NotImplemented, this will default to False. """ if isinstance(val, sympy.Basic): return True if isinstance(val, (list, tuple)): return any(is_parameterized(e) for e in val) getter = getattr(val, '_is_parameterized_', None) result = NotImplemented if getter is None else getter() if result is not NotImplemented: return result else: return False
Example #5
Source File: parameters.py From strawberryfields with Apache License 2.0 | 6 votes |
def par_convert(args, prog): """Convert Blackbird symbolic Operation arguments into their SF counterparts. Args: args (Iterable[Any]): Operation arguments prog (Program): program containing the Operations. Returns: list[Any]: converted arguments """ def do_convert(a): if isinstance(a, sympy.Basic): # substitute SF symbolic parameter objects for Blackbird ones s = {} for k in a.atoms(sympy.Symbol): if k.name[0] == "q": s[k] = MeasuredParameter(prog.register[int(k.name[1:])]) else: s[k] = prog.params(k.name) # free parameter return a.subs(s) return a # return non-symbols as-is return [do_convert(a) for a in args]
Example #6
Source File: model.py From solowPy with MIT License | 6 votes |
def marginal_product_capital(self): r""" Symbolic expression for the marginal product of capital (per unit effective labor). :getter: Return the current marginal product of capital. :type: sympy.Basic Notes ----- The marginal product of capital is defined as follows: .. math:: \frac{\partial F(K, AL)}{\partial K} \equiv f'(k) where :math:`k=K/AL` is capital stock (per unit effective labor). """ return sym.diff(self.intensive_output, k)
Example #7
Source File: model.py From QuantEcon.lectures.code with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, output, params): """ Create an instance of the Solow growth model. Parameters ---------- output : sym.Basic Symbolic expression defining the aggregate production function. params : dict Dictionary of model parameters. """ self.irf = impulse_response.ImpulseResponse(self) self.output = output self.params = params
Example #8
Source File: parse.py From Cirq with Apache License 2.0 | 6 votes |
def parse_formula(formula: str) -> Union[float, sympy.Basic]: """Attempts to parse formula text in exactly the same way as Quirk.""" if not isinstance(formula, str): raise TypeError('formula must be a string') token_map = {**PARSE_COMPLEX_TOKEN_MAP_RAD, 't': sympy.Symbol('t')} result = _parse_formula_using_token_map(formula, token_map) if isinstance(result, sympy.Basic): if result.free_symbols: return result result = complex(result) if isinstance(result, complex): if abs(np.imag(result)) > 1e-8: raise ValueError('Not a real result.') result = np.real(result) return float(cast(SupportsFloat, result))
Example #9
Source File: model.py From QuantEcon.lectures.code with BSD 3-Clause "New" or "Revised" License | 6 votes |
def marginal_product_capital(self): r""" Symbolic expression for the marginal product of capital (per unit effective labor). :getter: Return the current marginal product of capital (per unit effective labor). :type: sym.Basic Notes ----- The marginal product of capital is defined as follows: .. math:: \frac{\partial F(K, AL)}{\partial K} \equiv f'(k) where :math:`k=K/AL` is capital stock (per unit effective labor) """ return sym.diff(self.intensive_output, k)
Example #10
Source File: phased_x_z_gate.py From Cirq with Apache License 2.0 | 5 votes |
def z_exponent(self) -> Union[numbers.Real, sympy.Basic]: return self._z_exponent
Example #11
Source File: flatten_expressions.py From Cirq with Apache License 2.0 | 5 votes |
def _next_symbol(self, val: sympy.Basic) -> sympy.Symbol: name = self.get_param_name(val) symbol = sympy.Symbol(name) # Ensure the symbol hasn't already been used collision = 0 while symbol in self._taken_symbols: collision += 1 symbol = sympy.Symbol('{}_{}'.format(name, collision)) return symbol
Example #12
Source File: phased_x_z_gate.py From Cirq with Apache License 2.0 | 5 votes |
def with_z_exponent(self, z_exponent: Union[numbers.Real, sympy.Basic] ) -> 'cirq.PhasedXZGate': return PhasedXZGate(axis_phase_exponent=self._axis_phase_exponent, x_exponent=self._x_exponent, z_exponent=z_exponent)
Example #13
Source File: three_qubit_gates.py From Cirq with Apache License 2.0 | 5 votes |
def _is_parameterized_(self): return any( isinstance(angle, sympy.Basic) for angle in self._diag_angles_radians)
Example #14
Source File: three_qubit_gates.py From Cirq with Apache License 2.0 | 5 votes |
def __pow__(self, exponent: Any) -> 'ThreeQubitDiagonalGate': if not isinstance(exponent, (int, float, sympy.Basic)): return NotImplemented return ThreeQubitDiagonalGate([ protocols.mul(angle, exponent, NotImplemented) for angle in self._diag_angles_radians ])
Example #15
Source File: fourier_transform.py From Cirq with Apache License 2.0 | 5 votes |
def __init__(self, *, num_qubits: int, exponent: Union[float, sympy.Basic]): self._num_qubits = num_qubits self.exponent = exponent
Example #16
Source File: _compat.py From Cirq with Apache License 2.0 | 5 votes |
def proper_repr(value: Any) -> str: """Overrides sympy and numpy returning repr strings that don't parse.""" if isinstance(value, sympy.Basic): result = sympy.srepr(value) # HACK: work around https://github.com/sympy/sympy/issues/16074 # (only handles a few cases) fixed_tokens = [ 'Symbol', 'pi', 'Mul', 'Pow', 'Add', 'Mod', 'Integer', 'Float', 'Rational' ] for token in fixed_tokens: result = result.replace(token, 'sympy.' + token) return result if isinstance(value, np.ndarray): return 'np.array({!r}, dtype=np.{})'.format(value.tolist(), value.dtype) if isinstance(value, pd.MultiIndex): return (f'pd.MultiIndex.from_tuples({repr(list(value))}, ' f'names={repr(list(value.names))})') if isinstance(value, pd.Index): return (f'pd.Index({repr(list(value))}, ' f'name={repr(value.name)}, ' f'dtype={repr(str(value.dtype))})') if isinstance(value, pd.DataFrame): cols = [value[col].tolist() for col in value.columns] rows = list(zip(*cols)) return (f'pd.DataFrame(' f'\n columns={proper_repr(value.columns)}, ' f'\n index={proper_repr(value.index)}, ' f'\n data={repr(rows)}' f'\n)') return repr(value)
Example #17
Source File: flatten_expressions.py From Cirq with Apache License 2.0 | 5 votes |
def default_get_param_name(val: sympy.Basic) -> str: if isinstance(val, sympy.Symbol): return val.name return '<{!s}>'.format(val)
Example #18
Source File: flatten_expressions.py From Cirq with Apache License 2.0 | 5 votes |
def __init__( self, param_dict: Optional[resolver.ParamResolverOrSimilarType] = None, *, # Force keyword args get_param_name: Callable[[ sympy.Basic, ], str] = None): """Initializes a new _ParamFlattener. Args: param_dict: A default initial mapping from some parameter names, symbols, or expressions to other symbols or values. Only sympy expressions and symbols not specified in `param_dict` will be flattened. get_param_name: A callback function that returns a new parameter name for a given sympy expression or symbol. If this function returns the same value for two different expressions, `'_#'` is appended to the name to avoid name collision where `#` is the number of previous collisions. By default, returns the expression string surrounded by angle brackets e.g. `'<x+1>'`. """ if hasattr(self, '_taken_symbols'): # Has already been initialized return if isinstance(param_dict, resolver.ParamResolver): params = param_dict.param_dict else: params = param_dict if param_dict else {} symbol_params = { _ensure_not_str(param): _ensure_not_str(val) for param, val in params.items() } super().__init__(symbol_params) if get_param_name is None: get_param_name = self.default_get_param_name self.get_param_name = get_param_name self._taken_symbols = set(self.param_dict.values())
Example #19
Source File: fourier_transform.py From Cirq with Apache License 2.0 | 5 votes |
def _is_parameterized_(self): return isinstance(self.exponent, sympy.Basic)
Example #20
Source File: phased_x_z_gate.py From Cirq with Apache License 2.0 | 5 votes |
def x_exponent(self) -> Union[numbers.Real, sympy.Basic]: return self._x_exponent
Example #21
Source File: phased_x_z_gate.py From Cirq with Apache License 2.0 | 5 votes |
def __init__(self, *, x_exponent: Union[numbers.Real, sympy.Basic], z_exponent: Union[numbers.Real, sympy.Basic], axis_phase_exponent: Union[numbers.Real, sympy.Basic]) -> None: """ Args: x_exponent: Determines how much to rotate during the axis-in-XY-plane rotation. The $x$ in $Z^z Z^a X^x Z^{-a}$. z_exponent: The amount of phasing to apply after the axis-in-XY-plane rotation. The $z$ in $Z^z Z^a X^x Z^{-a}$. axis_phase_exponent: Determines which axis to rotate around during the axis-in-XY-plane rotation. The $a$ in $Z^z Z^a X^x Z^{-a}$. """ self._x_exponent = x_exponent self._z_exponent = z_exponent self._axis_phase_exponent = axis_phase_exponent
Example #22
Source File: phased_x_gate.py From Cirq with Apache License 2.0 | 5 votes |
def _canonical_exponent(self): period = self._period() if not period or isinstance(self._exponent, sympy.Basic): return self._exponent return self._exponent % period
Example #23
Source File: identity.py From Cirq with Apache License 2.0 | 5 votes |
def __pow__(self, power: Any) -> Any: if isinstance(power, (int, float, complex, sympy.Basic)): return self return NotImplemented
Example #24
Source File: angle.py From Cirq with Apache License 2.0 | 5 votes |
def canonicalize_half_turns(half_turns: sympy.Basic) -> sympy.Basic: pass
Example #25
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def __truediv__(self, other) -> Union['Duration', float]: if isinstance(other, (int, float, sympy.Basic)): return Duration(picos=self._picos / other) other_duration = _attempt_duration_like_to_duration(other) if other_duration is not None: return self._picos / other_duration._picos return NotImplemented
Example #26
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def __mul__(self, other) -> 'Duration': if not isinstance(other, (int, float, sympy.Basic)): return NotImplemented return Duration(picos=self._picos * other)
Example #27
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def total_millis(self) -> Union[sympy.Basic, float]: """Returns the number of milliseconds that the duration spans.""" return self._picos / 1000_000_000
Example #28
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def total_micros(self) -> Union[sympy.Basic, float]: """Returns the number of microseconds that the duration spans.""" return self._picos / 1000_000
Example #29
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def total_picos(self) -> Union[sympy.Basic, float]: """Returns the number of picoseconds that the duration spans.""" return self._picos
Example #30
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def __init__( self, value: DURATION_LIKE = None, *, # Force keyword args. picos: Union[int, float, sympy.Basic] = 0, nanos: Union[int, float, sympy.Basic] = 0, micros: Union[int, float, sympy.Basic] = 0, millis: Union[int, float, sympy.Basic] = 0) -> None: """Initializes a Duration with a time specified in some unit. If multiple arguments are specified, their contributions are added. Args: value: A value with a pre-specified time unit. Currently only supports 0 and `datetime.timedelta` instances. picos: A number of picoseconds to add to the time delta. nanos: A number of nanoseconds to add to the time delta. micros: A number of microseconds to add to the time delta. millis: A number of milliseconds to add to the time delta. Examples: >>> print(cirq.Duration(nanos=100)) 100 ns >>> print(cirq.Duration(micros=1.5 * sympy.Symbol('t'))) (1500.0*t) ns """ if value is not None and value != 0: if isinstance(value, datetime.timedelta): # timedelta has microsecond resolution. micros += int(value / datetime.timedelta(microseconds=1)) elif isinstance(value, Duration): picos += value._picos else: raise TypeError(f'Not a `cirq.DURATION_LIKE`: {repr(value)}.') self._picos: Union[float, int, sympy.Basic] = (picos + nanos * 1000 + micros * 1000_000 + millis * 1000_000_000)