本文整理汇总了Python中sympy.Symbol方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.Symbol方法的具体用法?Python sympy.Symbol怎么用?Python sympy.Symbol使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy
的用法示例。
在下文中一共展示了sympy.Symbol方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_quadratic_fermionic_simulation_gate_unitary
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def test_quadratic_fermionic_simulation_gate_unitary(weights, exponent):
generator = np.zeros((4, 4), dtype=np.complex128)
# w0 |10><01| + h.c.
generator[2, 1] = weights[0]
generator[1, 2] = weights[0].conjugate()
# w1 |11><11|
generator[3, 3] = weights[1]
expected_unitary = la.expm(-1j * exponent * generator)
gate = ofc.QuadraticFermionicSimulationGate(weights, exponent=exponent)
actual_unitary = cirq.unitary(gate)
assert np.allclose(expected_unitary, actual_unitary)
symbolic_gate = (ofc.QuadraticFermionicSimulationGate(
(sympy.Symbol('w0'), sympy.Symbol('w1')), exponent=sympy.Symbol('t')))
qubits = cirq.LineQubit.range(2)
circuit = cirq.Circuit(symbolic_gate._decompose_(qubits))
resolver = {'w0': weights[0], 'w1': weights[1], 't': exponent}
resolved_circuit = cirq.resolve_parameters(circuit, resolver)
decomp_unitary = resolved_circuit.unitary(qubit_order=qubits)
assert np.allclose(expected_unitary, decomp_unitary)
示例2: test_cubic_fermionic_simulation_gate_equality
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def test_cubic_fermionic_simulation_gate_equality():
eq = cirq.testing.EqualsTester()
eq.add_equality_group(
ofc.CubicFermionicSimulationGate()**0.5,
ofc.CubicFermionicSimulationGate((1,) * 3, exponent=0.5),
ofc.CubicFermionicSimulationGate((0.5,) * 3),
)
eq.add_equality_group(ofc.CubicFermionicSimulationGate((1j, 0, 0)),)
eq.add_equality_group(
ofc.CubicFermionicSimulationGate((sympy.Symbol('s'), 0, 0), exponent=2),
ofc.CubicFermionicSimulationGate((2 * sympy.Symbol('s'), 0, 0),
exponent=1),
)
eq.add_equality_group(
ofc.CubicFermionicSimulationGate((0, 0.7, 0), global_shift=2),
ofc.CubicFermionicSimulationGate((0, 0.35, 0),
global_shift=1,
exponent=2),
)
eq.add_equality_group(
ofc.CubicFermionicSimulationGate((1, 1, 1)),
ofc.CubicFermionicSimulationGate(((1 + 2 * np.pi), 1, 1)),
)
示例3: test_swap_network_trotter_ansatz_params
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def test_swap_network_trotter_ansatz_params():
ansatz = SwapNetworkTrotterAnsatz(hubbard_hamiltonian)
assert (set(ansatz.params()) ==
{sympy.Symbol(name) for name in
{'T_0_2_0', 'T_4_6_0', 'T_1_3_0', 'T_5_7_0',
'T_0_4_0', 'T_2_6_0', 'T_1_5_0', 'T_3_7_0',
'V_0_1_0', 'V_2_3_0', 'V_4_5_0', 'V_6_7_0'}})
ansatz = SwapNetworkTrotterAnsatz(hubbard_hamiltonian, iterations=2)
assert (set(ansatz.params()) ==
{sympy.Symbol(name) for name in
{'T_0_2_0', 'T_4_6_0', 'T_1_3_0', 'T_5_7_0',
'T_0_4_0', 'T_2_6_0', 'T_1_5_0', 'T_3_7_0',
'V_0_1_0', 'V_2_3_0', 'V_4_5_0', 'V_6_7_0',
'T_0_2_1', 'T_4_6_1', 'T_1_3_1', 'T_5_7_1',
'T_0_4_1', 'T_2_6_1', 'T_1_5_1', 'T_3_7_1',
'V_0_1_1', 'V_2_3_1', 'V_4_5_1', 'V_6_7_1'}})
示例4: test_low_rank_trotter_ansatz_params
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def test_low_rank_trotter_ansatz_params():
n = openfermion.count_qubits(lih_hamiltonian)
final_rank = 2
ansatz = LowRankTrotterAnsatz(
lih_hamiltonian,
final_rank=final_rank,
include_all_cz=True,
include_all_z=True)
assert len(list(ansatz.params())) == n + final_rank*(n + n*(n-1)//2)
ansatz = LowRankTrotterAnsatz(lih_hamiltonian, final_rank=2)
assert set(ansatz.params()) == {
sympy.Symbol(name) for name in {
'U_0_0', 'U_0_0_0', 'U_0_1_0', 'U_1_0',
'U_1_0_0', 'U_1_1_0', 'U_2_0', 'U_2_0_0',
'U_2_1_0', 'U_3_0', 'U_3_0_0', 'U_3_1_0',
'V_0_1_0_0', 'V_0_1_1_0', 'V_0_2_0_0', 'V_0_2_1_0',
'V_0_3_0_0', 'V_0_3_1_0', 'V_1_2_0_0', 'V_1_2_1_0',
'V_1_3_0_0', 'V_1_3_1_0', 'V_2_3_0_0', 'V_2_3_1_0'
}
}
示例5: assert_implements_consistent_protocols
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def assert_implements_consistent_protocols(
val: Any,
*,
exponents: Sequence[Any] = (
0, 1, -1, 0.5, 0.25, -0.5, 0.1, sympy.Symbol('s')),
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 a value is internally consistent and has a good __repr__."""
cirq.testing.assert_implements_consistent_protocols(
val,
exponents=exponents,
qubit_count=qubit_count,
ignoring_global_phase=ignoring_global_phase,
setup_code=setup_code,
global_vals=global_vals,
local_vals=local_vals)
示例6: assert_eigengate_implements_consistent_protocols
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
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)
示例7: sequence_nth_term
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def sequence_nth_term(min_entropy, max_entropy):
"""E.g., "What is the nth term in the sequence 1, 2, 3?"."""
entropy = random.uniform(min_entropy, max_entropy)
context = composition.Context()
variable = sympy.Symbol(context.pop())
sequence = _PolynomialSequence(variable, entropy)
min_num_terms = sequence.min_num_terms
num_terms = random.randint(min_num_terms, min_num_terms + 3)
sequence_sample = [sequence.term(n + 1) for n in range(num_terms)]
sequence_sample = display.NumberList(sequence_sample)
template = random.choice([
'What is the {variable}\'th term of {sequence}?',
])
answer = sequence.sympy
return example.Problem(
question=example.question(
context, template, variable=variable, sequence=sequence_sample),
answer=answer)
示例8: expand
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def expand(value, sample_args, context=None):
"""E.g., "Expand (x**2 + 1)**2."."""
del value # not used
if context is None:
context = composition.Context()
variable = sympy.Symbol(context.pop())
entropy, sample_args = sample_args.peel()
min_order = 1
max_order = 5
order = random.randint(min_order, max_order)
entropy -= math.log10(max_order - min_order + 1)
expression_ = polynomials.sample_with_brackets(variable, order, entropy)
expanded = sympy.expand(expression_)
template = random.choice([
'Expand {expression}.'
])
return example.Problem(
question=example.question(context, template, expression=expression_),
answer=expanded)
示例9: testDiv
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def testDiv(self):
div = ops.Div(2, 3)
self.assertEqual(str(div), '2/3')
self.assertEqual(div.sympy(), sympy.Rational(2, 3))
div = ops.Div(2, sympy.Rational(4, 5))
self.assertEqual(str(div), '2/(4/5)')
self.assertEqual(div.sympy(), sympy.Rational(5, 2))
div = ops.Div(1, ops.Div(2, 3))
self.assertEqual(str(div), '1/(2/3)')
self.assertEqual(div.sympy(), sympy.Rational(3, 2))
div = ops.Div(ops.Div(2, 3), 4)
self.assertEqual(str(div), '(2/3)/4')
self.assertEqual(div.sympy(), sympy.Rational(1, 6))
div = ops.Div(2, ops.Mul(3, 4))
self.assertEqual(str(div), '2/(3*4)')
div = ops.Div(2, sympy.Function('f')(sympy.Symbol('x')))
self.assertEqual(str(div), '2/f(x)')
示例10: coefficients_to_polynomial
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def coefficients_to_polynomial(coefficients, variables):
"""Converts array of lists of coefficients to a polynomial."""
coefficients = np.asarray(coefficients)
shape = coefficients.shape
indices = list(zip(*np.indices(shape).reshape([len(shape), -1])))
monomials = []
for power in indices:
coeffs = coefficients.item(power)
if (number.is_integer_or_rational(coeffs)
or isinstance(coeffs, sympy.Symbol)):
coeffs = [coeffs]
elif not isinstance(coeffs, list):
raise ValueError('Unrecognized coeffs={} type={}'
.format(coeffs, type(coeffs)))
for coeff in coeffs:
monomials.append(monomial(coeff, variables, power))
random.shuffle(monomials)
return ops.Add(*monomials)
示例11: subs_bilinear
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def subs_bilinear(expr):
"""
Substitutes bilinear forms from an expression with dedicated variables
:param expr:
:return:
"""
bilinear_ix = [isinstance(x,sympy.Mul) for e,x in enumerate(expr.args)]
new_expr = expr.copy()
replacement_dict = dict()
for bix in bilinear_ix:
term = expr.args[bix]
name = '__MUL__'.join(term.args)
z = sympy.Symbol(name = name)
new_expr = new_expr.subs(term,z)
replacement_dict[term] = z
return new_expr, replacement_dict
示例12: par_convert
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
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]
示例13: solve
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def solve(jarvis, s):
"""
Prints where expression equals zero
-- Example:
solve x**2 + 5*x + 3
solve x + 3 = 5
"""
x = sympy.Symbol('x')
def _format(solutions):
if solutions == 0:
return "No solution!"
ret = ''
for count, point in enumerate(solutions):
if x not in point:
return "Please use 'x' in expression."
x_value = point[x]
ret += "{}. x: {}\n".format(count, x_value)
return ret
def _calc(expr):
return sympy.solve(expr, x, dict=True)
s = remove_equals(jarvis, s)
calc(jarvis, s, calculator=_calc, formatter=_format, do_evalf=False)
示例14: _print_MatrixElement
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def _print_MatrixElement(self, expr):
from sympy.matrices import MatrixSymbol
from sympy import Symbol
if (isinstance(expr.parent, MatrixSymbol)
and expr.i.is_number and expr.j.is_number):
return self._print(
Symbol(expr.parent.name + '_%d%d'%(expr.i, expr.j)))
else:
prettyFunc = self._print(expr.parent)
prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', '
).parens(left='[', right=']')[0]
pform = prettyForm(binding=prettyForm.FUNC,
*stringPict.next(prettyFunc, prettyIndices))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyIndices
return pform
示例15: _print_Function
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Symbol [as 别名]
def _print_Function(self, e, sort=False):
# XXX works only for applied functions
func = e.func
args = e.args
if sort:
args = sorted(args, key=default_sort_key)
func_name = func.__name__
prettyFunc = self._print(C.Symbol(func_name))
prettyArgs = prettyForm(*self._print_seq(args).parens())
#postioning func_name
mid = prettyArgs.height()//2
if mid > 2:
prettyFunc.baseline = -mid + 1
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform